2020-04-02 17:27:31 +03:00
|
|
|
function SessionMiddleware({sessionService}) {
|
|
|
|
async function createSession(req, res, next) {
|
|
|
|
try {
|
|
|
|
await sessionService.createSessionForUser(req, res, req.user);
|
|
|
|
res.sendStatus(201);
|
|
|
|
} catch (err) {
|
|
|
|
next(err);
|
2018-10-02 11:35:23 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-02 17:27:31 +03:00
|
|
|
async function destroySession(req, res, next) {
|
2019-01-18 19:03:03 +03:00
|
|
|
try {
|
2020-04-02 17:27:31 +03:00
|
|
|
await sessionService.destroyCurrentSession(req);
|
|
|
|
res.sendStatus(204);
|
2019-01-18 19:03:03 +03:00
|
|
|
} catch (err) {
|
2020-04-02 17:27:31 +03:00
|
|
|
next(err);
|
2019-01-18 19:03:03 +03:00
|
|
|
}
|
2020-04-02 17:27:31 +03:00
|
|
|
}
|
2019-01-18 19:03:03 +03:00
|
|
|
|
2020-04-02 17:27:31 +03:00
|
|
|
async function authenticate(req, res, next) {
|
|
|
|
try {
|
|
|
|
const user = await sessionService.getUserForSession(req, res);
|
2020-10-23 17:34:41 +03:00
|
|
|
if (user) {
|
|
|
|
// Do not nullify `req.user` as it might have been already set
|
|
|
|
// in a previous middleware (authorize middleware).
|
|
|
|
req.user = user;
|
|
|
|
}
|
2020-04-02 17:27:31 +03:00
|
|
|
next();
|
|
|
|
} catch (err) {
|
|
|
|
next(err);
|
2019-01-18 19:03:03 +03:00
|
|
|
}
|
2020-04-02 17:27:31 +03:00
|
|
|
}
|
2019-01-18 19:03:03 +03:00
|
|
|
|
2020-04-02 17:27:31 +03:00
|
|
|
return {
|
|
|
|
createSession: createSession,
|
|
|
|
destroySession: destroySession,
|
|
|
|
authenticate: authenticate
|
|
|
|
};
|
|
|
|
}
|
2018-10-02 11:35:23 +03:00
|
|
|
|
2020-04-02 17:27:31 +03:00
|
|
|
module.exports = SessionMiddleware;
|