From f25da5f1eecdfc405f884ea2a9eb40b9181c9c22 Mon Sep 17 00:00:00 2001 From: zhangwenjian Date: Mon, 13 Apr 2020 00:13:35 +0800 Subject: [PATCH] =?UTF-8?q?=E8=B0=83=E6=95=B4=E4=B8=AD=E9=97=B4=E4=BB=B6?= =?UTF-8?q?=E7=BB=93=E6=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- router/middleware/auth.go | 42 ---------- router/middleware/customerror.go | 49 ------------ router/middleware/demo.go | 27 ------- router/middleware/header.go | 47 ------------ router/middleware/logger.go | 128 ------------------------------- router/middleware/permission.go | 37 --------- router/middleware/requestid.go | 26 ------- 7 files changed, 356 deletions(-) delete mode 100644 router/middleware/auth.go delete mode 100644 router/middleware/customerror.go delete mode 100644 router/middleware/demo.go delete mode 100644 router/middleware/header.go delete mode 100644 router/middleware/logger.go delete mode 100644 router/middleware/permission.go delete mode 100644 router/middleware/requestid.go diff --git a/router/middleware/auth.go b/router/middleware/auth.go deleted file mode 100644 index a396791..0000000 --- a/router/middleware/auth.go +++ /dev/null @@ -1,42 +0,0 @@ -package middleware - -import ( - config2 "go-admin/config" - "go-admin/handler" - jwt "go-admin/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 ":" that is used - // to extract token from the request. - // Optional. Default value "header:Authorization". - // Possible values: - // - "header:" - // - "query:" - // - "cookie:" - // - "param:" - 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, - }) - -} diff --git a/router/middleware/customerror.go b/router/middleware/customerror.go deleted file mode 100644 index 5fbd99d..0000000 --- a/router/middleware/customerror.go +++ /dev/null @@ -1,49 +0,0 @@ -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() -} diff --git a/router/middleware/demo.go b/router/middleware/demo.go deleted file mode 100644 index 0448f72..0000000 --- a/router/middleware/demo.go +++ /dev/null @@ -1,27 +0,0 @@ -package middleware - -import ( - "github.com/gin-gonic/gin" - "go-admin/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 == "/api/v1/logout" { - c.Next() - } else { - c.JSON(http.StatusOK, gin.H{ - "code": 500, - "msg": config.ApplicationConfig.EnvMsg, - }) - c.Abort() - return - } - } else { - c.Next() - } - } -} diff --git a/router/middleware/header.go b/router/middleware/header.go deleted file mode 100644 index 6ece741..0000000 --- a/router/middleware/header.go +++ /dev/null @@ -1,47 +0,0 @@ -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") -} diff --git a/router/middleware/logger.go b/router/middleware/logger.go deleted file mode 100644 index 25574c0..0000000 --- a/router/middleware/logger.go +++ /dev/null @@ -1,128 +0,0 @@ -package middleware - -import ( - "fmt" - "github.com/gin-gonic/gin" - "github.com/sirupsen/logrus" - "go-admin/config" - "go-admin/models" - "go-admin/utils" - "os" - "strings" - "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" { - menu := models.Menu{} - menu.Path = reqUri - menu.Action = reqMethod - menuList, _ := menu.Get() - 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 - if reqUri == "/login" { - sysOperLog.BusinessType = "10" - sysOperLog.Title = "用户登录" - sysOperLog.OperName = "-" - } else if strings.Contains(reqUri, "/api/v1/logout") { - sysOperLog.BusinessType = "11" - } else if strings.Contains(reqUri, "/api/v1/getCaptcha") { - sysOperLog.BusinessType = "12" - sysOperLog.Title = "验证码" - } else { - if reqMethod == "POST" { - sysOperLog.BusinessType = "1" - } else if reqMethod == "PUT" { - sysOperLog.BusinessType = "2" - } else if reqMethod == "DELETE" { - sysOperLog.BusinessType = "3" - } - } - sysOperLog.Method = reqMethod - if len(menuList) > 0 { - sysOperLog.Title = menuList[0].Title - } - 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() - if c.Err() == nil { - sysOperLog.Status = "0" - } else { - sysOperLog.Status = "1" - } - _, _ = sysOperLog.Create() - } - } -} diff --git a/router/middleware/permission.go b/router/middleware/permission.go deleted file mode 100644 index 0de7220..0000000 --- a/router/middleware/permission.go +++ /dev/null @@ -1,37 +0,0 @@ -package middleware - -import ( - "github.com/gin-gonic/gin" - mycasbin "go-admin/pkg/casbin" - "go-admin/pkg/jwtauth" - _ "go-admin/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 - } - } -} diff --git a/router/middleware/requestid.go b/router/middleware/requestid.go deleted file mode 100644 index 7ab5f7a..0000000 --- a/router/middleware/requestid.go +++ /dev/null @@ -1,26 +0,0 @@ -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() - } -}