"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "resetPassword", {
    enumerable: true,
    get: function() {
        return resetPassword;
    }
});
const _express = /*#__PURE__*/ _interop_require_default(require("express"));
const _expressasynchandler = /*#__PURE__*/ _interop_require_default(require("express-async-handler"));
const _config = /*#__PURE__*/ _interop_require_default(require("config"));
const _yup = /*#__PURE__*/ _interop_require_wildcard(require("yup"));
const _datefns = require("date-fns");
const _errors = require("@tamanu/errors");
const _constants = require("@tamanu/constants");
const _logging = require("@tamanu/shared/services/logging");
const _utils = require("./utils");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
function _getRequireWildcardCache(nodeInterop) {
    if (typeof WeakMap !== "function") return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache = function(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
        return {
            default: obj
        };
    }
    var cache = _getRequireWildcardCache(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {
        __proto__: null
    };
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for(var key in obj){
        if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj.default = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}
const resetPassword = _express.default.Router();
const schema = _yup.object({
    email: _yup.string().email('Must enter a valid email').required(),
    deviceId: _yup.string()
});
resetPassword.post('/$', (0, _expressasynchandler.default)(async (req, res)=>{
    const { store, body, settings } = req;
    const { models } = store;
    await schema.validate(body);
    const { email, deviceId } = body;
    const user = await models.User.getForAuthByEmail(email);
    const { isUserLockedOut, remainingLockout } = user ? await models.UserLoginAttempt.checkIsUserLockedOut({
        models,
        settings,
        userId: user.id,
        deviceId
    }) : false;
    if (!user) {
        _logging.log.info(`Password reset request: No user found with email ${email}`);
    // ⚠️ SECURITY INFO:
    // This logic is available to anonymous users, so it's important it doesn't give out
    // any information about the system. In this case, a hacker can use a "not found"
    // error message to figure out which emails are really in use.
    // So, we just return an "OK" response no matter what information is provided,
    // regardless of whether it's valid or not.
    } else if (isUserLockedOut) {
        _logging.log.info(`Trying to login with locked user account: ${email}`);
        throw new _errors.RateLimitedError(remainingLockout, _constants.LOCKED_OUT_ERROR_MESSAGE);
    } else {
        const token = await createOneTimeLogin(models, user);
        await sendResetEmail(req.emailService, user, token);
    }
    return res.send({
        ok: 'ok'
    });
}));
const createOneTimeLogin = async (models, user)=>{
    const token = await (0, _utils.getRandomBase64String)(_config.default.auth.resetPassword.tokenLength);
    const expiresAt = (0, _datefns.addMinutes)(new Date(), _config.default.auth.resetPassword.tokenExpiry);
    await models.OneTimeLogin.create({
        userId: user.id,
        token,
        expiresAt
    });
    return token;
};
const sendResetEmail = async (emailService, user, token)=>{
    const emailText = `
      Hi ${user.displayName},

      You are receiving this email because someone requested a password reset for
      this user account. To reset your password enter the following reset code into Tamanu.

      Reset Code: ${token}

      If you believe this was sent to you in error, please ignore this email.

      tamanu.io`;
    const result = await emailService.sendEmail({
        from: _config.default.mailgun.from,
        to: user.email,
        subject: 'Tamanu password reset',
        text: emailText
    });
    if (result.status === _constants.COMMUNICATION_STATUSES.SENT) {
        _logging.log.info(`Password reset request: Sent email to ${user.email}`);
    } else {
        _logging.log.error(`Password reset request: Mailgun error: ${result.error}`);
        // Small security hole but worth it IMO for the user experience - if the email cannot
        // be sent this exposes that a user exists with the given email address, but
        // only when we get a mailgun connection error, so not very often hopefully.
        throw new Error(`Email could not be sent`);
    }
};

//# sourceMappingURL=resetPassword.js.map