salix/back/methods/account/recover-password.js

61 lines
1.5 KiB
JavaScript

const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('recoverPassword', {
description: 'Send email to the user',
accepts: [
{
arg: 'email',
type: 'string',
description: 'The email of user',
required: true
}
],
http: {
path: `/recoverPassword`,
verb: 'POST'
}
});
Self.recoverPassword = async function(ctx, email) {
const models = Self.app.models;
const origin = ctx.req.headers.origin;
const $t = ctx.req.__; // $translate
const ttl = 1209600;
const user = await models.Account.findOne({
fields: ['id', 'name', 'password'],
where: {
email: email
}
});
if (!user)
throw new UserError(`This email does not belong to a user`);
const token = await models.AccessToken.create({
ttl: ttl,
userId: user.id
});
const title = $t('Recover password');
const body = `
<p>
${$t('Click on the following link to change your password')}:
</p>
</b>
<a href="${origin}/#!/account/${user.id}/basic-data?access_token=${token.id}">
${title}
</a>`;
await Self.rawSql(`CALL vn.mail_insert(?,?,?,?)`, [
email,
null,
title,
body
]);
return;
};
};