diff --git a/src/hooks.server.ts b/src/hooks.server.ts index c97f325..9797728 100644 --- a/src/hooks.server.ts +++ b/src/hooks.server.ts @@ -6,13 +6,15 @@ export const handle: Handle = async ({ event, resolve }) => { const pathname = event.url.pathname + const allowedPath = ['/login', '/signup', '/api/login', '/api/signup'] + if (pathname === '/login' || pathname === 'signup') { if (event.locals.user) { throw redirect(303, '/') } } - if (pathname !== '/login' && pathname !== '/signup') { + if (!allowedPath.includes(pathname)) { if (!event.locals.user) { throw redirect(303, '/login') } diff --git a/src/routes/(auth)/login/+page.svelte b/src/routes/(auth)/login/+page.svelte index 4d2ca85..30c26c7 100644 --- a/src/routes/(auth)/login/+page.svelte +++ b/src/routes/(auth)/login/+page.svelte @@ -2,8 +2,19 @@ import type { PageData } from './$types' import ThemeToggle from '$lib/components/theme-toggle.svelte' import UserAuthForm from './(components)/user-auth-form.svelte' + import { Button } from '$lib/components/ui/button' + import { goto } from '$app/navigation' export let data: PageData + + const guestLogin = async () => { + const response = await fetch('/api/login', { method: 'post' }) + + const data = await response.json() + if (data.success) { + goto('/') + } + }
Here - {' '} +

+
diff --git a/src/routes/api/login/+server.ts b/src/routes/api/login/+server.ts new file mode 100644 index 0000000..f736c6f --- /dev/null +++ b/src/routes/api/login/+server.ts @@ -0,0 +1,38 @@ +import type { RequestHandler } from './$types' +import { user as userSchema, session as sessionSchema } from '$lib/db/schema' +import { db } from '$lib/db' +import { nanoid } from 'nanoid' +import { eq } from 'drizzle-orm' + +export const GET: RequestHandler = async () => { + return new Response() +} + +export const POST: RequestHandler = async (event) => { + const users = await db + .select() + .from(userSchema) + .where(eq(userSchema.email, 'test@example.com')) + + const user = users[0] + const matchPassword = + user && (await Bun.password.verify('password', user.password)) + + if (user && matchPassword) { + const token = nanoid(32) + + const expiresAt = new Date() + expiresAt.setTime(expiresAt.getTime() + 4 * 60 * 60 * 1000) + + await db.insert(sessionSchema).values({ userId: user.id, token, expiresAt }) + + event.cookies.set('token', token, { + httpOnly: true, + sameSite: 'strict', + path: '/', + }) + return new Response(JSON.stringify({ success: true })) + } else { + return new Response(JSON.stringify({ hello: 'hello' })) + } +}