const express = require('express');
const bodyParser = require('body-parser');
const sqlite3 = require('sqlite3').verbose();
const path = require('path');
const crypto = require('crypto');

const app = express();
const PORT = 3000;

// Middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));

// Database Setup (In-memory)
const db = new sqlite3.Database(':memory:');

db.serialize(() => {
    db.run("CREATE TABLE users (id INTEGER PRIMARY KEY, username TEXT, password TEXT)");

    // Create 100 random users
    // If the attacker tries to brute force based on ID, they don't know who is admin.
    const stmt = db.prepare("INSERT INTO users (username, password) VALUES (?, ?)");
    for (let i = 0; i < 100; i++) {
        const randomUser = `worker-${crypto.randomBytes(4).toString('hex')}`;
        const randomPass = crypto.randomBytes(8).toString('hex');
        stmt.run(randomUser, randomPass);
    }
    stmt.finalize();
});

const FLAG = "REDACTED";

app.post('/api/login', (req, res) => {
    const { username, password } = req.body;

    
    const query = `SELECT id FROM users WHERE username = '${username}' AND password = '${password}'`;

    console.log(`Executing SQL: ${query}`);

    db.get(query, (err, row) => {
        if (err) {
            console.error(err);
            return res.redirect('/?error=Database Error');
        }

        if (!row || !row.id) {
            return res.redirect('/?error=Invalid Credentials');
        }

     

        if (activeAdmins[username]) {
            // Success!
            return res.redirect('/?flag=' + encodeURIComponent(FLAG));
        } else {
            // User is logged in but not an admin
            return res.redirect('/?error=Access Denied: Production Floor Workers are not allowed in the Prototype Lab.');
        }
    });
});

app.listen(PORT, () => {
    console.log(`Car Factory Server running on port ${PORT}`);
});