token.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package token
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. mhayaCrypto "github.com/mhaya/extend/crypto"
  6. mhayaTime "github.com/mhaya/extend/time"
  7. "github.com/mhaya/game/game_cluster/internal/code"
  8. mhayaLogger "github.com/mhaya/logger"
  9. )
  10. const (
  11. hashFormat = "pid:%d,openid:%s,playerid:%s,targetPath:%s,timestamp:%d"
  12. tokenExpiredDay = 3
  13. )
  14. type Token struct {
  15. PID int `json:"pid"`
  16. OpenID string `json:"open_id"`
  17. PlayerID string `json:"player_id"`
  18. TargetPath string `json:"target_path"`
  19. Nickname string `json:"nickname"`
  20. Timestamp int64 `json:"tt"`
  21. Hash string `json:"hash"`
  22. }
  23. func New(pid int, openId, playerId, targetPath, nickName string, appKey string) *Token {
  24. token := &Token{
  25. PID: pid,
  26. OpenID: openId,
  27. PlayerID: playerId,
  28. TargetPath: targetPath,
  29. Nickname: nickName,
  30. Timestamp: mhayaTime.Now().ToMillisecond(),
  31. }
  32. token.Hash = BuildHash(token, appKey)
  33. return token
  34. }
  35. func (t *Token) ToBase64() string {
  36. bytes, _ := json.Marshal(t)
  37. return mhayaCrypto.Base64Encode(string(bytes))
  38. }
  39. func DecodeToken(base64Token string) (*Token, bool) {
  40. if len(base64Token) < 1 {
  41. return nil, false
  42. }
  43. token := &Token{}
  44. bytes, err := mhayaCrypto.Base64DecodeBytes(base64Token)
  45. if err != nil {
  46. mhayaLogger.Warnf("base64Token = %s, validate error = %v", base64Token, err)
  47. return nil, false
  48. }
  49. err = json.Unmarshal(bytes, token)
  50. if err != nil {
  51. mhayaLogger.Warnf("base64Token = %s, unmarshal error = %v", base64Token, err)
  52. return nil, false
  53. }
  54. return token, true
  55. }
  56. func Validate(token *Token, appKey string) (int32, bool) {
  57. now := mhayaTime.Now()
  58. now.AddDays(tokenExpiredDay)
  59. if token.Timestamp > now.ToMillisecond() {
  60. mhayaLogger.Warnf("token is expired, token = %s", token)
  61. return code.AccountTokenValidateFail, false
  62. }
  63. newHash := BuildHash(token, appKey)
  64. if newHash != token.Hash {
  65. mhayaLogger.Warnf("hash validate fail. newHash = %s, token = %s", token)
  66. return code.AccountTokenValidateFail, false
  67. }
  68. return code.OK, true
  69. }
  70. func BuildHash(t *Token, appKey string) string {
  71. value := fmt.Sprintf(hashFormat, t.PID, t.OpenID, t.PlayerID, t.TargetPath, t.Timestamp)
  72. return mhayaCrypto.MD5(value + appKey)
  73. }