userauth.go 874 B

12345678910111213141516171819202122232425262728293031323334
  1. package auth
  2. import (
  3. "context"
  4. "slowwild/internal/constants"
  5. "google.golang.org/grpc"
  6. "google.golang.org/grpc/metadata"
  7. )
  8. // GetUserIDFromContext 从context中获取用户ID
  9. func GetUserIDFromContext(ctx context.Context) (string, bool) {
  10. userID, ok := ctx.Value(constants.UserIDKey).(string)
  11. return userID, ok
  12. }
  13. // NewUserAuthInterceptor 创建一个新的用户认证拦截器
  14. func NewUserAuthInterceptor() grpc.UnaryServerInterceptor {
  15. return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
  16. md, ok := metadata.FromIncomingContext(ctx)
  17. if !ok {
  18. return handler(ctx, req)
  19. }
  20. // 获取user_id
  21. userIDs := md.Get("user_id")
  22. if len(userIDs) > 0 {
  23. // 将user_id写入context
  24. ctx = context.WithValue(ctx, constants.UserIDKey, userIDs[0])
  25. }
  26. return handler(ctx, req)
  27. }
  28. }