user.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package utils
  2. import (
  3. "errors"
  4. "git.bvbej.com/bvbej/base-golang/pkg/hash"
  5. "git.bvbej.com/bvbej/base-golang/pkg/hmac"
  6. "git.bvbej.com/bvbej/base-golang/pkg/time_parse"
  7. "time"
  8. )
  9. var _ UserToken = (*userToken)(nil)
  10. type UserToken interface {
  11. i()
  12. Generate(id uint64, platform string) (userID, token string, err error)
  13. Validate(userID, token, platform string) (id uint64, err error)
  14. }
  15. type userToken struct {
  16. hashidsSecret string
  17. hashidsLength int
  18. hmacSecret string
  19. ttl time.Duration
  20. }
  21. func NewUserToken(hashidsSecret, hmacSecret string, ttl time.Duration) UserToken {
  22. return &userToken{
  23. hashidsSecret: hashidsSecret,
  24. hashidsLength: 32,
  25. hmacSecret: hmacSecret,
  26. ttl: time.Minute * ttl,
  27. }
  28. }
  29. func (t *userToken) i() {}
  30. func (t *userToken) Generate(id uint64, platform string) (userID, token string, err error) {
  31. hashidsPtr := hash.New(t.hashidsSecret, t.hashidsLength)
  32. userID, err = hashidsPtr.HashidsEncode([]int{int(int64(id)), int(time.Now().Unix())})
  33. if err != nil {
  34. return "", "", err
  35. }
  36. hmacPtr := hmac.New(t.hmacSecret)
  37. token = hmacPtr.Sha256ToString(userID + platform)
  38. return
  39. }
  40. func (t *userToken) Validate(userID, token, platform string) (id uint64, err error) {
  41. hashidsPtr := hash.New(t.hashidsSecret, t.hashidsLength)
  42. hmacPtr := hmac.New(t.hmacSecret)
  43. if hmacPtr.Sha256ToString(userID+platform) != token {
  44. return id, errors.New("token invalid")
  45. }
  46. hashidsDecode, err := hashidsPtr.HashidsDecode(userID)
  47. if err != nil {
  48. return id, err
  49. }
  50. if len(hashidsDecode) == 2 {
  51. if time_parse.SubInLocation(time.Unix(int64(hashidsDecode[1]), 0)) > float64(t.ttl/time.Second) {
  52. return id, errors.New("token expired")
  53. }
  54. }
  55. return uint64(hashidsDecode[0]), nil
  56. }