互动
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.

67 lines
1.6 KiB

5 years ago
  1. package jwt
  2. import (
  3. "errors"
  4. "fmt"
  5. "time"
  6. "github.com/dgrijalva/jwt-go"
  7. "github.com/ouxuanserver/osmanthuswine/src/helper"
  8. )
  9. type JwtClaims struct {
  10. AccountType string
  11. AccountId int64
  12. CustomerId int64
  13. CustomerPid int64
  14. Username string
  15. ActivityId int64
  16. AreaId int64
  17. jwt.StandardClaims
  18. }
  19. func GenJwtToken(accountType string, accountId, customerId, customerPid, areaId, activityId int64, username string) (string, error) {
  20. claims := JwtClaims{
  21. accountType,
  22. accountId,
  23. customerId,
  24. customerPid,
  25. username,
  26. activityId,
  27. areaId,
  28. jwt.StandardClaims{
  29. ExpiresAt: time.Now().Add(time.Duration(24000) * time.Hour).Unix(),
  30. Id: helper.CreateUUID(),
  31. Issuer: Issuer,
  32. Subject: Subject,
  33. Audience: Audience,
  34. },
  35. }
  36. t := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  37. return t.SignedString([]byte(Secret))
  38. }
  39. const Secret = "osmanthuswine-very-secret"
  40. const Issuer = "osmanthuswine-issuer-ox"
  41. const Subject = "osmanthuswine-subject-ox"
  42. const Audience = "osmanthuswine-audience-ox"
  43. func ParseAccessToken(accessToken string) (*JwtClaims, error) {
  44. var claims = &JwtClaims{}
  45. token, err := jwt.ParseWithClaims(accessToken, claims, func(token *jwt.Token) (i interface{}, e error) {
  46. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  47. return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
  48. }
  49. return []byte(Secret), nil
  50. })
  51. if token == nil {
  52. return claims, errors.New("token invalid")
  53. }
  54. if !claims.VerifyExpiresAt(time.Now().Unix(), true) {
  55. return nil, errors.New("token expired")
  56. }
  57. return claims, err
  58. }