58 lines
1.2 KiB
Go
58 lines
1.2 KiB
Go
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()
|
|
}
|
|
}
|