golang-im聊天
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

65 lines
1.9 KiB

  1. package interceptor
  2. import (
  3. "context"
  4. "gim/pkg/gerrors"
  5. "gim/pkg/grpclib"
  6. "gim/pkg/logger"
  7. "gim/pkg/pb"
  8. "gim/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. resp, err = handleWithAuth(ctx, req, info, handler, urlWhitelist)
  21. logger.Logger.Debug(name, zap.Any("method", info.FullMethod), zap.Any("md", md), zap.Any("req", req),
  22. zap.Any("resp", resp), zap.Error(err))
  23. s, _ := status.FromError(err)
  24. if s.Code() != 0 && s.Code() < 1000 {
  25. md, _ := metadata.FromIncomingContext(ctx)
  26. logger.Logger.Error(name, zap.String("method", info.FullMethod), zap.Any("md", md), zap.Any("req", req),
  27. zap.Any("resp", resp), zap.Error(err), zap.String("stack", gerrors.GetErrorStack(s)))
  28. }
  29. return
  30. }
  31. }
  32. // handleWithAuth 处理鉴权逻辑
  33. func handleWithAuth(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, urlWhitelist map[string]int) (interface{}, error) {
  34. serverName := strings.Split(info.FullMethod, "/")[1]
  35. if !strings.HasSuffix(serverName, "Int") {
  36. if _, ok := urlWhitelist[info.FullMethod]; !ok {
  37. userId, deviceId, err := grpclib.GetCtxData(ctx)
  38. if err != nil {
  39. return nil, err
  40. }
  41. token, err := grpclib.GetCtxToken(ctx)
  42. if err != nil {
  43. return nil, err
  44. }
  45. _, err = rpc.GetBusinessIntClient().Auth(ctx, &pb.AuthReq{
  46. UserId: userId,
  47. DeviceId: deviceId,
  48. Token: token,
  49. })
  50. if err != nil {
  51. return nil, err
  52. }
  53. }
  54. }
  55. return handler(ctx, req)
  56. }