playerloginlogic.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package logic
  2. import (
  3. "context"
  4. "github.com/golang-jwt/jwt/v4"
  5. "github.com/pkg/errors"
  6. "github.com/zeromicro/go-zero/core/logx"
  7. "time"
  8. "ylink/bff/authbff/api/internal/svc"
  9. "ylink/bff/authbff/api/internal/types"
  10. "ylink/comm/jwtkey"
  11. "ylink/comm/result"
  12. )
  13. type PlayerLoginLogic struct {
  14. logx.Logger
  15. ctx context.Context
  16. svcCtx *svc.ServiceContext
  17. }
  18. func NewPlayerLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PlayerLoginLogic {
  19. return &PlayerLoginLogic{
  20. Logger: logx.WithContext(ctx),
  21. ctx: ctx,
  22. svcCtx: svcCtx,
  23. }
  24. }
  25. func (l *PlayerLoginLogic) PlayerLogin(req *types.PlayerAuthReq) (resp *types.AuthResp, err error) {
  26. now := time.Now().Unix()
  27. token, err := l.generatePlayerToken(now, req.Type, req.GameId, req.PlayerId)
  28. if err != nil {
  29. return nil, errors.Wrap(result.NewErrCode(result.TokenGenerateError), "")
  30. }
  31. return &types.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 *PlayerLoginLogic) generatePlayerToken(iat int64, cType int32, gameId string, playerId 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.GameId] = gameId
  52. claims[jwtkey.PlayerId] = playerId
  53. claims[jwtkey.Type] = cType
  54. token := jwt.New(jwt.SigningMethodHS256)
  55. token.Claims = claims
  56. return token.SignedString([]byte(secret))
  57. }