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)
| 75 | // the database. Returns the key record if found, or an error. |
| 76 | // Updates LastUsed on successful validation. |
| 77 | func 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). |
| 101 | func ListAPIKeys(db *gorm.DB, userID string) ([]UserAPIKey, error) { |
no test coverage detected