"use strict";
/*
 *  This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
 *  License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
/*
Password reset works as follows:

1. Query the database to make sure there is a user with the given email address.
2. If a password reset was already sent within the last XX minutes,
   return an error -- we don't want people to spam other people with
   password resets.
3. Generate password reset token and write to database.
4. Send email.
5. Send response to user that email has been sent (or there was an error).
*/
const is_account_available_1 = __importDefault(require("@cocalc/server/auth/is-account-available"));
const password_reset_1 = require("@cocalc/server/auth/password-reset");
const password_reset_2 = __importDefault(require("@cocalc/server/email/password-reset"));
const get_params_1 = __importDefault(require("lib/api/get-params"));
async function passwordReset(req, res) {
    const { email } = (0, get_params_1.default)(req);
    let result;
    try {
        result = await handle(email?.toLowerCase(), req.ip);
    }
    catch (err) {
        result = { error: err.message };
    }
    res.json(result);
}
exports.default = passwordReset;
async function handle(email, ip) {
    if (await (0, is_account_available_1.default)(email)) {
        // Bad -- email is *available*, which means no way to reset
        // the password for it, since it doesn't exist.
        return { error: `There is no account with email "${email}".` };
    }
    // Check that user isn't spamming email.
    const n = await (0, password_reset_1.recentAttempts)(email, ip);
    if (n > 3) {
        return {
            error: `We recently sent multiple password resets for "${email}".  Check your email or wait a while and try later.`,
        };
    }
    const id = await (0, password_reset_1.createReset)(email, ip, 60 * 60 * 4); // 4 hour ttl seems reasonable for this.
    // TODO:
    // - Send email with the id and link
    // - Link should be back to next.js server (i.e., a new password reset target)
    // - Implement that target and backend handling of it.
    try {
        await (0, password_reset_2.default)(email, id);
    }
    catch (err) {
        console.trace(err);
        return {
            error: `Sending password reset email failed -- ${err.message}`,
        };
    }
    return {
        success: `Password reset email successfully sent to ${email}.`,
    };
}
//# sourceMappingURL=password-reset.js.map