2019-08-09 09:11:24 -05:00
|
|
|
const Promise = require('bluebird');
|
2021-10-08 09:11:26 -05:00
|
|
|
const tpl = require('@tryghost/tpl');
|
2020-05-22 13:22:20 -05:00
|
|
|
const errors = require('@tryghost/errors');
|
2019-08-09 09:11:24 -05:00
|
|
|
const models = require('../../models');
|
|
|
|
const auth = require('../../services/auth');
|
2020-05-05 13:37:53 -05:00
|
|
|
const api = require('./index');
|
2019-08-09 09:11:24 -05:00
|
|
|
|
2021-10-08 09:11:26 -05:00
|
|
|
const messages = {
|
|
|
|
accessDenied: 'Access Denied.'
|
|
|
|
};
|
|
|
|
|
2019-08-09 09:11:24 -05:00
|
|
|
const session = {
|
2019-09-11 04:28:55 -05:00
|
|
|
read(frame) {
|
2019-08-09 09:11:24 -05:00
|
|
|
/*
|
|
|
|
* TODO
|
|
|
|
* Don't query db for user, when new api http wrapper is in we can
|
|
|
|
* have direct access to req.user, we can also get access to some session
|
|
|
|
* inofrmation too and send it back
|
|
|
|
*/
|
2019-09-11 04:28:55 -05:00
|
|
|
return models.User.findOne({id: frame.options.context.user});
|
2019-08-09 09:11:24 -05:00
|
|
|
},
|
2019-09-11 04:28:55 -05:00
|
|
|
add(frame) {
|
|
|
|
const object = frame.data;
|
|
|
|
|
2019-08-09 09:11:24 -05:00
|
|
|
if (!object || !object.username || !object.password) {
|
2020-05-22 13:22:20 -05:00
|
|
|
return Promise.reject(new errors.UnauthorizedError({
|
2021-10-08 09:11:26 -05:00
|
|
|
message: tpl(messages.accessDenied)
|
2019-08-09 09:11:24 -05:00
|
|
|
}));
|
|
|
|
}
|
|
|
|
|
|
|
|
return models.User.check({
|
|
|
|
email: object.username,
|
|
|
|
password: object.password
|
|
|
|
}).then((user) => {
|
|
|
|
return Promise.resolve((req, res, next) => {
|
|
|
|
req.brute.reset(function (err) {
|
|
|
|
if (err) {
|
|
|
|
return next(err);
|
|
|
|
}
|
|
|
|
req.user = user;
|
|
|
|
auth.session.createSession(req, res, next);
|
|
|
|
});
|
|
|
|
});
|
2020-05-05 13:37:53 -05:00
|
|
|
}).catch(async (err) => {
|
2021-12-01 05:22:01 -05:00
|
|
|
if (!errors.utils.isGhostError(err)) {
|
2020-05-22 13:22:20 -05:00
|
|
|
throw new errors.UnauthorizedError({
|
2021-10-08 09:11:26 -05:00
|
|
|
message: tpl(messages.accessDenied),
|
2020-05-05 13:37:53 -05:00
|
|
|
err
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
if (err.errorType === 'PasswordResetRequiredError') {
|
|
|
|
await api.authentication.generateResetToken({
|
|
|
|
passwordreset: [{
|
|
|
|
email: object.username
|
2020-05-06 07:19:47 -05:00
|
|
|
}]
|
2020-05-05 13:37:53 -05:00
|
|
|
}, frame.options.context);
|
|
|
|
}
|
|
|
|
|
|
|
|
throw err;
|
2019-08-09 09:11:24 -05:00
|
|
|
});
|
|
|
|
},
|
|
|
|
delete() {
|
|
|
|
return Promise.resolve((req, res, next) => {
|
|
|
|
auth.session.destroySession(req, res, next);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = session;
|