fetch_ml/cmd/db-utils/init_multi_user.go
Jeremie Fraeys 4cdb68907e
refactor(utilities): update supporting modules for scheduler integration
Update utility modules:
- File utilities with secure file operations
- Environment pool with resource tracking
- Error types with scheduler error categories
- Logging with audit context support
- Network/SSH with connection pooling
- Privacy/PII handling with tenant boundaries
- Resource manager with scheduler allocation
- Security monitor with audit integration
- Tracking plugins (MLflow, TensorBoard) with auth
- Crypto signing with tenant keys
- Database init with multi-user support
2026-02-26 12:07:15 -05:00

98 lines
2.3 KiB
Go

// init_multi_user initializes a multi-user database with API keys
package main
import (
"context"
"database/sql"
"fmt"
"log"
"os"
_ "github.com/mattn/go-sqlite3"
)
func main() {
if len(os.Args) < 2 {
fmt.Println("Usage: init_multi_user <database_file>")
os.Exit(1)
}
dbPath := os.Args[1]
// Open database
db, err := sql.Open("sqlite3", dbPath)
if err != nil {
log.Fatalf("Failed to open database: %v", err)
}
// Create API keys table
createTable := `
CREATE TABLE IF NOT EXISTS api_keys (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL UNIQUE,
key_hash TEXT NOT NULL UNIQUE,
admin BOOLEAN NOT NULL DEFAULT FALSE,
roles TEXT NOT NULL DEFAULT '[]',
permissions TEXT NOT NULL DEFAULT '{}',
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
expires_at DATETIME,
revoked_at DATETIME,
CHECK (json_valid(roles)),
CHECK (json_valid(permissions))
);`
if _, err := db.ExecContext(context.Background(), createTable); err != nil {
log.Fatalf("Failed to create table: %v", err)
}
// Insert users
users := []struct {
userID string
keyHash string
roles string
permissions string
admin bool
}{
{
"admin_user",
"5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8",
`["user", "admin"]`,
`{"read": true, "write": true, "delete": true}`,
true,
},
{
"researcher1",
"ef92b778ba7a6c8f2150019a5678047b6a9a2b95cef8189518f9b35c54d2e3ae",
`["user", "researcher"]`,
`{"read": true, "write": true, "delete": false}`,
false,
},
{
"analyst1",
"a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3",
`["user", "analyst"]`,
`{"read": true, "write": false, "delete": false}`,
false,
},
}
for _, user := range users {
insert := `
INSERT OR REPLACE INTO api_keys (user_id, key_hash, admin, roles, permissions)
VALUES (?, ?, ?, ?, ?)`
if _, err := db.ExecContext(context.Background(), insert,
user.userID, user.keyHash, user.admin, user.roles, user.permissions); err != nil {
log.Printf("Failed to insert user %s: %v", user.userID, err)
} else {
fmt.Printf("Successfully inserted user: %s\n", user.userID)
}
}
fmt.Println("Database initialization complete!")
// Close database
if err := db.Close(); err != nil {
log.Printf("Warning: failed to close database: %v", err)
}
}