ba0cfc08e3
- Added database schema for users, api_keys, sync_state, change_log, and sync_config - Implemented API key generation and validation with bcrypt hashing - Created Chi-based REST API server with endpoints for: - Task CRUD operations (create, read, update, delete) - Task actions (complete, start, stop) - Tag management (list, add, remove) - Projects listing - Health check endpoint - Added middleware for authentication and CORS - Implemented change log tracking with triggers (key:value format) - Added configurable change log retention (default 30 days) - Created server CLI commands (opal server start, opal server keygen) - Dependencies added: golang.org/x/crypto/bcrypt, github.com/go-chi/chi/v5
157 lines
3.6 KiB
Go
157 lines
3.6 KiB
Go
package engine
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"encoding/base64"
|
|
"fmt"
|
|
"time"
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
// APIKey represents an API key in the database
|
|
type APIKey struct {
|
|
ID int
|
|
Name string
|
|
UserID int
|
|
CreatedAt time.Time
|
|
LastUsed *time.Time
|
|
Revoked bool
|
|
}
|
|
|
|
// GenerateAPIKey creates a new API key for the given name
|
|
func GenerateAPIKey(name string) (string, error) {
|
|
db := GetDB()
|
|
if db == nil {
|
|
return "", fmt.Errorf("database not initialized")
|
|
}
|
|
|
|
// Generate random key: oak_ + 32 random bytes (base64 encoded)
|
|
keyBytes := make([]byte, 32)
|
|
if _, err := rand.Read(keyBytes); err != nil {
|
|
return "", fmt.Errorf("failed to generate random key: %w", err)
|
|
}
|
|
|
|
key := "oak_" + base64.URLEncoding.EncodeToString(keyBytes)
|
|
|
|
// Hash the key for storage
|
|
hashedKey, err := bcrypt.GenerateFromPassword([]byte(key), bcrypt.DefaultCost)
|
|
if err != nil {
|
|
return "", fmt.Errorf("failed to hash key: %w", err)
|
|
}
|
|
|
|
// Store in database (user_id defaults to 1 for shared user)
|
|
_, err = db.Exec(`
|
|
INSERT INTO api_keys (key, name, user_id, created_at)
|
|
VALUES (?, ?, 1, ?)
|
|
`, string(hashedKey), name, timeNow().Unix())
|
|
|
|
if err != nil {
|
|
return "", fmt.Errorf("failed to store API key: %w", err)
|
|
}
|
|
|
|
return key, nil
|
|
}
|
|
|
|
// ValidateAPIKey checks if an API key is valid and updates last_used timestamp
|
|
func ValidateAPIKey(key string) (bool, int, error) {
|
|
db := GetDB()
|
|
if db == nil {
|
|
return false, 0, fmt.Errorf("database not initialized")
|
|
}
|
|
|
|
// Get all non-revoked keys
|
|
rows, err := db.Query(`
|
|
SELECT id, key, user_id, revoked
|
|
FROM api_keys
|
|
WHERE revoked = 0
|
|
`)
|
|
if err != nil {
|
|
return false, 0, fmt.Errorf("failed to query API keys: %w", err)
|
|
}
|
|
defer rows.Close()
|
|
|
|
// Check each key (bcrypt comparison)
|
|
for rows.Next() {
|
|
var id, userID int
|
|
var hashedKey string
|
|
var revoked bool
|
|
|
|
if err := rows.Scan(&id, &hashedKey, &userID, &revoked); err != nil {
|
|
continue
|
|
}
|
|
|
|
// Compare with bcrypt
|
|
if err := bcrypt.CompareHashAndPassword([]byte(hashedKey), []byte(key)); err == nil {
|
|
// Valid key found - update last_used
|
|
now := timeNow().Unix()
|
|
_, _ = db.Exec("UPDATE api_keys SET last_used = ? WHERE id = ?", now, id)
|
|
return true, userID, nil
|
|
}
|
|
}
|
|
|
|
return false, 0, nil
|
|
}
|
|
|
|
// ListAPIKeys returns all API keys for a user (without the actual key value)
|
|
func ListAPIKeys(userID int) ([]*APIKey, error) {
|
|
db := GetDB()
|
|
if db == nil {
|
|
return nil, fmt.Errorf("database not initialized")
|
|
}
|
|
|
|
rows, err := db.Query(`
|
|
SELECT id, name, user_id, created_at, last_used, revoked
|
|
FROM api_keys
|
|
WHERE user_id = ?
|
|
ORDER BY created_at DESC
|
|
`, userID)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to query API keys: %w", err)
|
|
}
|
|
defer rows.Close()
|
|
|
|
var keys []*APIKey
|
|
for rows.Next() {
|
|
key := &APIKey{}
|
|
var createdAt, lastUsed int64
|
|
var lastUsedNull *int64
|
|
|
|
err := rows.Scan(&key.ID, &key.Name, &key.UserID, &createdAt, &lastUsedNull, &key.Revoked)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to scan API key: %w", err)
|
|
}
|
|
|
|
key.CreatedAt = time.Unix(createdAt, 0)
|
|
if lastUsedNull != nil {
|
|
lastUsed = *lastUsedNull
|
|
t := time.Unix(lastUsed, 0)
|
|
key.LastUsed = &t
|
|
}
|
|
|
|
keys = append(keys, key)
|
|
}
|
|
|
|
return keys, nil
|
|
}
|
|
|
|
// RevokeAPIKey marks an API key as revoked
|
|
func RevokeAPIKey(keyID int) error {
|
|
db := GetDB()
|
|
if db == nil {
|
|
return fmt.Errorf("database not initialized")
|
|
}
|
|
|
|
result, err := db.Exec("UPDATE api_keys SET revoked = 1 WHERE id = ?", keyID)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to revoke API key: %w", err)
|
|
}
|
|
|
|
rows, _ := result.RowsAffected()
|
|
if rows == 0 {
|
|
return fmt.Errorf("API key not found")
|
|
}
|
|
|
|
return nil
|
|
}
|