2024-01-23 01:21:41 -05:00
|
|
|
import { SECRET_JWT_KEY } from '$env/static/private'
|
|
|
|
|
import { fail, redirect } from '@sveltejs/kit'
|
2024-01-25 03:05:13 -05:00
|
|
|
import { compare, hash } from 'bcrypt-ts'
|
2024-01-23 01:21:41 -05:00
|
|
|
import type { PageServerLoad, Actions } from './$types'
|
2024-01-23 01:22:49 -05:00
|
|
|
import { Users } from '$lib/server/users'
|
2024-01-25 19:50:26 -05:00
|
|
|
import jwt from 'jsonwebtoken'
|
2024-01-23 01:21:41 -05:00
|
|
|
|
|
|
|
|
export const load: PageServerLoad = async ({ url }) => {
|
|
|
|
|
const redirectLocation = url.searchParams.get('redirect')
|
|
|
|
|
return { redirectLocation }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const actions: Actions = {
|
|
|
|
|
signIn: async ({ request, cookies }) => {
|
|
|
|
|
const formData = await request.formData()
|
|
|
|
|
const { username, password, redirectLocation } = Object.fromEntries(formData)
|
2024-01-25 03:05:13 -05:00
|
|
|
|
2024-02-19 15:03:39 -05:00
|
|
|
const user = Users.getUsername(username.toString())
|
2024-01-25 03:05:13 -05:00
|
|
|
if (!user) return fail(400, { message: 'Invalid Username' })
|
|
|
|
|
|
2024-02-19 15:03:39 -05:00
|
|
|
const passwordValid = await compare(password.toString(), user.password)
|
2024-01-25 03:05:13 -05:00
|
|
|
if (!passwordValid) return fail(400, { message: 'Invalid Password' })
|
|
|
|
|
|
2024-01-25 19:50:26 -05:00
|
|
|
const authToken = jwt.sign({ id: user.id, username: user.username }, SECRET_JWT_KEY, { expiresIn: '100d' })
|
2024-01-25 03:05:13 -05:00
|
|
|
|
|
|
|
|
cookies.set('lazuli-auth', authToken, { path: '/', httpOnly: true, sameSite: 'strict', secure: false, maxAge: 60 * 60 * 24 * 100 })
|
|
|
|
|
|
|
|
|
|
if (redirectLocation) throw redirect(303, redirectLocation.toString())
|
|
|
|
|
throw redirect(303, '/')
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
newUser: async ({ request, cookies }) => {
|
|
|
|
|
const formData = await request.formData()
|
|
|
|
|
const { username, password } = Object.fromEntries(formData)
|
|
|
|
|
|
|
|
|
|
const passwordHash = await hash(password.toString(), 10)
|
|
|
|
|
const newUser = Users.addUser(username.toString(), passwordHash)
|
2024-02-19 15:03:39 -05:00
|
|
|
if (!newUser) return fail(400, { message: 'Username already in use' })
|
2024-01-25 03:05:13 -05:00
|
|
|
|
2024-02-19 15:03:39 -05:00
|
|
|
const authToken = jwt.sign({ id: newUser.id, username: newUser.username }, SECRET_JWT_KEY, { expiresIn: '100d' })
|
2024-01-25 03:05:13 -05:00
|
|
|
|
|
|
|
|
cookies.set('lazuli-auth', authToken, { path: '/', httpOnly: true, sameSite: 'strict', secure: false, maxAge: 60 * 60 * 24 * 100 })
|
|
|
|
|
|
|
|
|
|
throw redirect(303, '/')
|
2024-01-23 01:21:41 -05:00
|
|
|
},
|
|
|
|
|
}
|