frist commit

This commit is contained in:
zhangwenjian committed 2020-03-13 17:37:11 +08:00
commit 2c78861ee6
1548 files changed
+507028

No files matched your search

+42
View File
@@ -0,0 +1,42 @@
package middleware
import (
config2 "goadmin/config"
"goadmin/handler"
jwt "goadmin/pkg/jwtauth"
"time"
)
func AuthInit() (*jwt.GinJWTMiddleware, error) {
// the jwt middleware
return jwt.New(&jwt.GinJWTMiddleware{
Realm: "test zone",
Key: []byte("secret key"),
Timeout: time.Hour,
MaxRefresh: time.Hour,
IdentityKey: config2.ApplicationConfig.JwtSecret,
PayloadFunc: handler.PayloadFunc,
IdentityHandler: handler.IdentityHandler,
Authenticator: handler.Authenticator,
Authorizator: handler.Authorizator,
Unauthorized: handler.Unauthorized,
// TokenLookup is a string in the form of "<source>:<name>" that is used
// to extract token from the request.
// Optional. Default value "header:Authorization".
// Possible values:
// - "header:<name>"
// - "query:<name>"
// - "cookie:<name>"
// - "param:<name>"
TokenLookup: "header: Authorization, query: token, cookie: jwt",
// TokenLookup: "query:token",
// TokenLookup: "cookie:token",
// TokenHeadName is a string in the header. Default value is "Bearer"
TokenHeadName: "Bearer",
// TimeFunc provides the current time. You can override it to use another time value. This is useful for testing or if your server uses a different time zone than your tokens.
TimeFunc: time.Now,
})
}
@@ -0,0 +1,49 @@
package middleware
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
"strconv"
"strings"
"time"
)
func CustomError(c *gin.Context) {
defer func() {
if err := recover(); err != nil {
if c.IsAborted() {
c.Status(200)
}
switch errStr := err.(type) {
case string:
p := strings.Split(errStr, "#")
if len(p) == 3 && p[0] == "CustomError" {
statusCode, e := strconv.Atoi(p[1])
if e != nil {
break
}
c.Status(statusCode)
fmt.Println(
time.Now().Format("\n 2006-01-02 15:04:05.9999"),
"[ERROR]",
c.Request.Method,
c.Request.URL,
statusCode,
c.Request.RequestURI,
c.ClientIP(),
p[2],
)
c.JSON(http.StatusOK, gin.H{
"code": statusCode,
"msg": p[2],
})
}
default:
panic(err)
}
}
}()
c.Next()
}
+27
View File
@@ -0,0 +1,27 @@
package middleware
import (
"github.com/gin-gonic/gin"
"goadmin/config"
"net/http"
)
func DemoEvn() gin.HandlerFunc {
return func(c *gin.Context) {
if config.ApplicationConfig.Env == "demo" {
method := c.Request.Method
if method == "GET" || method == "OPTIONS" || c.Request.RequestURI == "/login" || c.Request.RequestURI == "/logout" {
c.Next()
} else {
c.JSON(http.StatusOK, gin.H{
"code": 500,
"msg": config.ApplicationConfig.EnvMsg,
})
c.Abort()
return
}
} else {
c.Next()
}
}
}
+47
View File
@@ -0,0 +1,47 @@
package middleware
import (
"github.com/gin-gonic/gin"
"net/http"
"time"
)
// NoCache is a middleware function that appends headers
// to prevent the client from caching the HTTP response.
func NoCache(c *gin.Context) {
c.Header("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate, value")
c.Header("Expires", "Thu, 01 Jan 1970 00:00:00 GMT")
c.Header("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
c.Next()
}
// Options is a middleware function that appends headers
// for options requests and aborts then exits the middleware
// chain and ends the request.
func Options(c *gin.Context) {
if c.Request.Method != "OPTIONS" {
c.Next()
} else {
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE,OPTIONS")
c.Header("Access-Control-Allow-Headers", "authorization, origin, content-type, accept")
c.Header("Allow", "HEAD,GET,POST,PUT,PATCH,DELETE,OPTIONS")
c.Header("Content-Type", "application/json")
c.AbortWithStatus(200)
}
}
// Secure is a middleware function that appends security
// and resource access headers.
func Secure(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "*")
//c.Header("X-Frame-Options", "DENY")
c.Header("X-Content-Type-Options", "nosniff")
c.Header("X-XSS-Protection", "1; mode=block")
if c.Request.TLS != nil {
c.Header("Strict-Transport-Security", "max-age=31536000")
}
// Also consider adding Content-Security-Policy headers
// c.Header("Content-Security-Policy", "script-src 'self' https://cdnjs.cloudflare.com")
}
+97
View File
@@ -0,0 +1,97 @@
package middleware
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"goadmin/config"
"goadmin/models"
"goadmin/utils"
"os"
"time"
)
// 日志记录到文件
func LoggerToFile() gin.HandlerFunc {
//写入文件
src, err := os.OpenFile(config.ApplicationConfig.LogPath, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
if err != nil {
fmt.Println("err", err)
}
//实例化
logger := logrus.New()
//设置输出
logger.Out = src
//设置日志级别
logger.SetLevel(logrus.DebugLevel)
//设置日志格式
logger.SetFormatter(&logrus.TextFormatter{})
return func(c *gin.Context) {
// 开始时间
startTime := time.Now()
// 处理请求
c.Next()
// 结束时间
endTime := time.Now()
// 执行时间
latencyTime := endTime.Sub(startTime)
// 请求方式
reqMethod := c.Request.Method
// 请求路由
reqUri := c.Request.RequestURI
// 状态码
statusCode := c.Writer.Status()
// 请求IP
clientIP := c.ClientIP()
// 日志格式
logger.Infof(" %3d %13v %15s %s %s\r\n",
statusCode,
latencyTime,
clientIP,
reqMethod,
reqUri,
)
logger.Infoln()
fmt.Println(
startTime.Format("\n2006-01-02 15:04:05.9999"),
"[INFO]",
reqMethod,
reqUri,
statusCode,
latencyTime,
reqUri,
clientIP,
)
if c.Request.Method != "GET" && c.Request.Method != "OPTIONS" {
SysOperLog := models.SysOperLog{}
SysOperLog.OperIp = clientIP
SysOperLog.OperLocation = utils.GetLocation(clientIP)
SysOperLog.Status = utils.IntToString(statusCode)
SysOperLog.OperName = utils.GetUserName(c)
SysOperLog.RequestMethod = c.Request.Method
SysOperLog.OperUrl = reqUri
SysOperLog.Method = reqMethod
b, _ := c.Get("body")
SysOperLog.OperParam, _ = utils.StructToJsonStr(b)
SysOperLog.CreateBy = utils.GetCurrntTime()
SysOperLog.OperTime = utils.GetCurrntTime()
SysOperLog.LatencyTime = (latencyTime).String()
SysOperLog.UserAgent = c.Request.UserAgent()
_, _ = SysOperLog.Create()
}
}
}
@@ -0,0 +1,37 @@
package middleware
import (
"github.com/gin-gonic/gin"
mycasbin "goadmin/pkg/casbin"
"goadmin/pkg/jwtauth"
_ "goadmin/pkg/jwtauth"
"log"
"net/http"
)
//权限检查中间件
func AuthCheckRole() gin.HandlerFunc {
return func(c *gin.Context) {
//根据上下文获取载荷claims 从claims获得role
//claims := c.MustGet("claims").(*jwt.MapClaims)
data, _ := c.Get("JWT_PAYLOAD")
v := data.(jwtauth.MapClaims)
e, _ := mycasbin.Casbin()
//检查权限
res, err := e.Enforce(v["rolekey"], c.Request.URL.Path, c.Request.Method)
log.Println("----------------", v["rolekey"], c.Request.URL.Path, c.Request.Method)
if err != nil {
log.Println(err.Error())
}
if res {
c.Next()
} else {
c.JSON(http.StatusOK, gin.H{
"status": 401,
"msg": "对不起,您没有该接口访问权限,请联系管理员",
})
c.Abort()
return
}
}
}
@@ -0,0 +1,26 @@
package middleware
import (
"github.com/gin-gonic/gin"
"github.com/satori/go.uuid"
)
func RequestId() gin.HandlerFunc {
return func(c *gin.Context) {
// Check for incoming header, use it if exists
requestId := c.Request.Header.Get("X-Request-Id")
// Create request id with UUID4
if requestId == "" {
u4 := uuid.NewV4()
requestId = u4.String()
}
// Expose it for use in the application
c.Set("X-Request-Id", requestId)
// Set X-Request-Id header
c.Writer.Header().Set("X-Request-Id", requestId)
c.Next()
}
}
+208
View File
@@ -0,0 +1,208 @@
package router
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/spf13/viper"
"github.com/swaggo/gin-swagger"
"github.com/swaggo/gin-swagger/swaggerFiles"
. "goadmin/apis"
_ "goadmin/docs"
"goadmin/handler"
"goadmin/handler/sd"
_ "goadmin/pkg/jwtauth"
"goadmin/router/middleware"
"log"
)
func InitRouter() *gin.Engine {
r := gin.New()
r.Use(middleware.LoggerToFile())
r.Use(middleware.CustomError)
r.Use(middleware.NoCache)
r.Use(middleware.Options)
r.Use(middleware.Secure)
r.Use(middleware.RequestId())
r.Use(middleware.DemoEvn())
r.Static("/static", "./static")
r.GET("/info", Ping)
r.GET("/heath", Heath)
// 监控信息
svcd := r.Group("/sd")
{
svcd.GET("/health", sd.HealthCheck)
svcd.GET("/disk", sd.DiskCheck)
svcd.GET("/cpu", sd.CPUCheck)
svcd.GET("/ram", sd.RAMCheck)
svcd.GET("/os", sd.OSCheck)
}
// the jwt middleware
authMiddleware, err := middleware.AuthInit()
if err != nil {
_ = fmt.Errorf("JWT Error", err.Error())
}
r.POST("/login", authMiddleware.LoginHandler)
r.POST("/logout", handler.LogOut)
// Refresh time can be longer than token timeout
r.GET("/refresh_token", authMiddleware.RefreshHandler)
//r.GET("/dashboard", Dashboard)
r.GET("/routes", Dashboard)
apiv1 := r.Group("/api/v1")
{
apiv1.GET("/getCaptcha", GenerateCaptchaHandler)
apiv1.GET("/menuTreeselect", GetMenuTreeelect)
apiv1.GET("/rolemenu", GetRoleMenu)
apiv1.POST("/rolemenu", InsertRoleMenu)
apiv1.DELETE("/rolemenu/:id", DeleteRoleMenu)
apiv1.GET("/dict/databytype/:dictType", GetDictDataByDictType)
}
auth := r.Group("/api/v1")
auth.Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
{
auth.GET("/deptList", GetDeptList)
auth.GET("/deptTree", GetDeptTree)
auth.GET("/dept/:deptId", GetDept)
auth.POST("/dept", InsertDept)
auth.PUT("/dept", UpdateDept)
auth.DELETE("/dept/:id", DeleteDept)
auth.GET("/dict/datalist", GetDictDataList)
auth.GET("/dict/data/:dictCode", GetDictData)
auth.POST("/dict/data", InsertDictData)
auth.PUT("/dict/data/", UpdateDictData)
auth.DELETE("/dict/data/:dictCode", DeleteDictData)
auth.GET("/dict/typelist", GetDictTypeList)
auth.GET("/dict/type/:dictId", GetDictType)
auth.POST("/dict/type", InsertDictType)
auth.PUT("/dict/type", UpdateDictType)
auth.DELETE("/dict/type/:dictId", DeleteDictType)
auth.GET("/sysUserList", GetSysUserList)
auth.GET("/sysUser/:userId", GetSysUser)
auth.GET("/sysUser/", GetSysUserInit)
auth.POST("/sysUser", InsertSysUser)
auth.PUT("/sysUser", UpdateSysUser)
auth.DELETE("/sysUser/:userId", DeleteSysUser)
auth.GET("/rolelist", GetRoleList)
auth.GET("/role/:roleId", GetRole)
auth.POST("/role", InsertRole)
auth.PUT("/role", UpdateRole)
auth.PUT("/roledatascope", UpdateRoleDataScope)
auth.DELETE("/role/:roleId", DeleteRole)
auth.GET("/configList", GetConfigList)
auth.GET("/config/:configId", GetConfig)
auth.POST("/config", InsertConfig)
auth.PUT("/config", UpdateConfig)
auth.DELETE("/config/:configId", DeleteConfig)
auth.GET("/roleMenuTreeselect/:roleId", GetMenuTreeRoleselect)
auth.GET("/roleDeptTreeselect/:roleId", GetDeptTreeRoleselect)
auth.GET("/getinfo", GetInfo)
auth.GET("/user/profile", GetSysUserProfile)
auth.GET("/postlist", GetPostList)
auth.GET("/post/:postId", GetPost)
auth.POST("/post", InsertPost)
auth.PUT("/post", UpdatePost)
auth.DELETE("/post/:postId", DeletePost)
auth.GET("/menulist", GetMenuList)
auth.GET("/menu/:id", GetMenu)
auth.POST("/menu", InsertMenu)
auth.PUT("/menu", UpdateMenu)
auth.DELETE("/menu/:id", DeleteMenu)
auth.GET("/menurole", GetMenuRole)
auth.GET("/menuids", GetMenuIDS)
auth.GET("/loginloglist", GetLoginLogList)
auth.GET("/loginlog/:infoId", GetLoginLog)
auth.POST("/loginlog", InsertLoginLog)
auth.PUT("/loginlog", UpdateLoginLog)
auth.DELETE("/loginlog/:infoId", DeleteLoginLog)
auth.GET("/operloglist", GetOperLogList)
auth.GET("/operlog/:operId", GetOperLog)
auth.DELETE("/operlog/:operId", DeleteOperLog)
auth.GET("/configKey/:configKey", GetConfigByConfigKey)
}
//r.NoRoute(authMiddleware.MiddlewareFunc(), NoFound)
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
return r
}
func Ping(c *gin.Context) {
log.Println(viper.GetString(`settings.database.type`))
c.JSON(200, gin.H{
"message": "ok",
})
}
func Heath(c *gin.Context) {
c.JSON(200, gin.H{
"status": "UP",
})
}
func Dashboard(c *gin.Context) {
var user = make(map[string]interface{})
user["login_name"] = "admin"
user["user_id"] = 1
user["user_name"] = "管理员"
user["dept_id"] = 1
var cmenuList = make(map[string]interface{})
cmenuList["children"] = nil
cmenuList["parent_id"] = 1
cmenuList["title"] = "用户管理"
cmenuList["name"] = "Sysuser"
cmenuList["icon"] = "user"
cmenuList["order_num"] = 1
cmenuList["id"] = 4
cmenuList["path"] = "sysuser"
cmenuList["component"] = "sysuser/index"
var lista = make([]interface{}, 1)
lista[0] = cmenuList
var menuList = make(map[string]interface{})
menuList["children"] = lista
menuList["parent_id"] = 1
menuList["name"] = "Upms"
menuList["title"] = "权限管理"
menuList["icon"] = "example"
menuList["order_num"] = 1
menuList["id"] = 4
menuList["path"] = "/upms"
menuList["component"] = "Layout"
var list = make([]interface{}, 1)
list[0] = menuList
var data = make(map[string]interface{})
data["user"] = user
data["menuList"] = list
var r = make(map[string]interface{})
r["code"] = 200
r["data"] = data
c.JSON(200, r)
}