var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var challenge2Router = require('./routes/challenge2')
var challenge3Router = require('./routes/challenge3');
var challenge4Router = require('./routes/challenge4');

const FLAG_1 = "IGCTF{ReMoveYoUrDebUgGinGStAteMents}";
const FLAG_2 = "IGCTF{HiHiHaxxED}";
const FLAG_4 = "IGCTF{OtH3RCo0LFl4gN4m3}";

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/challenge2', challenge2Router);
app.use('/challenge3', challenge3Router);
app.use('/challenge4', challenge4Router);
app.use('/users', usersRouter);


// GARBO CODE FOLLOWING DONT HATE
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database('database.db', sqlite3.OPEN_READONLY);


app.post('/flag1', (req, res) => {
    var user = req.body.user;
    var pass = req.body.pass;

    if (user === 'admin' && pass === 'DezeNoten123') {
        res.send({flag: FLAG_1});
    } else {
        res.send("false");
    }
});

async function credentialsMatch(user, pass, match) {
    // EXAMPLE INJECTION:
    //' OR 'a'='a
    var statement = "SELECT * FROM Credentials WHERE user=\'" + user + "\' AND pass=\'" + pass + "\';";
    db.each(statement, (err, row) => {
        match();
    });
}

app.post('/flag2', (req, res) => {
    var user = req.body.user;
    var pass = req.body.pass;

    var sent = false;

    credentialsMatch(user, pass, () => {
        if (!sent) {
            res.send({flag: FLAG_2});
            sent = true;
        }
    });
    // lol deal with it
    setTimeout(() => {
        if (!sent)
            res.send("false");
    }, 1000);
});

app.post('/flag4', (req, res) => {
    var user = req.body.user;
    var pass = req.body.pass;

    if (user === 'admin' && pass === 'somePla1nT3xtP4Ss') {
        res.send({flag: FLAG_4});
    } else {
        res.send("false");
    }
});

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;
