You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

75 rivejä
2.2 KiB

  1. package interceptor
  2. import (
  3. "context"
  4. "egg-im/pkg/gerrors"
  5. "egg-im/pkg/grpclib"
  6. "egg-im/pkg/logger"
  7. "egg-im/pkg/pb"
  8. "egg-im/pkg/rpc"
  9. "strings"
  10. "go.uber.org/zap"
  11. "google.golang.org/grpc"
  12. "google.golang.org/grpc/metadata"
  13. "google.golang.org/grpc/status"
  14. )
  15. // NewInterceptor 生成GRPC过滤器
  16. func NewInterceptor(name string, urlWhitelist map[string]int) grpc.UnaryServerInterceptor {
  17. return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
  18. defer gerrors.LogPanic(name, ctx, req, info, &err)
  19. md, _ := metadata.FromIncomingContext(ctx)
  20. s, _ := status.FromError(err)
  21. if s.Code() != 0 && s.Code() < 1000 {
  22. md, _ := metadata.FromIncomingContext(ctx)
  23. logger.Logger.Error(name, zap.String("method", info.FullMethod), zap.Any("md", md), zap.Any("req", req),
  24. zap.Any("resp", resp), zap.Error(err), zap.String("stack", gerrors.GetErrorStack(s)))
  25. }
  26. if err != nil {
  27. return
  28. }
  29. resp, err = handleWithAuth(ctx, req, info, handler, urlWhitelist)
  30. logger.Logger.Debug(name, zap.Any("method", info.FullMethod), zap.Any("md", md), zap.Any("req", req),
  31. zap.Any("resp", resp), zap.Error(err))
  32. s, _ = status.FromError(err)
  33. if s.Code() != 0 && s.Code() < 1000 {
  34. md, _ := metadata.FromIncomingContext(ctx)
  35. logger.Logger.Error(name, zap.String("method", info.FullMethod), zap.Any("md", md), zap.Any("req", req),
  36. zap.Any("resp", resp), zap.Error(err), zap.String("stack", gerrors.GetErrorStack(s)))
  37. }
  38. return
  39. }
  40. }
  41. // handleWithAuth 处理鉴权逻辑
  42. func handleWithAuth(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, urlWhitelist map[string]int) (interface{}, error) {
  43. serverName := strings.Split(info.FullMethod, "/")[1]
  44. if !strings.HasSuffix(serverName, "Int") {
  45. if _, ok := urlWhitelist[info.FullMethod]; !ok {
  46. userId, deviceId, err := grpclib.GetCtxData(ctx)
  47. if err != nil {
  48. return nil, err
  49. }
  50. token, err := grpclib.GetCtxToken(ctx)
  51. if err != nil {
  52. return nil, err
  53. }
  54. _, err = rpc.GetBusinessIntClient().Auth(ctx, &pb.AuthReq{
  55. UserId: userId,
  56. DeviceId: deviceId,
  57. Token: token,
  58. })
  59. if err != nil {
  60. return nil, err
  61. }
  62. }
  63. }
  64. return handler(ctx, req)
  65. }