From 7568cb43a6e6655dd3f9bce0d99baebab239ad1c Mon Sep 17 00:00:00 2001 From: Julien Oculi Date: Thu, 20 Jun 2024 14:52:16 +0200 Subject: [PATCH] fix(api): :bug: 3rd party cookies maybe blocked when opening magic link --- routes/api/magiclink/index.ts | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/routes/api/magiclink/index.ts b/routes/api/magiclink/index.ts index 0713141..25734ba 100644 --- a/routes/api/magiclink/index.ts +++ b/routes/api/magiclink/index.ts @@ -4,7 +4,7 @@ import 'npm:iterator-polyfill' import { FreshContext } from '$fresh/server.ts' import { Contact, type Mail, send } from '@cohabit/cohamail/mod.ts' import { magicLinkTemplate } from '@cohabit/cohamail/templates/mod.ts' -import { SessionHandlers } from '../../../src/session/mod.ts' +import { SessionHandlers, SessionStore } from '../../../src/session/mod.ts' import { respondApi } from '../../../src/utils.ts' import { sleep } from '@jotsr/delayed' import { User } from '@cohabit/ressources_manager/src/models/mod.ts' @@ -39,7 +39,7 @@ export const handler: SessionHandlers = { // generate magic link const token = crypto.randomUUID() const endpoint = - `${ctx.url.origin}/api/magiclink?token=${token}&redirect=/profil` + `${ctx.url.origin}/api/magiclink?token=${token}&session=${ctx.state.session.uuid}&redirect=/profil` // save token to session ctx.state.session.flash(`MAGIC_LINK__${token}`, { @@ -72,11 +72,21 @@ export const handler: SessionHandlers = { async GET(request, ctx) { const token = ctx.url.searchParams.get('token') const redirect = ctx.url.searchParams.get('redirect') + const sessionId = ctx.url.searchParams.get('session') - // no token - if (token === null) { - return respondApi('error', 'no token provided', 400) + // no token or sessionId + if (token === null || sessionId === null) { + return respondApi('error', 'no token or session provided', 400) } + + // set session if 3rd party cookies was blocked + ctx.state.session = ctx.state.session ?? SessionStore.getSession(sessionId) + + // no session available + if (ctx.state.session === null) { + return respondApi('error', 'no session datas', 401) + } + // wrong or timeout token const entry = ctx.state.session.get(`MAGIC_LINK__${token}`)