"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.disableTwoFactorValidator = exports.confirmTwoFactorValidator = exports.requestOrConfirmTwoFactorValidator = void 0;
const tslib_1 = require("tslib");
const express_validator_1 = require("express-validator");
const misc_1 = require("../../helpers/custom-validators/misc");
const shared_1 = require("./shared");
const requestOrConfirmTwoFactorValidator = [
    (0, express_validator_1.param)('id').custom(misc_1.isIdValid),
    (req, res, next) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
        if ((0, shared_1.areValidationErrors)(req, res))
            return;
        if (!(yield checkCanEnableOrDisableTwoFactor(req.params.id, res)))
            return;
        if (res.locals.user.otpSecret) {
            return res.fail({
                status: 400,
                message: `Two factor is already enabled.`
            });
        }
        return next();
    })
];
exports.requestOrConfirmTwoFactorValidator = requestOrConfirmTwoFactorValidator;
const confirmTwoFactorValidator = [
    (0, express_validator_1.body)('requestToken').custom(misc_1.exists),
    (0, express_validator_1.body)('otpToken').custom(misc_1.exists),
    (req, res, next) => {
        if ((0, shared_1.areValidationErrors)(req, res))
            return;
        return next();
    }
];
exports.confirmTwoFactorValidator = confirmTwoFactorValidator;
const disableTwoFactorValidator = [
    (0, express_validator_1.param)('id').custom(misc_1.isIdValid),
    (req, res, next) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
        if ((0, shared_1.areValidationErrors)(req, res))
            return;
        if (!(yield checkCanEnableOrDisableTwoFactor(req.params.id, res)))
            return;
        if (!res.locals.user.otpSecret) {
            return res.fail({
                status: 400,
                message: `Two factor is already disabled.`
            });
        }
        return next();
    })
];
exports.disableTwoFactorValidator = disableTwoFactorValidator;
function checkCanEnableOrDisableTwoFactor(userId, res) {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        const authUser = res.locals.oauth.token.user;
        if (!(yield (0, shared_1.checkUserIdExist)(userId, res)))
            return;
        if (res.locals.user.id !== authUser.id && authUser.hasRight(1) !== true) {
            res.fail({
                status: 403,
                message: `User ${authUser.username} does not have right to change two factor setting of this user.`
            });
            return false;
        }
        return true;
    });
}
//# sourceMappingURL=two-factor.js.map