Skip to content

Commit 8b160bb

Browse files
Shio0909lyingbug
authored andcommitted
fix: use typed context key instead of string literal- Add UserContextKey constant to types package- Replace bare string 'user' with types.UserContextKey in auth middleware- Update user service to use UserContextKey for context value retrieval- Fixes staticcheck SA1029 warningThis prevents potential context key collisions.
1 parent aa4af53 commit 8b160bb

File tree

3 files changed

+5
-3
lines changed

3 files changed

+5
-3
lines changed

internal/application/service/user.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -419,7 +419,7 @@ func (s *userService) RevokeToken(ctx context.Context, tokenString string) error
419419

420420
// GetCurrentUser gets current user from context
421421
func (s *userService) GetCurrentUser(ctx context.Context) (*types.User, error) {
422-
user, ok := ctx.Value("user").(*types.User)
422+
user, ok := ctx.Value(types.UserContextKey).(*types.User)
423423
if !ok {
424424
return nil, errors.New("user not found in context")
425425
}

internal/middleware/auth.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -130,14 +130,14 @@ func Auth(
130130
// 存储用户和租户信息到上下文
131131
c.Set(types.TenantIDContextKey.String(), targetTenantID)
132132
c.Set(types.TenantInfoContextKey.String(), tenant)
133-
c.Set("user", user)
133+
c.Set(types.UserContextKey.String(), user)
134134
c.Request = c.Request.WithContext(
135135
context.WithValue(
136136
context.WithValue(
137137
context.WithValue(c.Request.Context(), types.TenantIDContextKey, targetTenantID),
138138
types.TenantInfoContextKey, tenant,
139139
),
140-
"user", user,
140+
types.UserContextKey, user,
141141
),
142142
)
143143
c.Next()

internal/types/const.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ const (
1212
RequestIDContextKey ContextKey = "RequestID"
1313
// LoggerContextKey is the context key for logger
1414
LoggerContextKey ContextKey = "Logger"
15+
// UserContextKey is the context key for user information
16+
UserContextKey ContextKey = "User"
1517
)
1618

1719
// String returns the string representation of the context key

0 commit comments

Comments
 (0)