cleaned
This commit is contained in:
+11
-20
@@ -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()
|
||||
|
||||
|
||||
+14
-1
@@ -1,6 +1,10 @@
|
||||
package models
|
||||
|
||||
import "github.com/golang-jwt/jwt/v5"
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
type AuthorizationRequest struct {
|
||||
UserID string `json:"user_id"`
|
||||
@@ -19,3 +23,12 @@ type Claims struct {
|
||||
Role string `json:"role"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
// ContextKey is a custom type for context keys to avoid collisions
|
||||
type ContextKey string
|
||||
|
||||
// CacheEntry represents a token cache entry
|
||||
type CacheEntry struct {
|
||||
Claims *Claims
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user