golang-im聊天
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

interceptor.go 1.9 KiB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. }