MCPcopy
hub / github.com/mudler/LocalAI / ValidateAPIKey

Function ValidateAPIKey

core/http/auth/apikeys.go:77–98  ·  view source on GitHub ↗

ValidateAPIKey looks up an API key by hashing the plaintext and searching the database. Returns the key record if found, or an error. Updates LastUsed on successful validation.

(db *gorm.DB, plaintext, hmacSecret string)

Source from the content-addressed store, hash-verified

75// the database. Returns the key record if found, or an error.
76// Updates LastUsed on successful validation.
77func ValidateAPIKey(db *gorm.DB, plaintext, hmacSecret string) (*UserAPIKey, error) {
78 hash := HashAPIKey(plaintext, hmacSecret)
79
80 var key UserAPIKey
81 if err := db.Preload("User").Where("key_hash = ?", hash).First(&key).Error; err != nil {
82 return nil, fmt.Errorf("invalid API key")
83 }
84
85 if key.ExpiresAt != nil && time.Now().After(*key.ExpiresAt) {
86 return nil, fmt.Errorf("API key expired")
87 }
88
89 if key.User.Status != StatusActive {
90 return nil, fmt.Errorf("user account is not active")
91 }
92
93 // Update LastUsed
94 now := time.Now()
95 db.Model(&key).Update("last_used", now)
96
97 return &key, nil
98}
99
100// ListAPIKeys returns all API keys for the given user (without plaintext).
101func ListAPIKeys(db *gorm.DB, userID string) ([]UserAPIKey, error) {

Callers 3

apikeys_test.goFile · 0.92
RegisterAuthRoutesFunction · 0.92
tryAuthenticateFunction · 0.85

Calls 3

HashAPIKeyFunction · 0.85
PreloadMethod · 0.80
UpdateMethod · 0.65

Tested by

no test coverage detected