调整中间件结构
This commit is contained in:
1 parent
4106f023d0
commit
f25da5f1ee
7 files changed
-356
No files matched your search
@@ -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 "<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,
|
||||
})
|
||||
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user