diff --git a/src/auth/magic_link/MagicLinkController.ts b/src/auth/magic_link/MagicLinkController.ts index a806227..ec006aa 100644 --- a/src/auth/magic_link/MagicLinkController.ts +++ b/src/auth/magic_link/MagicLinkController.ts @@ -116,32 +116,41 @@ export default class MagicLinkController extends Controll } protected async getLobby(req: Request, res: Response): Promise { - const link = await MagicLink.select() + const links = await MagicLink.select() .where('session_id', req.getSession().id) .sortBy('authorized') .where('used', 0) - .first(); - if (!link) { + .get(); + if (links.length === 0) { throw new NotFoundHttpError('magic link', req.url); } - if (!await link.isValid()) { - req.flash('error', 'This magic link has expired. Please try again.'); - res.redirect(link.getOrFail('original_url')); + let validLink; + for (const link of links) { + if (await link.isValid()) { + validLink = link; + } else { + req.flash('error', 'This magic link has expired. Please try again.'); + await link.delete(); + } + } + + if (!validLink) { + res.redirect(req.getIntendedUrl() || route('home')); return; } - if (await link.isAuthorized()) { - link.use(); - await link.save(); - await this.performAction(link, req, res); + if (await validLink.isAuthorized()) { + validLink.use(); + await validLink.save(); + await this.performAction(validLink, req, res); return; } res.render('magic_link_lobby', { - email: link.getOrFail('email'), - type: link.getOrFail('action_type'), - validUntil: link.getExpirationDate().getTime(), + email: validLink.getOrFail('email'), + type: validLink.getOrFail('action_type'), + validUntil: validLink.getExpirationDate().getTime(), websocketUrl: config.get('app.public_websocket_url') + this.magicLinkWebsocketPath, }); }