2018-10-03 16:45:42 +03:00
|
|
|
const Promise = require('bluebird');
|
2021-10-05 12:36:12 +03:00
|
|
|
const tpl = require('@tryghost/tpl');
|
2020-05-22 21:22:20 +03:00
|
|
|
const errors = require('@tryghost/errors');
|
2018-10-03 16:45:42 +03:00
|
|
|
const models = require('../../models');
|
|
|
|
const auth = require('../../services/auth');
|
2020-05-05 21:37:53 +03:00
|
|
|
const api = require('./index');
|
2018-10-03 16:45:42 +03:00
|
|
|
|
2021-10-05 12:36:12 +03:00
|
|
|
const messages = {
|
|
|
|
authAccessDenied: 'Access denied.'
|
|
|
|
};
|
|
|
|
|
2018-10-03 16:45:42 +03:00
|
|
|
const session = {
|
2019-09-11 12:28:55 +03:00
|
|
|
read(frame) {
|
2018-10-03 16:45:42 +03: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 12:28:55 +03:00
|
|
|
return models.User.findOne({id: frame.options.context.user});
|
2018-10-03 16:45:42 +03:00
|
|
|
},
|
2019-09-11 12:28:55 +03:00
|
|
|
add(frame) {
|
|
|
|
const object = frame.data;
|
|
|
|
|
2018-10-03 16:45:42 +03:00
|
|
|
if (!object || !object.username || !object.password) {
|
2020-05-22 21:22:20 +03:00
|
|
|
return Promise.reject(new errors.UnauthorizedError({
|
2021-10-05 12:36:12 +03:00
|
|
|
message: tpl(messages.authAccessDenied)
|
2018-10-03 16:45:42 +03:00
|
|
|
}));
|
|
|
|
}
|
|
|
|
|
|
|
|
return models.User.check({
|
|
|
|
email: object.username,
|
|
|
|
password: object.password
|
|
|
|
}).then((user) => {
|
|
|
|
return Promise.resolve((req, res, next) => {
|
2018-10-18 11:58:29 +03:00
|
|
|
req.brute.reset(function (err) {
|
|
|
|
if (err) {
|
|
|
|
return next(err);
|
|
|
|
}
|
|
|
|
req.user = user;
|
|
|
|
auth.session.createSession(req, res, next);
|
|
|
|
});
|
2018-10-03 16:45:42 +03:00
|
|
|
});
|
2020-05-05 21:37:53 +03:00
|
|
|
}).catch(async (err) => {
|
2021-12-01 13:22:01 +03:00
|
|
|
if (!errors.utils.isGhostError(err)) {
|
2020-05-22 21:22:20 +03:00
|
|
|
throw new errors.UnauthorizedError({
|
2021-10-05 12:36:12 +03:00
|
|
|
message: tpl(messages.authAccessDenied),
|
2020-05-05 21:37:53 +03:00
|
|
|
err
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
if (err.errorType === 'PasswordResetRequiredError') {
|
|
|
|
await api.authentication.generateResetToken({
|
|
|
|
passwordreset: [{
|
|
|
|
email: object.username
|
2020-05-06 15:19:47 +03:00
|
|
|
}]
|
2020-05-05 21:37:53 +03:00
|
|
|
}, frame.options.context);
|
|
|
|
}
|
|
|
|
|
|
|
|
throw err;
|
2018-10-03 16:45:42 +03:00
|
|
|
});
|
|
|
|
},
|
|
|
|
delete() {
|
|
|
|
return Promise.resolve((req, res, next) => {
|
|
|
|
auth.session.destroySession(req, res, next);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = session;
|