From 4106f023d098351323ad4e6914057a1484151a53 Mon Sep 17 00:00:00 2001 From: zhangwenjian Date: Mon, 13 Apr 2020 00:11:47 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=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 --- middleware/auth.go | 27 ++++++++ middleware/customerror.go | 49 +++++++++++++++ middleware/demo.go | 27 ++++++++ middleware/header.go | 47 ++++++++++++++ middleware/logger.go | 128 ++++++++++++++++++++++++++++++++++++++ middleware/permission.go | 37 +++++++++++ middleware/requestid.go | 26 ++++++++ 7 files changed, 341 insertions(+) create mode 100644 middleware/auth.go create mode 100644 middleware/customerror.go create mode 100644 middleware/demo.go create mode 100644 middleware/header.go create mode 100644 middleware/logger.go create mode 100644 middleware/permission.go create mode 100644 middleware/requestid.go diff --git a/middleware/auth.go b/middleware/auth.go new file mode 100644 index 0000000..aa7fc02 --- /dev/null +++ b/middleware/auth.go @@ -0,0 +1,27 @@ +package middleware + +import ( + config2 "go-admin/config" + "go-admin/handler" + jwt "go-admin/pkg/jwtauth" + "time" +) + +func AuthInit() (*jwt.GinJWTMiddleware, error) { + 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: "header: Authorization, query: token, cookie: jwt", + TokenHeadName: "Bearer", + TimeFunc: time.Now, + }) + +} diff --git a/middleware/customerror.go b/middleware/customerror.go new file mode 100644 index 0000000..5fbd99d --- /dev/null +++ b/middleware/customerror.go @@ -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() +} diff --git a/middleware/demo.go b/middleware/demo.go new file mode 100644 index 0000000..0448f72 --- /dev/null +++ b/middleware/demo.go @@ -0,0 +1,27 @@ +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/middleware/header.go b/middleware/header.go new file mode 100644 index 0000000..6ece741 --- /dev/null +++ b/middleware/header.go @@ -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") +} diff --git a/middleware/logger.go b/middleware/logger.go new file mode 100644 index 0000000..f0c1ba2 --- /dev/null +++ b/middleware/logger.go @@ -0,0 +1,128 @@ +package middleware + +import ( + "fmt" + "github.com/gin-gonic/gin" + "github.com/sirupsen/logrus" + "go-admin/config" + "go-admin/models" + "go-admin/pkg/utils" + "os" + "strings" + "time" +) + +//实例化 +var logger = logrus.New() + +// 日志记录到文件 +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.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.GetUserName(c) + 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/middleware/permission.go b/middleware/permission.go new file mode 100644 index 0000000..e809455 --- /dev/null +++ b/middleware/permission.go @@ -0,0 +1,37 @@ +package middleware + +import ( + "github.com/gin-gonic/gin" + "go-admin/pkg" + 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) { + data, _ := c.Get("JWT_PAYLOAD") + v := data.(jwtauth.MapClaims) + e, err := mycasbin.Casbin() + pkg.HasError(err,"",500) + //检查权限 + res, err := e.Enforce(v["rolekey"], c.Request.URL.Path, c.Request.Method) + log.Println("----------------", v["rolekey"], c.Request.URL.Path, c.Request.Method) + + pkg.HasError(err,"",500) + + if res { + c.Next() + } else { + c.JSON(http.StatusOK, gin.H{ + "status": 401, + "msg": "对不起,您没有该接口访问权限,请联系管理员", + }) + c.Abort() + return + } + } +} diff --git a/middleware/requestid.go b/middleware/requestid.go new file mode 100644 index 0000000..7ab5f7a --- /dev/null +++ b/middleware/requestid.go @@ -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() + } +}