From c6758721ecd578b0c319c0c6d858fe932a65050a Mon Sep 17 00:00:00 2001 From: Julien Oculi Date: Thu, 20 Jun 2024 13:17:12 +0200 Subject: [PATCH] refactor(api): :recycle: use cxt session instead of getting it from request --- routes/api/magiclink/index.ts | 21 +++++++-------------- 1 file changed, 7 insertions(+), 14 deletions(-) diff --git a/routes/api/magiclink/index.ts b/routes/api/magiclink/index.ts index 831e46e..0c7bc88 100644 --- a/routes/api/magiclink/index.ts +++ b/routes/api/magiclink/index.ts @@ -1,10 +1,10 @@ import 'npm:iterator-polyfill' // Polyfill AsyncIterator -import { FreshContext, Handlers } from '$fresh/server.ts' +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 { SessionStore } from '../../../src/session/mod.ts' +import { SessionHandlers } 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' @@ -25,7 +25,7 @@ export async function getUserByMail(email: string): Promise { return user } -export const handler: Handlers = { +export const handler: SessionHandlers = { async POST(request, ctx) { const { email } = await request.json() as { email: string } @@ -42,8 +42,7 @@ export const handler: Handlers = { `${ctx.url.origin}/api/magiclink?token=${token}&redirect=/profil` // save token to session - const session = SessionStore.getFromRequest(request) - session?.flash(`MAGIC_LINK__${token}`, { + ctx.state.session.flash(`MAGIC_LINK__${token}`, { email, remoteId: remoteId(ctx), timestamp: Date.now(), @@ -70,22 +69,16 @@ export const handler: Handlers = { ) } }, - async GET(request, ctx) { + async GET(_request, ctx) { const token = ctx.url.searchParams.get('token') const redirect = ctx.url.searchParams.get('redirect') - const session = SessionStore.getFromRequest(request) - - // no session datas - if (session === undefined) { - return respondApi('error', 'no session datas', 401) - } // no token if (token === null) { return respondApi('error', 'no token provided', 400) } // wrong or timeout token - const entry = session.get(`MAGIC_LINK__${token}`) + const entry = ctx.state.session.get(`MAGIC_LINK__${token}`) const lifespan = Date.now() - 10 * 60 * 1_000 // ten minutes @@ -96,7 +89,7 @@ export const handler: Handlers = { // check remote id (same user/machine that has query the token) if (entry.remoteId === remoteId(ctx)) { const user = await getUserByMail(entry.email) - session.set('user', user) + ctx.state.session.set('user', user) if (redirect) { return Response.redirect(new URL(redirect, ctx.basePath))