mirror of
https://github.com/spchcap/speech.capital.git
synced 2026-01-14 16:48:44 +00:00
Feat: Verify user from pass_hash in cookie
This commit is contained in:
@@ -1,16 +1,18 @@
|
|||||||
const json = (d, o) => new Response(JSON.stringify(d), { ...o, headers: { 'Content-Type': 'application/json', ...(o?.headers || {}) } });
|
const json = (d, o) => new Response(JSON.stringify(d), { ...o, headers: { 'Content-Type': 'application/json', ...(o?.headers || {}) } });
|
||||||
|
const cookie = c => (c.match(/auth_user=([^;]+)/)?.[1] || null);
|
||||||
|
const hash = c => (c.match(/auth_hash=([^;]+)/)?.[1] || null);
|
||||||
|
const tsEq=(a,b)=>{if(!a||!b)return!1;let d=a.length^b.length;for(let i=0;i<a.length;i++)d|=a.charCodeAt(i)^b.charCodeAt(i);return d===0};
|
||||||
|
const clear = ()=>{const o=`Domain=.speech.capital; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT`;return {'Set-Cookie':`auth_user=; ${o}`,'Set-Cookie':`auth_hash=; ${o}`}};
|
||||||
|
|
||||||
export async function onRequest({ request, env }) {
|
export async function onRequest({ request, env }) {
|
||||||
const sid = (request.headers.get('Cookie') || '').match(/session_id=([^;]+)/)?.[1];
|
const c = request.headers.get('Cookie') || '';
|
||||||
if (!sid) return json({ user: null });
|
const u = cookie(c), h = hash(c);
|
||||||
|
if (!u || !h) return json({ user: null });
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const user = await env.D1_SPCHCAP.prepare(
|
const user = await env.D1_SPCHCAP.prepare('SELECT id, username, role, pass_hash FROM users WHERE username = ?').bind(u).first();
|
||||||
`SELECT u.id,u.username,u.role FROM users u JOIN sessions s ON u.id=s.user_id
|
if (user && tsEq(user.pass_hash, h)) return json({ user: { id: user.id, username: user.username, role: user.role } });
|
||||||
WHERE s.id=? AND s.expires_at>CURRENT_TIMESTAMP`
|
return json({ user: null }, { headers: clear() });
|
||||||
).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) {
|
} catch (e) {
|
||||||
return json({ error: { message: e.message } }, { status: 500 });
|
return json({ error: { message: e.message } }, { status: 500 });
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user