Implement user authentication with hashed passwords

Replaces hardcoded admin credentials with a users table in the database, storing hashed passwords and user roles. Updates the login logic in app.py to authenticate against the database using Werkzeug's password hashing utilities. Adds admin credential configuration to config.py and ensures a default admin user is created during database initialization.
This commit is contained in:
Jon Ander Oribe
2026-01-11 17:54:43 +01:00
parent 03ce847196
commit dd56617c4c
5 changed files with 52 additions and 4 deletions

View File

@@ -12,6 +12,8 @@ from contextlib import contextmanager
from datetime import datetime
from pathlib import Path
from typing import Any
from werkzeug.security import generate_password_hash
from config import ADMIN_USERNAME, ADMIN_PASSWORD
logger = logging.getLogger('intercept.database')
@@ -100,6 +102,31 @@ def init_db() -> None:
)
''')
# Users table for authentication
conn.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
role TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
cursor = conn.execute('SELECT COUNT(*) FROM users')
if cursor.fetchone()[0] == 0:
from config import ADMIN_USERNAME, ADMIN_PASSWORD
logger.info(f"Creating default admin user: {ADMIN_USERNAME}")
# Password hashing
hashed_pw = generate_password_hash(ADMIN_PASSWORD)
conn.execute('''
INSERT INTO users (username, password_hash, role)
VALUES (?, ?, ?)
''', (ADMIN_USERNAME, hashed_pw, 'admin'))
logger.info("Database initialized successfully")