
import crypto from "crypto";

import {
    login,
    getUser,
    getUserMFA
} from "../lib/mysql.mjs";

import {
    validateOTPCode
} from "../lib/otp.mjs";

export const get = async function(request, response) {
    if (typeof request.session.userid != 'string') {
        response.render(`ui/login.njk`, {
            step: 'login'
        });
        return;
    }
    if (request.session.otpVerified != true) {
        response.render(`ui/login.njk`, {
            step: 'otp'
        });
        return;
    }
}

export const post = async function(request, response) {
    if (typeof request.body.username == 'string' && typeof request.body.password == 'string') {
        let username = request.body.username;
        let password = crypto.createHash('sha256').update(request.body.password).digest('hex')

        let loginResult = await login(username, password)

        if (loginResult == null) {
            response.render(`ui/login.njk`, {
                step: 'login',
                error: 'login failed'
            });
            return;
        }

        request.session.userid = loginResult.id;
        request.session.login = {
            completed: false,
            otpVerified: false
        }
        request.session.save();
    
        if (loginResult.otpsecret != '' && loginResult.yubikey != '') {
            response.render(`ui/login.njk`, {
                step: 'otp'
            });
            return;
        } else {
            request.session.login.completed = true;
            response.redirect('/profile')
        }
    } else if (typeof request.body.otpToken == 'string') {
        let otpToken = request.body.otpToken;
        let userData = await getUser(request.session.userid);
        let mfaData = await getUserMFA(request.session.userid);

        let validationResult = await validateOTPCode(userData.mail, mfaData.otpsecret, otpToken);

        if (validationResult != null) {
            request.session.login.completed = true;
            response.redirect('/profile');
        } else {
            request.session.destroy();
            response.render(`ui/login.njk`, {
                step: 'login',
                error: 'otp failed'
            });
        }
    }
}