|
1 | | -import { CookiesManager } from '$lib/cookies_manager' |
2 | | -import { db } from '$lib/database' |
3 | | -import { NodemailerManager } from '$lib/nodemailer_manager' |
4 | | -import type { Actions, PageServerLoad } from '.svelte-kit/types/src/routes/register/$types' |
5 | | -import { invalid, redirect } from '@sveltejs/kit' |
6 | | -import bcrypt from 'bcrypt' |
| 1 | +import type { PageServerLoad } from '.svelte-kit/types/src/routes/$types' |
| 2 | +import { redirect } from '@sveltejs/kit' |
7 | 3 |
|
8 | | -export const load: PageServerLoad = async ({ locals, url }) => { |
9 | | - if (locals.user) { |
10 | | - const redirect_url = url.searchParams.get('redirect') || ' /' |
11 | | - throw redirect(302, redirect_url) |
12 | | - } |
13 | | -} |
14 | | - |
15 | | -async function sendMail(username: string) { |
16 | | - const nodemailerManager = new NodemailerManager() |
17 | | - |
18 | | - try { |
19 | | - await nodemailerManager.sendMail( |
20 | | - 'info@sinproject.net', |
21 | | - 'SvelteKit Authentication', |
22 | | - `${username} logged in ` |
23 | | - ) |
24 | | - } catch (error) { |
25 | | - console.error(error) |
26 | | - } |
27 | | -} |
28 | | - |
29 | | -export const actions: Actions = { |
30 | | - default: async ({ cookies, request }) => { |
31 | | - const data = await request.formData() |
32 | | - const username = data.get('username') as string |
33 | | - const password = data.get('password') as string |
34 | | - |
35 | | - if (!username || !password) return invalid(404, { missing: true }) |
36 | | - |
37 | | - const user = await db.user.findUnique({ where: { username } }) |
38 | | - |
39 | | - if (!user) return invalid(400, { credentials: true }) |
40 | | - |
41 | | - const password_valid = await bcrypt.compare(password, user.password) |
42 | | - |
43 | | - if (!password_valid) return invalid(400, { credentials: true }) |
44 | | - |
45 | | - sendMail(username) |
46 | | - |
47 | | - const auth_token = await db.authToken.upsert({ |
48 | | - where: { user_id: user.id }, |
49 | | - update: { token: crypto.randomUUID() }, |
50 | | - create: { user_id: user.id, token: crypto.randomUUID() }, |
51 | | - }) |
52 | | - |
53 | | - new CookiesManager(cookies).setSessionId(auth_token.token) |
54 | | - |
55 | | - return { success: true } |
56 | | - }, |
| 4 | +export const load: PageServerLoad = async ({ locals }) => { |
| 5 | + if (locals.user) throw redirect(302, '/') |
57 | 6 | } |
0 commit comments