"use strict";
/*
 * server component for the TimeLimit App
 * Copyright (C) 2019 - 2021 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.requireMailAndLocaleByAuthToken = exports.getMailAndLocaleByAuthToken = exports.createAuthTokenByMailAddress = void 0;
const http_errors_1 = require("http-errors");
const token_1 = require("../../util/token");
const createAuthTokenByMailAddress = async ({ mail, database, transaction, locale }) => {
    const token = (0, token_1.generateAuthToken)();
    await database.authtoken.create({
        token,
        mail,
        createdAt: Date.now().toString(),
        locale
    }, { transaction });
    return token;
};
exports.createAuthTokenByMailAddress = createAuthTokenByMailAddress;
const getMailAndLocaleByAuthToken = async ({ mailAuthToken, database, transaction, invalidate }) => {
    const entry = await database.authtoken.findOne({
        where: {
            token: mailAuthToken
        },
        transaction
    });
    if (entry) {
        if (invalidate) {
            const rowCounter = await database.authtoken.destroy({
                where: {
                    token: mailAuthToken
                },
                transaction
            });
            if (rowCounter !== 1) {
                return null;
            }
        }
        return {
            mail: entry.mail,
            locale: entry.locale
        };
    }
    else {
        return null;
    }
};
exports.getMailAndLocaleByAuthToken = getMailAndLocaleByAuthToken;
const requireMailAndLocaleByAuthToken = async ({ mailAuthToken, database, transaction, invalidate }) => {
    const result = await (0, exports.getMailAndLocaleByAuthToken)({ mailAuthToken, database, transaction, invalidate });
    if (!result) {
        throw new http_errors_1.Unauthorized();
    }
    return result;
};
exports.requireMailAndLocaleByAuthToken = requireMailAndLocaleByAuthToken;
//# sourceMappingURL=index.js.map