silphius/app/session.server.js
2024-06-15 16:31:04 -05:00

35 lines
1.0 KiB
JavaScript

import {join} from 'node:path';
import {createFileSessionStorage} from "@remix-run/node";
import {redirect} from '@remix-run/react';
const {getSession, commitSession, destroySession} = createFileSessionStorage({
dir: join(import.meta.dirname, 'data', 'remote', 'sessions'),
cookie: {
secrets: ["r3m1xr0ck5"],
sameSite: true,
},
});
export {getSession, commitSession, destroySession};
export async function juggleSession(request) {
const session = await getSession(request.headers.get('Cookie'));
const url = new URL(request.url);
if (!session.get('id')) {
if (!url.searchParams.has('session')) {
const [id] = crypto.getRandomValues(new Uint32Array(1));
session.set('id', id);
throw redirect(`${url.origin}${url.pathname}?session`, {
headers: {
'Set-Cookie': await commitSession(session),
},
});
}
}
else if (url.searchParams.has('session')) {
throw redirect(`${url.origin}${url.pathname}`);
}
return session ? session : {id: 0};
}