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.

65 lines
1.5 KiB

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