playerauthlogic.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package logic
  2. import (
  3. "context"
  4. "github.com/golang-jwt/jwt/v4"
  5. "github.com/pkg/errors"
  6. "time"
  7. "ylink/comm/jwtkey"
  8. "ylink/comm/result"
  9. "ylink/core/auth/rpc/internal/svc"
  10. "ylink/core/auth/rpc/pb"
  11. "github.com/zeromicro/go-zero/core/logx"
  12. )
  13. type PlayerAuthLogic struct {
  14. ctx context.Context
  15. svcCtx *svc.ServiceContext
  16. logx.Logger
  17. }
  18. func NewPlayerAuthLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PlayerAuthLogic {
  19. return &PlayerAuthLogic{
  20. ctx: ctx,
  21. svcCtx: svcCtx,
  22. Logger: logx.WithContext(ctx),
  23. }
  24. }
  25. func (l *PlayerAuthLogic) PlayerAuth(in *pb.PlayerAuthReq) (*pb.AuthResp, error) {
  26. now := time.Now().Unix()
  27. token, err := l.generatePlayerToken(now, in.PlayerId, in.GameId)
  28. if err != nil {
  29. return nil, errors.Wrap(result.NewErrCode(result.TokenGenerateError), "")
  30. }
  31. return &pb.AuthResp{
  32. AccessToken: token,
  33. }, nil
  34. }
  35. //
  36. // generatePlayerToken
  37. // @Description: 玩家token签发
  38. // @receiver l
  39. // @param iat
  40. // @param playerId
  41. // @param gameId
  42. // @return string
  43. // @return error
  44. //
  45. func (l *PlayerAuthLogic) generatePlayerToken(iat int64, playerId string, gameId string) (string, error) {
  46. secret := l.svcCtx.Config.JwtAuth.AccessSecret
  47. expire := l.svcCtx.Config.JwtAuth.AccessExpire
  48. claims := make(jwt.MapClaims)
  49. claims["iat"] = iat
  50. claims["exp"] = iat + expire
  51. claims[jwtkey.PlayerId] = playerId
  52. claims[jwtkey.GameId] = gameId
  53. token := jwt.New(jwt.SigningMethodHS256)
  54. token.Claims = claims
  55. return token.SignedString([]byte(secret))
  56. }