init: taotie-api 项目初始化
This commit is contained in:
57
api/middleware/authMiddleware.go
Normal file
57
api/middleware/authMiddleware.go
Normal file
@@ -0,0 +1,57 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"taotie-api/common"
|
||||
"taotie-api/core"
|
||||
"taotie-api/utils/sctx"
|
||||
"taotie-api/utils/sjwt"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func Auth(cfg *core.Configuration) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": common.ErrSysValidationFailed.Info().Id,
|
||||
"msg": "缺少 Authorization 头",
|
||||
"ok": false,
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
parts := strings.SplitN(authHeader, " ", 2)
|
||||
if len(parts) != 2 || parts[0] != "Bearer" {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": common.ErrSysValidationFailed.Info().Id,
|
||||
"msg": "Authorization 格式错误,应为 Bearer <token>",
|
||||
"ok": false,
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
claims, err := sjwt.ParseToken(parts[1], cfg.JWT.SignString)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": common.ErrSysValidationFailed.Info().Id,
|
||||
"msg": "token 无效或已过期",
|
||||
"ok": false,
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
sctx.SetCurrentUser(c, &sctx.CurrentUser{
|
||||
UserId: claims.UserId,
|
||||
UserName: claims.UserName,
|
||||
TenantId: claims.TenantId,
|
||||
})
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
19
api/middleware/corsMiddleware.go
Normal file
19
api/middleware/corsMiddleware.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/gin-contrib/cors"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func Cors() gin.HandlerFunc {
|
||||
return cors.New(cors.Config{
|
||||
AllowOrigins: []string{"*"}, // 允许所有来源(生产环境不建议使用)
|
||||
AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"}, // 允许的请求方法
|
||||
AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization"}, // 允许的请求头部
|
||||
ExposeHeaders: []string{"Content-Length", "Access-Control-Allow-Origin", "Authorization"}, // 允许客户端获取的响应头部
|
||||
AllowCredentials: true, // 允许携带 Cookie
|
||||
MaxAge: 12 * time.Hour, // 预检请求的缓存时间
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user