新增系统设置接口

This commit is contained in:
wxb committed 2020-08-07 10:22:52 +08:00
commit 389d2970c0
150 files changed
+21555

No files matched your search

+26
View File
@@ -0,0 +1,26 @@
package middleware
import (
"go-admin/handler"
jwt "go-admin/pkg/jwtauth"
"go-admin/tools/config"
"time"
)
func AuthInit() (*jwt.GinJWTMiddleware, error) {
return jwt.New(&jwt.GinJWTMiddleware{
Realm: "test zone",
Key: []byte(config.ApplicationConfig.JwtSecret),
Timeout: time.Hour,
MaxRefresh: time.Hour,
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,
})
}
+49
View File
@@ -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("2006-01-02 15:04:05"),
"[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()
}
+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")
}
+22
View File
@@ -0,0 +1,22 @@
package middleware
import (
"github.com/gin-gonic/gin"
)
func InitMiddleware(r *gin.Engine) {
// 日志处理
r.Use(LoggerToFile())
// 自定义错误处理
r.Use(CustomError)
// NoCache is a middleware function that appends headers
r.Use(NoCache)
// 跨域处理
r.Use(Options)
// Secure is a middleware function that appends security
r.Use(Secure)
// Set X-Request-Id header
r.Use(RequestId())
}
+108
View File
@@ -0,0 +1,108 @@
package middleware
import (
"fmt"
"github.com/gin-gonic/gin"
"go-admin/global"
"go-admin/models"
"go-admin/tools"
config2 "go-admin/tools/config"
"strings"
"time"
)
// 日志记录到文件
func LoggerToFile() gin.HandlerFunc {
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()
// 日志格式
fmt.Printf("%s [INFO] %s %s %3d %13v %15s \r\n",
startTime.Format("2006-01-02 15:04:05"),
reqMethod,
reqUri,
statusCode,
latencyTime,
clientIP,
)
global.RequestLogger.Info(statusCode, latencyTime, clientIP, reqMethod, reqUri)
if c.Request.Method != "GET" && c.Request.Method != "OPTIONS" && config2.LoggerConfig.EnabledDB {
SetDBOperLog(c, clientIP, statusCode, reqUri, reqMethod, latencyTime)
}
}
}
// 写入操作日志表
// 该方法后续即将弃用
func SetDBOperLog(c *gin.Context, clientIP string, statusCode int, reqUri string, reqMethod string, latencyTime time.Duration) {
menu := models.Menu{}
menu.Path = reqUri
menu.Action = reqMethod
menuList, _ := menu.Get()
sysOperLog := models.SysOperLog{}
sysOperLog.OperIp = clientIP
sysOperLog.OperLocation = tools.GetLocation(clientIP)
sysOperLog.Status = tools.IntToString(statusCode)
sysOperLog.OperName = tools.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, _ = tools.StructToJsonStr(b)
sysOperLog.CreateBy = tools.GetUserName(c)
sysOperLog.OperTime = tools.GetCurrentTime()
sysOperLog.LatencyTime = (latencyTime).String()
sysOperLog.UserAgent = c.Request.UserAgent()
if c.Err() == nil {
sysOperLog.Status = "0"
} else {
sysOperLog.Status = "1"
}
_, _ = sysOperLog.Create()
}
+42
View File
@@ -0,0 +1,42 @@
package middleware
import (
"fmt"
"github.com/gin-gonic/gin"
mycasbin "go-admin/pkg/casbin"
"go-admin/pkg/jwtauth"
_ "go-admin/pkg/jwtauth"
"go-admin/tools"
"net/http"
)
//权限检查中间件
func AuthCheckRole() gin.HandlerFunc {
return func(c *gin.Context) {
data, _ := c.Get("JWT_PAYLOAD")
v := data.(jwtauth.MapClaims)
e, err := mycasbin.Casbin()
tools.HasError(err, "", 500)
//检查权限
res, err := e.Enforce(v["rolekey"], c.Request.URL.Path, c.Request.Method)
tools.HasError(err, "", 500)
fmt.Printf("%s [INFO] %s %s %s \r\n",
tools.GetCurrentTimeStr(),
c.Request.Method,
c.Request.URL.Path,
v["rolekey"],
)
if res {
c.Next()
} else {
c.JSON(http.StatusOK, gin.H{
"code": 403,
"msg": "对不起,您没有该接口访问权限,请联系管理员",
})
c.Abort()
return
}
}
}
+26
View File
@@ -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()
}
}