|
|
@@ -1,53 +1,64 @@
|
|
|
package middleware
|
|
|
|
|
|
import (
|
|
|
- "net/http"
|
|
|
- "strings"
|
|
|
-
|
|
|
"github.com/gin-gonic/gin"
|
|
|
-
|
|
|
- "newaterobot-process/service"
|
|
|
+ "github.com/golang-jwt/jwt/v4"
|
|
|
+ "net/http"
|
|
|
+ "newaterobot-process/utils"
|
|
|
)
|
|
|
|
|
|
// JWTAuthMiddleware JWT认证中间件
|
|
|
func JWTAuthMiddleware() gin.HandlerFunc {
|
|
|
return func(c *gin.Context) {
|
|
|
- // 获取token
|
|
|
- authHeader := c.GetHeader("Authorization")
|
|
|
- if authHeader == "" {
|
|
|
- c.JSON(http.StatusUnauthorized, gin.H{
|
|
|
- "code": 401,
|
|
|
- "message": "请求未携带token,无权限访问",
|
|
|
- })
|
|
|
- c.Abort()
|
|
|
- return
|
|
|
+
|
|
|
+ if c.Keys == nil {
|
|
|
+ c.Keys = make(map[string]any)
|
|
|
+ }
|
|
|
+ //判断
|
|
|
+ var code int
|
|
|
+ var data interface{}
|
|
|
+ code = http.StatusOK
|
|
|
+ //分别从Header和Query Param当中获取 jwt-token
|
|
|
+ token := c.GetHeader("JWT-TOKEN")
|
|
|
+ if token == "" {
|
|
|
+ token = c.Query("JWT-TOKEN")
|
|
|
}
|
|
|
|
|
|
- // 按空格分割
|
|
|
- parts := strings.SplitN(authHeader, " ", 2)
|
|
|
- if !(len(parts) == 2 && parts[0] == "Bearer") {
|
|
|
- c.JSON(http.StatusUnauthorized, gin.H{
|
|
|
- "code": 401,
|
|
|
- "message": "请求头中auth格式有误",
|
|
|
- })
|
|
|
- c.Abort()
|
|
|
- return
|
|
|
+ // session未中断
|
|
|
+ if _, ok := c.Keys[utils.SessionUserIdKey]; ok {
|
|
|
+ c.Next()
|
|
|
+ }
|
|
|
+
|
|
|
+ if token == "" {
|
|
|
+ code = http.StatusUnauthorized
|
|
|
+ data = "无法获取token参数"
|
|
|
+ } else {
|
|
|
+ claim, err := utils.ParseTokenWithDep(token)
|
|
|
+ if err != nil {
|
|
|
+ switch err.(*jwt.ValidationError).Errors {
|
|
|
+ case jwt.ValidationErrorExpired:
|
|
|
+ code = http.StatusUnauthorized
|
|
|
+ default:
|
|
|
+ code = http.StatusUnauthorized
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ if code == http.StatusOK {
|
|
|
+ c.Keys[utils.SessionUserIdKey] = claim.ID
|
|
|
+ c.Keys[utils.SessionDepIdKey] = claim.Dep
|
|
|
+ }
|
|
|
}
|
|
|
|
|
|
- // 解析token
|
|
|
- claims, err := service.GetJWTService().ParseToken(parts[1])
|
|
|
- if err != nil {
|
|
|
+ if code != http.StatusOK {
|
|
|
c.JSON(http.StatusUnauthorized, gin.H{
|
|
|
- "code": 401,
|
|
|
- "message": "token无效或已过期",
|
|
|
+ "code": code,
|
|
|
+ "msg": "token 验证失败",
|
|
|
+ "data": data,
|
|
|
})
|
|
|
+
|
|
|
c.Abort()
|
|
|
return
|
|
|
}
|
|
|
-
|
|
|
- // 将用户信息保存到上下文
|
|
|
- c.Set("user_id", claims.UserID)
|
|
|
- c.Set("username", claims.Username)
|
|
|
c.Next()
|
|
|
}
|
|
|
-}
|
|
|
+}
|