mirror of https://github.com/TZGyn/shortener
added protected routes
parent
32d6696365
commit
2821aef5d7
@ -0,0 +1,23 @@
|
||||
import { authenticateUser } from '$lib/server/auth'
|
||||
import { redirect, type Handle } from '@sveltejs/kit'
|
||||
|
||||
export const handle: Handle = async ({ event, resolve }) => {
|
||||
event.locals.user = await authenticateUser(event)
|
||||
|
||||
const pathname = event.url.pathname
|
||||
|
||||
if (pathname === '/login' || pathname === 'signup') {
|
||||
if (event.locals.user) {
|
||||
throw redirect(303, '/')
|
||||
}
|
||||
}
|
||||
|
||||
if (pathname !== '/login' && pathname !== '/signup') {
|
||||
if (!event.locals.user) {
|
||||
throw redirect(303, '/login')
|
||||
}
|
||||
}
|
||||
const response = await resolve(event)
|
||||
|
||||
return response
|
||||
}
|
||||
@ -0,0 +1,37 @@
|
||||
import type { RequestEvent } from '@sveltejs/kit'
|
||||
import { db } from '$lib/db'
|
||||
import { session as sessionSchema } from '$lib/db/schema'
|
||||
import { and, eq, gt } from 'drizzle-orm'
|
||||
|
||||
export const getUserFromSessionToken = async (token: string) => {
|
||||
const now = new Date()
|
||||
const sessions = await db
|
||||
.select()
|
||||
.from(sessionSchema)
|
||||
.where(
|
||||
and(eq(sessionSchema.token, token), gt(sessionSchema.expiresAt, now)),
|
||||
)
|
||||
|
||||
const session = sessions[0]
|
||||
|
||||
if (!session) {
|
||||
return null
|
||||
}
|
||||
return session.userId
|
||||
}
|
||||
|
||||
export const authenticateUser = async (event: RequestEvent) => {
|
||||
const { cookies } = event
|
||||
const sessionToken = cookies.get('token')
|
||||
|
||||
if (!sessionToken) {
|
||||
return null
|
||||
}
|
||||
|
||||
console.log(sessionToken)
|
||||
|
||||
const user = await getUserFromSessionToken(sessionToken)
|
||||
console.log(user)
|
||||
|
||||
return user
|
||||
}
|
||||
Loading…
Reference in New Issue