This commit is contained in:
2025-12-04 10:56:54 +08:00
parent 60992c1e44
commit e4946b7ad7
2 changed files with 25 additions and 21 deletions
+11 -20
View File
@@ -13,25 +13,16 @@ import (
"github.com/golang-jwt/jwt/v5"
)
// contextKey is a custom type for context keys to avoid collisions
type contextKey string
const (
claimsKey contextKey = "claims"
userIDKey contextKey = "user_id"
usernameKey contextKey = "username"
roleKey contextKey = "role"
claimsKey models.ContextKey = "claims"
userIDKey models.ContextKey = "user_id"
usernameKey models.ContextKey = "username"
roleKey models.ContextKey = "role"
)
// Token cache entry
type cacheEntry struct {
claims *models.Claims
expiresAt time.Time
}
var (
// Token cache for high-frequency requests
tokenCache = make(map[string]*cacheEntry)
tokenCache = make(map[string]*models.CacheEntry)
tokenCacheMutex sync.RWMutex
// Cache JWT secret to avoid repeated os.Getenv calls
@@ -77,7 +68,7 @@ func cleanExpiredTokens() {
now := time.Now()
for token, entry := range tokenCache {
if now.After(entry.expiresAt) {
if now.After(entry.ExpiresAt) {
delete(tokenCache, token)
}
}
@@ -104,8 +95,8 @@ func JWTAuth(next http.HandlerFunc) http.HandlerFunc {
// Check cache first (read lock)
tokenCacheMutex.RLock()
if cached, exists := tokenCache[tokenString]; exists {
if time.Now().Before(cached.expiresAt) {
claims := cached.claims
if time.Now().Before(cached.ExpiresAt) {
claims := cached.Claims
tokenCacheMutex.RUnlock()
// Add claims to context and proceed
@@ -170,9 +161,9 @@ func JWTAuth(next http.HandlerFunc) http.HandlerFunc {
}
}
}
tokenCache[tokenString] = &cacheEntry{
claims: claims,
expiresAt: expiresAt,
tokenCache[tokenString] = &models.CacheEntry{
Claims: claims,
ExpiresAt: expiresAt,
}
tokenCacheMutex.Unlock()