From 48cda62678a588a7b4bda8652d086e72fd266205 Mon Sep 17 00:00:00 2001 From: multipleof4 Date: Thu, 2 Oct 2025 11:07:54 -0700 Subject: [PATCH] Feat: Endpoint to get current user from session --- functions/api/user.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 functions/api/user.js diff --git a/functions/api/user.js b/functions/api/user.js new file mode 100644 index 0000000..c0c7189 --- /dev/null +++ b/functions/api/user.js @@ -0,0 +1,17 @@ +const json = (d, o) => new Response(JSON.stringify(d), { ...o, headers: { 'Content-Type': 'application/json', ...(o?.headers || {}) } }); + +export async function onRequest({ request, env }) { + const sid = (request.headers.get('Cookie') || '').match(/session_id=([^;]+)/)?.[1]; + if (!sid) return json({ user: null }); + try { + const user = await env.D1_SPCHCAP.prepare( + `SELECT u.id,u.username,u.role FROM users u JOIN sessions s ON u.id=s.user_id + WHERE s.id=? AND s.expires_at>CURRENT_TIMESTAMP` + ).bind(sid).first(); + if(user) return json({ user }); + const cookie=`session_id=; Domain=.speech.capital; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT`; + return json({ user: null }, { headers: { 'Set-Cookie': cookie } }); + } catch (e) { + return json({ error: { message: e.message } }, { status: 500 }); + } +}