cae8d30111c7429f5aba7c3ef246333fa70d6730.svn-base 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package jwt
  2. import (
  3. //"strings"
  4. "github.com/dgrijalva/jwt-go"
  5. "github.com/gin-gonic/gin"
  6. "../../pkg/e"
  7. "../../pkg/util"
  8. jwtGet "../../pkg/util"
  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. }