feat(xo-server): only create a single token per web client (and user)

Related to e07e2d3cc

Similar to 581b42fa9
This commit is contained in:
Julien Fontanet 2023-11-09 17:07:34 +01:00
parent a8aac295eb
commit 96025df12f
2 changed files with 17 additions and 1 deletions

View File

@ -8,6 +8,7 @@
> Users must be able to say: “Nice enhancement, I'm eager to test it”
- [REST API] Add `users` collection
- [Authentication] Re-use existing token instead of creating a new one when connecting with the same user on the same browser
### Bug fixes

View File

@ -214,10 +214,25 @@ async function setUpPassport(express, xo, { authentication: authCfg, http: { coo
const PERMANENT_VALIDITY = ifDef(authCfg.permanentCookieValidity, parseDuration)
const SESSION_VALIDITY = ifDef(authCfg.sessionCookieValidity, parseDuration)
const TEN_YEARS = 10 * 365 * 24 * 60 * 60 * 1e3
const setToken = async (req, res, next) => {
let { clientId } = req.cookies
if (clientId === undefined) {
clientId = Math.random().toString(36).slice(2)
res.cookie('clientId', clientId, {
...cookieCfg,
// no reason for this entry to ever expire, can be set to a long duration
maxAge: TEN_YEARS,
})
}
const { user, isPersistent } = req.session
const token = await xo.createAuthenticationToken({
description: 'web sign in',
client: {
id: clientId,
},
description: req.get('user-agent') ?? 'unknown browser',
expiresIn: isPersistent ? PERMANENT_VALIDITY : SESSION_VALIDITY,
userId: user.id,
})