(ctx context.Context, clientName string, instanceID int)
| 33 | } |
| 34 | |
| 35 | func (s *ClientAPIKeyStore) Create(ctx context.Context, clientName string, instanceID int) (string, *ClientAPIKey, error) { |
| 36 | // Generate new API key |
| 37 | rawKey, err := GenerateAPIKey() |
| 38 | if err != nil { |
| 39 | return "", nil, fmt.Errorf("failed to generate API key: %w", err) |
| 40 | } |
| 41 | |
| 42 | // Hash the key for storage |
| 43 | keyHash := HashAPIKey(rawKey) |
| 44 | |
| 45 | // Use a transaction to atomically intern the string and insert the API key |
| 46 | tx, err := s.db.BeginTx(ctx, nil) |
| 47 | if err != nil { |
| 48 | return "", nil, fmt.Errorf("failed to begin transaction: %w", err) |
| 49 | } |
| 50 | defer tx.Rollback() |
| 51 | |
| 52 | // Intern the client name |
| 53 | ids, err := dbinterface.InternStringNullable(ctx, tx, &clientName) |
| 54 | if err != nil { |
| 55 | return "", nil, fmt.Errorf("failed to intern client_name: %w", err) |
| 56 | } |
| 57 | |
| 58 | // Insert the client API key |
| 59 | clientAPIKey := &ClientAPIKey{} |
| 60 | var createdAt, lastUsedAt sql.NullTime |
| 61 | err = tx.QueryRowContext(ctx, ` |
| 62 | INSERT INTO client_api_keys (key_hash, client_name_id, instance_id) |
| 63 | VALUES (?, ?, ?) |
| 64 | RETURNING id, key_hash, instance_id, created_at, last_used_at |
| 65 | `, keyHash, ids[0], instanceID).Scan( |
| 66 | &clientAPIKey.ID, |
| 67 | &clientAPIKey.KeyHash, |
| 68 | &clientAPIKey.InstanceID, |
| 69 | &createdAt, |
| 70 | &lastUsedAt, |
| 71 | ) |
| 72 | |
| 73 | if err != nil { |
| 74 | return "", nil, err |
| 75 | } |
| 76 | |
| 77 | if err = tx.Commit(); err != nil { |
| 78 | return "", nil, fmt.Errorf("failed to commit transaction: %w", err) |
| 79 | } |
| 80 | |
| 81 | clientAPIKey.ClientName = clientName |
| 82 | clientAPIKey.CreatedAt = createdAt.Time |
| 83 | if lastUsedAt.Valid { |
| 84 | clientAPIKey.LastUsedAt = &lastUsedAt.Time |
| 85 | } |
| 86 | |
| 87 | // Return both the raw key (to show user once) and the model |
| 88 | return rawKey, clientAPIKey, nil |
| 89 | } |
| 90 | |
| 91 | func (s *ClientAPIKeyStore) GetAll(ctx context.Context) ([]*ClientAPIKey, error) { |
| 92 | query := ` |
nothing calls this directly
no test coverage detected