jwt.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package jwt
  2. import (
  3. //"strings"
  4. "tmr-watch/pkg/e"
  5. "tmr-watch/pkg/util"
  6. jwtGet "tmr-watch/pkg/util"
  7. "github.com/dgrijalva/jwt-go"
  8. "github.com/gin-gonic/gin"
  9. )
  10. func JWT() gin.HandlerFunc {
  11. return func(c *gin.Context) {
  12. var code int
  13. var data interface{}
  14. code = e.SUCCESS
  15. //Authorization := c.GetHeader("Authorization")
  16. //token := strings.Split(Authorization, " ")
  17. Authorization := c.GetHeader("token")
  18. token := Authorization
  19. if Authorization == "" {
  20. code = e.INVALID_PARAMS
  21. } else {
  22. //_, err := util.ParseToken(token[1])
  23. _, err := util.ParseToken(token)
  24. if err != nil {
  25. switch err.(*jwt.ValidationError).Errors {
  26. case jwt.ValidationErrorExpired:
  27. code = e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT
  28. default:
  29. code = e.ERROR_AUTH_CHECK_TOKEN_FAIL
  30. }
  31. }
  32. }
  33. if code != e.SUCCESS {
  34. c.JSON(e.SUCCESS, gin.H{
  35. "code": code,
  36. "msg": "登录超时",
  37. "data": data,
  38. })
  39. c.Abort()
  40. return
  41. }
  42. t, _ := jwt.Parse(token, func(*jwt.Token) (interface{}, error) {
  43. return jwtGet.JwtSecret, nil
  44. })
  45. c.Set("jwt_username", jwtGet.GetIdFromClaims("username", t.Claims))
  46. c.Next()
  47. }
  48. }