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


function sendTOTPForm(response, errors=[]) {
    response.render(`views/htmx/totpForm.njk`, {
        errors: errors
    });
}


export const get = async function(request, response) {
    if (request.getAuthState() != 'totp-verfication') {
        response.redirect('/htmx/authForm');
        return;
    }

    sendTOTPForm(response);
}

export const post = async function(request, response) {
    // redirect if not in TOTP verification state
    if (request.getAuthState() != 'totp-verfication') {
        response.redirect('/htmx/authForm');
        return;
    }

    // validate input
    if (!request.body.otpToken || typeof request.body.otpToken != 'string') {
        sendTOTPForm(response, [{
            title: 'OTP token is required',
            detail: 'no OTP token was received.'
        }]);
        return;
    }

    let otpToken = request.body.otpToken;
    let dbUser = await request.getUser();

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

    if (validationResult != null) {
        request.setAuthState('authenticated');
        response.set('HX-Redirect', '/profile').status(200).end();
    } else {
        sendTOTPForm(response, [{
            title: 'OTP validation failed',
            detail: 'the provided OTP token is invalid. Please try again.'
        }]);
    }
}