auth.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package utils
  2. import (
  3. "gd_gateway/errors"
  4. "strconv"
  5. "time"
  6. "gd_gateway/common.in/config"
  7. "github.com/dgrijalva/jwt-go"
  8. )
  9. type UtimesClaims struct {
  10. Jti string `json:"jti"`
  11. jwt.StandardClaims
  12. }
  13. type UserClaims struct {
  14. Uid int64 `json:"uid"`
  15. UserName string `json:"user_name"`
  16. //Password string `json:"password"`
  17. jwt.StandardClaims
  18. }
  19. type UtimesIssuer int
  20. const (
  21. UserJWTKey = "be3bc479a23b6161c229b0a27359d869"
  22. )
  23. func ProductToken(uid int64, userName string) (string, error) {
  24. expired, _ := config.Conf.Cgi.GdGateway.TokenExpired.Int64()
  25. claims := UserClaims{
  26. uid,
  27. userName,
  28. jwt.StandardClaims{
  29. ExpiresAt: time.Now().Unix() + expired, //3600*2, //过期时间
  30. Subject: strconv.FormatInt(uid, 10), //uid
  31. IssuedAt: time.Now().Unix(), //生成时间
  32. NotBefore: time.Now().Unix(),
  33. },
  34. }
  35. plain := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  36. return plain.SignedString([]byte(UserJWTKey))
  37. }
  38. func ParseToken(tokenString string) (int64, string, error) {
  39. token, err := jwt.ParseWithClaims(tokenString, &UserClaims{}, func(token *jwt.Token) (interface{}, error) {
  40. return []byte(UserJWTKey), nil
  41. })
  42. if err != nil {
  43. switch err.(*jwt.ValidationError).Errors {
  44. case jwt.ValidationErrorExpired:
  45. return 0, "", errors.UserTokenExpire
  46. default:
  47. return 0, "", errors.UserTokenError
  48. }
  49. }
  50. if clams, ok := token.Claims.(*UserClaims); ok {
  51. return clams.Uid, clams.UserName, nil
  52. } else {
  53. return 0, "", errors.UserTokenError
  54. }
  55. }