refactor(api): ♻️ use cxt session instead of getting it from request
This commit is contained in:
parent
d8b79987ca
commit
c6758721ec
|
@ -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<User | undefined> {
|
|||
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<MagicLinkInfos>(`MAGIC_LINK__${token}`, {
|
||||
ctx.state.session.flash<MagicLinkInfos>(`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<MagicLinkInfos>(`MAGIC_LINK__${token}`)
|
||||
const entry = ctx.state.session.get<MagicLinkInfos>(`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))
|
||||
|
|
Loading…
Reference in a new issue