CreateAPIKey generates and stores a new API key for the given user. Returns the plaintext key (shown once) and the database record.
(db *gorm.DB, userID, name, role, hmacSecret string, expiresAt *time.Time)
| 49 | // CreateAPIKey generates and stores a new API key for the given user. |
| 50 | // Returns the plaintext key (shown once) and the database record. |
| 51 | func CreateAPIKey(db *gorm.DB, userID, name, role, hmacSecret string, expiresAt *time.Time) (string, *UserAPIKey, error) { |
| 52 | plaintext, hash, prefix, err := GenerateAPIKey(hmacSecret) |
| 53 | if err != nil { |
| 54 | return "", nil, err |
| 55 | } |
| 56 | |
| 57 | record := &UserAPIKey{ |
| 58 | ID: uuid.New().String(), |
| 59 | UserID: userID, |
| 60 | Name: name, |
| 61 | KeyHash: hash, |
| 62 | KeyPrefix: prefix, |
| 63 | Role: role, |
| 64 | ExpiresAt: expiresAt, |
| 65 | } |
| 66 | |
| 67 | if err := db.Create(record).Error; err != nil { |
| 68 | return "", nil, fmt.Errorf("failed to store API key: %w", err) |
| 69 | } |
| 70 | |
| 71 | return plaintext, record, nil |
| 72 | } |
| 73 | |
| 74 | // ValidateAPIKey looks up an API key by hashing the plaintext and searching |
| 75 | // the database. Returns the key record if found, or an error. |