"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResetPasswordHandler = void 0;
const yup_1 = require("yup");
const global_logger_factory_1 = require("global-logger-factory");
const BadRequestHttpError_1 = require("../../../util/errors/BadRequestHttpError");
const JsonInteractionHandler_1 = require("../JsonInteractionHandler");
const YupUtil_1 = require("../YupUtil");
const inSchema = (0, yup_1.object)({
    recordId: (0, yup_1.string)().trim().min(1).required(),
    password: (0, yup_1.string)().trim().required(),
});
/**
 * Resets a password if a valid `recordId` is provided,
 * which should have been generated by a different handler.
 */
class ResetPasswordHandler extends JsonInteractionHandler_1.JsonInteractionHandler {
    logger = (0, global_logger_factory_1.getLoggerFor)(this);
    passwordStore;
    forgotPasswordStore;
    constructor(passwordStore, forgotPasswordStore) {
        super();
        this.passwordStore = passwordStore;
        this.forgotPasswordStore = forgotPasswordStore;
    }
    async getView() {
        return { json: (0, YupUtil_1.parseSchema)(inSchema) };
    }
    async handle({ json }) {
        // Validate input data
        const { password, recordId } = await (0, YupUtil_1.validateWithError)(inSchema, json);
        await this.resetPassword(recordId, password);
        return { json: {} };
    }
    /**
     * Resets the password for the account associated with the given recordId.
     */
    async resetPassword(recordId, newPassword) {
        const id = await this.forgotPasswordStore.get(recordId);
        if (!id) {
            this.logger.warn(`Trying to use invalid reset URL with record ID ${recordId}`);
            throw new BadRequestHttpError_1.BadRequestHttpError('This reset password link is no longer valid.');
        }
        await this.passwordStore.update(id, newPassword);
        await this.forgotPasswordStore.delete(recordId);
        this.logger.debug(`Resetting password for login ${id}`);
    }
}
exports.ResetPasswordHandler = ResetPasswordHandler;
//# sourceMappingURL=ResetPasswordHandler.js.map