added guest login

pull/3/head
TZGyn 2 years ago
parent 389c835494
commit c0ff2f0de8
Signed by: TZGyn
GPG Key ID: 122EAF77AE81FD4A

@ -6,13 +6,15 @@ export const handle: Handle = async ({ event, resolve }) => {
const pathname = event.url.pathname const pathname = event.url.pathname
const allowedPath = ['/login', '/signup', '/api/login', '/api/signup']
if (pathname === '/login' || pathname === 'signup') { if (pathname === '/login' || pathname === 'signup') {
if (event.locals.user) { if (event.locals.user) {
throw redirect(303, '/') throw redirect(303, '/')
} }
} }
if (pathname !== '/login' && pathname !== '/signup') { if (!allowedPath.includes(pathname)) {
if (!event.locals.user) { if (!event.locals.user) {
throw redirect(303, '/login') throw redirect(303, '/login')
} }

@ -2,8 +2,19 @@
import type { PageData } from './$types' import type { PageData } from './$types'
import ThemeToggle from '$lib/components/theme-toggle.svelte' import ThemeToggle from '$lib/components/theme-toggle.svelte'
import UserAuthForm from './(components)/user-auth-form.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 export let data: PageData
const guestLogin = async () => {
const response = await fetch('/api/login', { method: 'post' })
const data = await response.json()
if (data.success) {
goto('/')
}
}
</script> </script>
<div <div
@ -41,8 +52,9 @@
class="underline underline-offset-4 hover:text-primary" class="underline underline-offset-4 hover:text-primary"
> >
Here Here
</a>{' '} </a>
</p> </p>
<Button variant="ghost" on:click={guestLogin}>Guest</Button>
</div> </div>
</div> </div>
</div> </div>

@ -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' }))
}
}
Loading…
Cancel
Save