98 lines
2.3 KiB
Go
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
|
|
admin bool
|
|
roles string
|
|
permissions string
|
|
}{
|
|
{
|
|
"admin_user",
|
|
"5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8",
|
|
true,
|
|
`["user", "admin"]`,
|
|
`{"read": true, "write": true, "delete": true}`,
|
|
},
|
|
{
|
|
"researcher1",
|
|
"ef92b778ba7a6c8f2150019a5678047b6a9a2b95cef8189518f9b35c54d2e3ae",
|
|
false,
|
|
`["user", "researcher"]`,
|
|
`{"read": true, "write": true, "delete": false}`,
|
|
},
|
|
{
|
|
"analyst1",
|
|
"a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3",
|
|
false,
|
|
`["user", "analyst"]`,
|
|
`{"read": true, "write": false, "delete": 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)
|
|
}
|
|
}
|