hedera-front/back/common/models/user.js

66 lines
1.8 KiB
JavaScript
Raw Normal View History

2020-05-06 16:44:42 +00:00
const app = require('../../server/server');
const loopback = require('loopback');
const path = require('path');
2020-06-29 11:31:48 +00:00
function getUrl() {
return app.get('rootUrl') || app.get('url');
}
2020-05-06 16:44:42 +00:00
2020-06-29 11:31:48 +00:00
function getFrom() {
return app.dataSources.email.settings.transports[0].auth.from;
}
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = 'ValidationError';
this.statusCode = 422;
}
}
2020-05-06 16:44:42 +00:00
2020-06-29 11:31:48 +00:00
module.exports = function (Self) {
2020-05-06 16:44:42 +00:00
Self.afterRemote('create', async function(ctx, instance) {
2020-06-29 11:31:48 +00:00
const url = new URL(getUrl());
2020-05-06 16:44:42 +00:00
const options = {
type: 'email',
to: instance.email,
2020-06-29 11:31:48 +00:00
from: getFrom(),
2020-05-06 16:44:42 +00:00
subject: 'Thanks for registering',
template: path.resolve(__dirname, '../../views/verify.ejs'),
2020-06-29 11:31:48 +00:00
redirect: `${getUrl()}#/login/${instance.email}?emailConfirmed`,
host: url.hostname,
port: url.port,
protocol: url.protocol.split(':')[0],
2020-05-06 16:44:42 +00:00
user: Self
};
2020-06-29 11:31:48 +00:00
instance.verify(options)
.then(res => console.log('> Verification email sent:', res));
2020-05-06 16:44:42 +00:00
});
2020-06-29 11:31:48 +00:00
Self.validatePassword = function(password) {
if (!password) {
throw new ValidationError('passwordEmpty');
}
const pattern = new RegExp('(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.{6,})')
if (!pattern.test(password)) {
throw new ValidationError('passwordRequeriments');
}
};
2020-05-06 16:44:42 +00:00
Self.on('resetPasswordRequest', async function(info) {
const renderer = loopback.template(path.resolve(__dirname, '../../views/reset-password.ejs'));
const html = renderer({
2020-06-29 11:31:48 +00:00
url: `${getUrl()}#/reset-password?access_token=${info.accessToken.id}`
2020-05-06 16:44:42 +00:00
});
await app.models.Email.send({
to: info.email,
2020-06-29 11:31:48 +00:00
from: getFrom(),
2020-05-06 16:44:42 +00:00
subject: 'Password reset',
html
});
2020-06-29 11:31:48 +00:00
console.log('> Sending password reset email to:', info.email);
2020-05-06 16:44:42 +00:00
});
};