2020-04-02 16:26:05 +03:00
|
|
|
# Session Service
|
|
|
|
|
|
|
|
## Usage
|
|
|
|
|
|
|
|
```js
|
|
|
|
const SessionService = require('@tryghost/session-service');
|
|
|
|
|
|
|
|
const sessionService = SessionService({
|
|
|
|
async getSession(req, res) {
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
require('express-session')(config)(req, res, (err) => {
|
|
|
|
if (err) {
|
|
|
|
reject(err);
|
|
|
|
}
|
|
|
|
resolve(req.session);
|
|
|
|
})
|
|
|
|
})
|
|
|
|
},
|
|
|
|
async findUserById({id}) {
|
|
|
|
return UserModel.findUserById(id);
|
|
|
|
},
|
|
|
|
getOriginOfRequest(req) {
|
|
|
|
return req.headers.origin;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
app.use(async (req, res, next) => {
|
|
|
|
try {
|
|
|
|
const user = await sessionService.getUserForSession(req, res);
|
|
|
|
req.user = user;
|
|
|
|
next();
|
|
|
|
} catch (err) {
|
|
|
|
next(err);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
app.post('/login', async (req, res) => {
|
|
|
|
try {
|
2021-01-25 19:00:15 +03:00
|
|
|
const user = await UserModel.verify(req.body);
|
|
|
|
await sessionService.createSessionForUser(req, res, user);
|
2020-04-02 16:26:05 +03:00
|
|
|
res.redirect('/home');
|
|
|
|
} catch (err) {
|
|
|
|
return next(err);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
app.post('/logout', async (req, res) => {
|
|
|
|
try {
|
2021-01-25 19:00:15 +03:00
|
|
|
await sessionService.destroyCurrentSession(req, res);
|
2020-04-02 16:26:05 +03:00
|
|
|
res.redirect('/login');
|
|
|
|
} catch (err) {
|
|
|
|
return next(err);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
```
|