# Practical 5 – Network Security: User Registration and Login
import hashlib
import secrets
import sqlite3

DB = "users.db"

def init_db():
    with sqlite3.connect(DB) as db:
        db.execute("""CREATE TABLE IF NOT EXISTS users (
            username TEXT PRIMARY KEY, salt TEXT NOT NULL, password_hash TEXT NOT NULL)""")

def hash_password(password, salt=None):
    salt = salt or secrets.token_hex(16)
    digest = hashlib.pbkdf2_hmac(
        "sha256", password.encode(), salt.encode(), 100_000
    ).hex()
    return salt, digest

def register_user(username, password):
    salt, digest = hash_password(password)
    try:
        with sqlite3.connect(DB) as db:
            db.execute("INSERT INTO users VALUES (?, ?, ?)",
                       (username, salt, digest))
        return "User registered successfully!"
    except sqlite3.IntegrityError:
        return "Username already exists!"

def authenticate_user(username, password):
    with sqlite3.connect(DB) as db:
        row = db.execute(
            "SELECT salt, password_hash FROM users WHERE username=?",
            (username,),
        ).fetchone()
    return bool(row and hash_password(password, row[0])[1] == row[1])

if __name__ == "__main__":
    init_db()
    print(register_user("alice", "secret_password"))
    print("Login success?", authenticate_user("alice", "secret_password"))
    print("Login success?", authenticate_user("alice", "wrong_password"))

# What this code does: stores salted PBKDF2 password hashes in SQLite and
# demonstrates registering a user and checking valid and invalid logins.
