package auth import ( "context" "slowwild/internal/constants" "google.golang.org/grpc" "google.golang.org/grpc/metadata" ) // GetUserIDFromContext 从context中获取用户ID func GetUserIDFromContext(ctx context.Context) (string, bool) { userID, ok := ctx.Value(constants.UserIDKey).(string) return userID, ok } // NewUserAuthInterceptor 创建一个新的用户认证拦截器 func NewUserAuthInterceptor() 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) } // 获取user_id userIDs := md.Get("user_id") if len(userIDs) > 0 { // 将user_id写入context ctx = context.WithValue(ctx, constants.UserIDKey, userIDs[0]) } return handler(ctx, req) } }