|
- package mw
-
- import (
- "applet/app/e"
- "applet/app/utils"
- "errors"
- "github.com/dgrijalva/jwt-go"
- "strings"
- "time"
-
- "github.com/gin-gonic/gin"
- )
-
- // AuthJWT is jwt middleware
- func AuthJWT(c *gin.Context) {
-
- //获取请求头中的Authorization
- authHeader := c.Request.Header.Get("Authorization")
- if authHeader == "" {
- e.OutErr(c, e.ERR_UNAUTHORIZED, errors.New("token 不能为空"))
- return
- }
-
- //拆分Authorization字段获取token字符串
- parts := strings.SplitN(authHeader, " ", 2)
- if !(len(parts) == 2 && parts[0] == "Bearer") {
- e.OutErr(c, e.ERR_TOKEN_FORMAT, errors.New("token 格式不对"))
- return
- }
-
- //验证token字符串
- claim, err := utils.ParseToken(parts[1])
- if err != nil {
- v, _ := err.(*jwt.ValidationError)
- if v.Errors == jwt.ValidationErrorExpired {
- e.OutErr(c, e.ERR_TOKEN_EXPIRE, errors.New("token 过期已失效"))
- return
- }
- e.OutErr(c, e.ERR_UNAUTHORIZED, errors.New("token 验证失败"))
- return
- }
-
- //过期判断
- if time.Now().Unix() > claim.ExpiresAt {
- e.OutErr(c, e.ERR_TOKEN_EXPIRE, errors.New("token 过期已失效"))
- return
- }
- MasterId := claim.MasterId
- if strings.Contains(MasterId, "_") {
- ex := strings.Split(MasterId, "_")
- if len(ex) >= 3 {
- MasterId = ex[0]
- c.Set("phone", ex[1])
- c.Set("is_system", ex[2])
- }
- }
- //设置上下文信息
- c.Set("master_id", MasterId)
- c.Next()
- }
|