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

61 lines
1.5 KiB
JavaScript
Raw Normal View History

2022-09-20 13:21:01 +00:00
const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
2022-09-21 13:15:19 +00:00
Self.remoteMethodCtx('recoverPassword', {
2022-09-20 13:21:01 +00:00
description: 'Send email to the user',
accepts: [
{
arg: 'email',
type: 'string',
description: 'The email of user',
2022-09-21 13:15:19 +00:00
required: true
2022-09-20 13:21:01 +00:00
}
],
http: {
path: `/recoverPassword`,
2022-09-21 13:15:19 +00:00
verb: 'POST'
2022-09-20 13:21:01 +00:00
}
});
2022-09-21 13:15:19 +00:00
Self.recoverPassword = async function(ctx, email) {
2022-09-20 13:21:01 +00:00
const models = Self.app.models;
2022-09-21 13:15:19 +00:00
const origin = ctx.req.headers.origin;
const $t = ctx.req.__; // $translate
2022-09-21 13:15:19 +00:00
const ttl = 1209600;
const user = await models.Account.findOne({
fields: ['id', 'name', 'password'],
2022-09-20 13:21:01 +00:00
where: {
email: email
}
});
if (!user)
throw new UserError(`This email does not belong to a user`);
2022-09-21 13:15:19 +00:00
const token = await models.AccessToken.create({
ttl: ttl,
userId: user.id
2022-09-20 13:21:01 +00:00
});
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;
2022-09-20 13:21:01 +00:00
};
};