2020-04-30 22:26:12 +03:00
|
|
|
const errors = require('@tryghost/errors');
|
2021-10-08 17:21:22 +03:00
|
|
|
const tpl = require('@tryghost/tpl');
|
2019-07-17 13:28:16 +03:00
|
|
|
const models = require('../../models');
|
2020-08-11 16:01:16 +03:00
|
|
|
const security = require('@tryghost/security');
|
2021-10-08 17:21:22 +03:00
|
|
|
const messages = {inviteNotFound: 'Invite not found.',
|
|
|
|
inviteExpired: 'Invite is expired.',
|
|
|
|
inviteEmailAlreadyExist: {
|
|
|
|
message: 'Could not create an account, email is already in use.',
|
|
|
|
context: 'Attempting to create an account with existing email address.',
|
|
|
|
help: 'Use different email address to register your account.'
|
|
|
|
}};
|
2019-07-17 13:28:16 +03:00
|
|
|
|
|
|
|
async function accept(invitation) {
|
|
|
|
const data = invitation.invitation[0];
|
|
|
|
const inviteToken = security.url.decodeBase64(data.token);
|
|
|
|
const options = {context: {internal: true}};
|
|
|
|
|
|
|
|
let invite = await models.Invite.findOne({token: inviteToken, status: 'sent'}, options);
|
|
|
|
|
|
|
|
if (!invite) {
|
2021-10-08 17:21:22 +03:00
|
|
|
throw new errors.NotFoundError({message: tpl(messages.inviteNotFound)});
|
2019-07-17 13:28:16 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
if (invite.get('expires') < Date.now()) {
|
2021-10-08 17:21:22 +03:00
|
|
|
throw new errors.NotFoundError({message: tpl(messages.inviteExpired)});
|
2019-07-17 13:28:16 +03:00
|
|
|
}
|
|
|
|
|
2020-09-09 02:58:53 +03:00
|
|
|
let user = await models.User.findOne({email: data.email});
|
|
|
|
if (user) {
|
|
|
|
throw new errors.ValidationError({
|
2021-10-08 17:21:22 +03:00
|
|
|
message: tpl(messages.inviteEmailAlreadyExist.message),
|
|
|
|
context: tpl(messages.inviteEmailAlreadyExist.context),
|
|
|
|
help: tpl(messages.inviteEmailAlreadyExist.help)
|
2020-09-09 02:58:53 +03:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2019-07-17 13:28:16 +03:00
|
|
|
await models.User.add({
|
|
|
|
email: data.email,
|
|
|
|
name: data.name,
|
|
|
|
password: data.password,
|
|
|
|
roles: [invite.toJSON().role_id]
|
|
|
|
}, options);
|
|
|
|
|
|
|
|
return invite.destroy(options);
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = accept;
|