ms-auth/internal/users/delivery/grpc/token_interceptor.go

31 lines
699 B
Go
Raw Permalink Normal View History

2024-10-09 17:07:38 +00:00
package grpc
import (
"context"
"git.sch9.ru/new_gate/ms-auth/internal/sessions"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)
func TokenInterceptor(s sessions.UseCase) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return handler(ctx, req)
}
auth := md.Get("authorization")
if len(auth) == 0 {
return handler(ctx, req)
}
userId, err := s.Read(ctx, auth[0])
if err != nil {
return handler(ctx, req)
}
ctx = context.WithValue(ctx, "userId", *userId)
return handler(ctx, req)
}
}