connectlogic.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package logic
  2. import (
  3. "context"
  4. "github.com/golang-jwt/jwt/v4"
  5. "github.com/pkg/errors"
  6. "ylink/comm/globalkey"
  7. "ylink/comm/jwtkey"
  8. "ylink/comm/result"
  9. "ylink/core/inner/rpc/inner"
  10. "ylink/flowsrv/rpc/internal/mgr"
  11. "ylink/flowsrv/rpc/internal/svc"
  12. "ylink/flowsrv/rpc/pb"
  13. "github.com/zeromicro/go-zero/core/logx"
  14. )
  15. type ConnectLogic struct {
  16. ctx context.Context
  17. svcCtx *svc.ServiceContext
  18. logx.Logger
  19. }
  20. func NewConnectLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ConnectLogic {
  21. return &ConnectLogic{
  22. ctx: ctx,
  23. svcCtx: svcCtx,
  24. Logger: logx.WithContext(ctx),
  25. }
  26. }
  27. func (l *ConnectLogic) Connect(in *pb.CommandReq, stream pb.Flowsrv_ConnectServer) error {
  28. uid, gameId, err := l.checkAuth(in)
  29. if err != nil {
  30. return stream.Send(&pb.CommandResp{
  31. Code: result.TokenParseError,
  32. Msg: err.Error(),
  33. Data: nil,
  34. })
  35. }
  36. _, err = l.svcCtx.InnerRpc.NotifyUserOnline(l.ctx, &inner.NotifyUserStatusReq{
  37. Type: in.Type,
  38. Uid: uid,
  39. GameId: gameId,
  40. })
  41. if err != nil {
  42. return stream.Send(&pb.CommandResp{
  43. Code: result.ServerCommonError,
  44. Msg: err.Error(),
  45. Data: nil,
  46. })
  47. }
  48. mgr.GetFlowMgrInstance().SetFlow(uid, stream)
  49. return stream.Send(&pb.CommandResp{
  50. Code: result.Ok,
  51. Msg: "success",
  52. Data: nil,
  53. })
  54. }
  55. func (l *ConnectLogic) checkAuth(in *pb.CommandReq) (string, string, error) {
  56. token, err := jwt.Parse(in.AccessToken, func(token *jwt.Token) (i interface{}, err error) {
  57. return []byte(l.svcCtx.Config.JwtAuth.AccessSecret), nil
  58. })
  59. uid := ""
  60. gameId := ""
  61. if token.Valid {
  62. //将获取的token中的Claims强转为MapClaims
  63. claims, _ := token.Claims.(jwt.MapClaims)
  64. if in.Type == globalkey.CONNECT_TYPE_PLAYER {
  65. uid = claims[jwtkey.PlayerId].(string)
  66. gameId = claims[jwtkey.GameId].(string)
  67. } else {
  68. uid = claims[jwtkey.CsId].(string)
  69. }
  70. return uid, gameId, nil
  71. } else if ve, ok := err.(*jwt.ValidationError); ok {
  72. if ve.Errors&jwt.ValidationErrorMalformed != 0 {
  73. return uid, gameId, errors.Wrap(result.NewErrCode(result.TokenParseError), "")
  74. } else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
  75. // Token is either expired or not active yet
  76. return uid, gameId, errors.Wrap(result.NewErrCode(result.TokenExpireError), "")
  77. } else {
  78. return uid, gameId, errors.Wrap(result.NewErrCode(result.TokenParseError), "")
  79. }
  80. } else {
  81. return uid, gameId, errors.Wrap(result.NewErrCode(result.TokenParseError), "")
  82. }
  83. }