feat: Refactor user management to replace email with username across the application
This commit is contained in:
@@ -273,7 +273,7 @@ export default function initializeDatabase() {
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),
|
||||
name TEXT NOT NULL,
|
||||
email TEXT UNIQUE NOT NULL,
|
||||
username TEXT UNIQUE NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
role TEXT CHECK(role IN ('admin', 'project_manager', 'user', 'read_only')) DEFAULT 'user',
|
||||
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
|
||||
@@ -309,9 +309,36 @@ export default function initializeDatabase() {
|
||||
);
|
||||
|
||||
-- Create indexes for performance
|
||||
CREATE INDEX IF NOT EXISTS idx_users_email ON users(email);
|
||||
CREATE INDEX IF NOT EXISTS idx_users_username ON users(username);
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_token ON sessions(session_token);
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_user ON sessions(user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_audit_user_timestamp ON audit_logs(user_id, timestamp);
|
||||
`);
|
||||
|
||||
// Migration: Add username column and migrate from email if needed
|
||||
try {
|
||||
// Check if username column exists
|
||||
const columns = db.prepare("PRAGMA table_info(users)").all();
|
||||
const hasUsername = columns.some(col => col.name === 'username');
|
||||
const hasEmail = columns.some(col => col.name === 'email');
|
||||
|
||||
if (!hasUsername && hasEmail) {
|
||||
// Add username column
|
||||
db.exec(`ALTER TABLE users ADD COLUMN username TEXT;`);
|
||||
|
||||
// Migrate existing email data to username (for development/testing)
|
||||
// In production, you might want to handle this differently
|
||||
db.exec(`UPDATE users SET username = email WHERE username IS NULL;`);
|
||||
|
||||
// Create unique index on username
|
||||
db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_users_username_unique ON users(username);`);
|
||||
|
||||
console.log("✅ Migrated users table from email to username");
|
||||
} else if (!hasUsername) {
|
||||
// If neither username nor email exists, something is wrong
|
||||
console.warn("⚠️ Users table missing both username and email columns");
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn("Migration warning:", e.message);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user