migrate auth v2 code
This commit is contained in:
@@ -1,9 +1,9 @@
|
||||
import { redirect } from '@sveltejs/kit';
|
||||
import type { RequestEvent } from '@sveltejs/kit';
|
||||
import { PROXY_URL } from '$app/env/public';
|
||||
import { pbAdmin } from '$lib/server/pocketbase';
|
||||
|
||||
export function getSession(event: RequestEvent) {
|
||||
return event.locals.session;
|
||||
return event.locals.user;
|
||||
}
|
||||
|
||||
export function requireAuth(event: RequestEvent) {
|
||||
@@ -14,72 +14,14 @@ export function requireAuth(event: RequestEvent) {
|
||||
return session;
|
||||
}
|
||||
|
||||
export async function signup(email: string, password: string, famName: string, parentName?: string) {
|
||||
const res = await fetch(`${PROXY_URL}/api/admin/signup`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email, password, famName, parentName }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error || 'Signup failed');
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function login(email: string, password: string) {
|
||||
console.log(email);
|
||||
const res = await fetch(`${PROXY_URL}/api/admin/login`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email, password }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error || 'Login failed');
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function joinMember(inviteCode: string, name: string, deviceToken: string) {
|
||||
const res = await fetch(`${PROXY_URL}/api/members/join`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ inviteCode, name, deviceToken }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error || 'Join failed');
|
||||
return data;
|
||||
}
|
||||
|
||||
export function setSessionCookie(event: RequestEvent, session: { famId: string; userId: string; famSlug: string }) {
|
||||
event.cookies.set('session', JSON.stringify(session), {
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
path: '/',
|
||||
maxAge: 60 * 60 * 24 * 30,
|
||||
secure: false,
|
||||
});
|
||||
}
|
||||
|
||||
export function setDeviceTokenCookie(event: RequestEvent, token: string) {
|
||||
event.cookies.set('device_token', token, {
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
path: '/',
|
||||
maxAge: 60 * 60 * 24 * 365,
|
||||
secure: false,
|
||||
});
|
||||
}
|
||||
|
||||
export function setPbTokenCookie(event: RequestEvent, token: string) {
|
||||
event.cookies.set('pb_token', token, {
|
||||
httpOnly: false,
|
||||
sameSite: 'lax',
|
||||
path: '/',
|
||||
maxAge: 60 * 60 * 24,
|
||||
secure: false,
|
||||
});
|
||||
}
|
||||
|
||||
export function clearSession(event: RequestEvent) {
|
||||
event.cookies.delete('session', { path: '/' });
|
||||
event.cookies.delete('pb_token', { path: '/' });
|
||||
event.cookies.delete('device_token', { path: '/' });
|
||||
}
|
||||
|
||||
// Resolve the fam slug + admin display name used for the post-login redirect.
|
||||
export async function getFamContext(famId: string) {
|
||||
const fam = await pbAdmin.getOne('fams', famId).catch(() => null);
|
||||
return { famSlug: fam?.slug || famId, famName: fam?.name || '' };
|
||||
}
|
||||
@@ -2,11 +2,11 @@ import type { RequestEvent } from '@sveltejs/kit';
|
||||
import { PROXY_URL } from '$app/env/public';
|
||||
|
||||
function sessionHeaders(event: RequestEvent): Record<string, string> {
|
||||
const s = event.locals.session;
|
||||
if (!s) return {};
|
||||
const u = event.locals.user;
|
||||
if (!u) return {};
|
||||
return {
|
||||
'x-session-famid': s.famId,
|
||||
'x-session-userid': s.userId,
|
||||
'x-session-famid': u.famId,
|
||||
'x-session-userid': u.id,
|
||||
'Content-Type': 'application/json'
|
||||
};
|
||||
}
|
||||
@@ -93,9 +93,6 @@ export const hono = {
|
||||
async verify(event: RequestEvent, famId: string) {
|
||||
return request('GET', `/api/admin/${famId}/verify`, undefined, sessionHeaders(event));
|
||||
},
|
||||
async regenInvite(event: RequestEvent, famId: string) {
|
||||
return request('POST', `/api/admin/${famId}/regen-invite`, undefined, sessionHeaders(event));
|
||||
},
|
||||
async weeklySummary(event: RequestEvent, famId: string) {
|
||||
return request('GET', `/api/admin/${famId}/weekly-summary`, undefined, sessionHeaders(event));
|
||||
},
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
import { PB_EMAIL, PB_PASSWORD } from '$app/env/private';
|
||||
import { SERVER_IP } from '$app/env/public';
|
||||
export const PB_ENDPOINT = import.meta.env.PROD ? '/pb' : `http://${SERVER_IP}:8090`;
|
||||
|
||||
let token: string | null = null;
|
||||
let tokenExpiry = 0;
|
||||
|
||||
async function ensureToken(): Promise<string> {
|
||||
if (token && Date.now() < tokenExpiry) return token;
|
||||
const res = await fetch(`${PB_ENDPOINT}/api/collections/_superusers/auth-with-password`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ identity: PB_EMAIL, password: PB_PASSWORD }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(`PB admin auth failed: ${JSON.stringify(data)}`);
|
||||
token = data.token;
|
||||
tokenExpiry = Date.now() + 23 * 60 * 60 * 1000;
|
||||
return token!;
|
||||
}
|
||||
|
||||
export const pbAdmin = {
|
||||
async getList(collection: string, filter = '') {
|
||||
const t = await ensureToken();
|
||||
const params = new URLSearchParams();
|
||||
if (filter) params.set('filter', filter);
|
||||
params.set('perPage', '200');
|
||||
const res = await fetch(`${PB_ENDPOINT}/api/collections/${collection}/records?${params}`, {
|
||||
headers: { Authorization: `Bearer ${t}` },
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(`PB list ${collection}: ${JSON.stringify(data)}`);
|
||||
return data.items || [];
|
||||
},
|
||||
|
||||
async getOne(collection: string, id: string) {
|
||||
const t = await ensureToken();
|
||||
const res = await fetch(`${PB_ENDPOINT}/api/collections/${collection}/records/${id}`, {
|
||||
headers: { Authorization: `Bearer ${t}` },
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(`PB get ${collection}/${id}: ${JSON.stringify(data)}`);
|
||||
return data;
|
||||
},
|
||||
|
||||
async update(collection: string, id: string, data: Record<string, unknown>) {
|
||||
const t = await ensureToken();
|
||||
const res = await fetch(`${PB_ENDPOINT}/api/collections/${collection}/records/${id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${t}` },
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
const result = await res.json();
|
||||
if (!res.ok) throw new Error(`PB update ${collection}/${id}: ${JSON.stringify(result)}`);
|
||||
return result;
|
||||
},
|
||||
};
|
||||
Reference in New Issue
Block a user