"use strict";
/*
 * server component for the TimeLimit App
 * Copyright (C) 2019 - 2022 Jonas Lochmann
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.recoverParentPassword = void 0;
const http_errors_1 = require("http-errors");
const schema_1 = require("../../api/schema");
const mail_1 = require("../../util/mail");
const token_1 = require("../../util/token");
const authentication_1 = require("../authentication");
const websocket_1 = require("../websocket");
const recoverParentPassword = async ({ database, websocket, password, mailAuthToken }) => {
    (0, schema_1.assertPlaintextParentPasswordValid)(password);
    await database.transaction(async (transaction) => {
        const mailInfo = await (0, authentication_1.requireMailAndLocaleByAuthToken)({ mailAuthToken, database, transaction, invalidate: true });
        // update the user entry
        const userEntry = await database.user.findOne({
            where: {
                mail: mailInfo.mail
            },
            transaction
        });
        if (!userEntry) {
            throw new http_errors_1.Conflict();
        }
        userEntry.passwordHash = password.hash;
        userEntry.secondPasswordHash = password.secondHash;
        userEntry.secondPasswordSalt = password.secondSalt;
        await userEntry.save({ transaction });
        // invalidate the user list
        await database.family.update({
            userListVersion: (0, token_1.generateVersionId)()
        }, {
            where: {
                familyId: userEntry.familyId
            },
            transaction
        });
        await (0, websocket_1.notifyClientsAboutChangesDelayed)({
            database,
            familyId: userEntry.familyId,
            websocket,
            generalLevel: 2,
            targetedLevels: new Map(),
            sourceDeviceId: null,
            transaction
        });
        transaction.afterCommit(async () => {
            await (0, mail_1.sendPasswordRecoveryUsedMail)({
                receiver: mailInfo.mail,
                locale: mailInfo.locale
            });
        });
    });
};
exports.recoverParentPassword = recoverParentPassword;
//# sourceMappingURL=recover-parent-password.js.map