diff --git a/packages/xo-server/src/index.mjs b/packages/xo-server/src/index.mjs index 1b0bd1db9..67bb1a41a 100644 --- a/packages/xo-server/src/index.mjs +++ b/packages/xo-server/src/index.mjs @@ -273,7 +273,8 @@ async function setUpPassport(express, xo, { authentication: authCfg, http: { coo })(req, res, next) } - if (req.cookies.token) { + const { token } = req.cookies + if (token !== undefined && (await xo.isValidAuthenticationToken(token))) { next() } else { req.flash('return-url', url) diff --git a/packages/xo-server/src/xo-mixins/authentication.mjs b/packages/xo-server/src/xo-mixins/authentication.mjs index c4901656a..f69f58336 100644 --- a/packages/xo-server/src/xo-mixins/authentication.mjs +++ b/packages/xo-server/src/xo-mixins/authentication.mjs @@ -221,22 +221,26 @@ export default class { return db.remove((await db.get(predicate)).filter(createPredicate(filter)).map(({ id }) => id)) } + async _getAuthenticationToken(id, properties) { + const token = await this._tokens.first(properties ?? id) + if (token !== undefined) { + unserialize(token) + + if (token.expiration > Date.now()) { + return token + } + + this._tokens.remove(id)::ignoreErrors() + } + } + async getAuthenticationToken(properties) { const id = typeof properties === 'string' ? properties : properties.id - const token = await this._tokens.first(properties) + const token = await this._getAuthenticationToken(id, properties) if (token === undefined) { throw noSuchAuthenticationToken(id) } - - unserialize(token) - - if (!(token.expiration > Date.now())) { - this._tokens.remove(id)::ignoreErrors() - - throw noSuchAuthenticationToken(id) - } - return token } @@ -261,6 +265,10 @@ export default class { return tokens } + async isValidAuthenticationToken(id) { + return (await this.getAuthenticationToken(id)) !== undefined + } + async updateAuthenticationToken(properties, { description }) { const token = await this.getAuthenticationToken(properties) patch(token, { description })