智盟项目
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.3 KiB

  1. package mw
  2. import (
  3. "applet/app/e"
  4. "applet/app/utils"
  5. "errors"
  6. "github.com/dgrijalva/jwt-go"
  7. "strings"
  8. "time"
  9. "github.com/gin-gonic/gin"
  10. )
  11. // AuthJWT is jwt middleware
  12. func AuthJWT(c *gin.Context) {
  13. //获取请求头中的Authorization
  14. authHeader := c.Request.Header.Get("Authorization")
  15. if authHeader == "" {
  16. e.OutErr(c, e.ERR_UNAUTHORIZED, errors.New("token 不能为空"))
  17. return
  18. }
  19. //拆分Authorization字段获取token字符串
  20. parts := strings.SplitN(authHeader, " ", 2)
  21. if !(len(parts) == 2 && parts[0] == "Bearer") {
  22. e.OutErr(c, e.ERR_TOKEN_FORMAT, errors.New("token 格式不对"))
  23. return
  24. }
  25. //验证token字符串
  26. claim, err := utils.ParseToken(parts[1])
  27. if err != nil {
  28. v, _ := err.(*jwt.ValidationError)
  29. if v.Errors == jwt.ValidationErrorExpired {
  30. e.OutErr(c, e.ERR_TOKEN_EXPIRE, errors.New("token 过期已失效"))
  31. return
  32. }
  33. e.OutErr(c, e.ERR_UNAUTHORIZED, errors.New("token 验证失败"))
  34. return
  35. }
  36. //过期判断
  37. if time.Now().Unix() > claim.ExpiresAt {
  38. e.OutErr(c, e.ERR_TOKEN_EXPIRE, errors.New("token 过期已失效"))
  39. return
  40. }
  41. MasterId := claim.MasterId
  42. if strings.Contains(MasterId, "_") {
  43. ex := strings.Split(MasterId, "_")
  44. if len(ex) >= 3 {
  45. MasterId = ex[0]
  46. c.Set("phone", ex[1])
  47. c.Set("is_system", ex[2])
  48. }
  49. }
  50. //设置上下文信息
  51. c.Set("master_id", MasterId)
  52. c.Next()
  53. }