aboutsummaryrefslogtreecommitdiffstats
path: root/src/routes/(static)/register/+page.server.ts
blob: 2dffef0191d813cff6574b3410301e48eab65276 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import { fail, redirect } from "@sveltejs/kit";
import { fd, post, login } from "$lib/utils";

export const load = async ({ parent }) => {
	const { user } = await parent();
	if (user) redirect(307, `/${user.username}`);

	const index = Math.floor(Math.random() * 64) + 1;

	return { index };
};

export const actions = {
	default: async ({ cookies, request }) => {
		const ip = request.headers.get("cf-connecting-ip");

		const form = await fd(request);
		let { profile, username, password, cipher, salt, pubkey, loginRedirect } =
			form;
		const user = { profile, username, password, cipher, salt, pubkey };
		let error;

		if (loginRedirect === "undefined") loginRedirect = undefined;

		try {
			await post("/register", { user }, { "cf-connecting-ip": ip });
		} catch (e: any) {
			error = e.message;
		}

		try {
			await login(user, cookies, ip);
			error = null;
		} catch (e: any) {
			error ||= e.message;
		}

		if (error) return fail(400, { error });
		redirect(307, loginRedirect || `/${user.username}`);
	},
};