aboutsummaryrefslogtreecommitdiffstats
path: root/src/routes/(app)/register/+page.server.js
blob: f2b49e3f7a81dfafc435222b81272a5fc80d5bdb (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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import {
	NumberDictionary,
	uniqueNamesGenerator,
	colors,
	adjectives,
	animals
} from 'unique-names-generator';
import { fail, redirect } from '@sveltejs/kit';
import { fd, post, login } from '$lib/utils';

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

	let username = uniqueNamesGenerator({
		dictionaries: [animals, NumberDictionary.generate({ min: 10, max: 99 })],
		length: 2,
		separator: ''
	});

	let password = uniqueNamesGenerator({
		dictionaries: [colors, NumberDictionary.generate({ min: 100, max: 999 })],
		length: 2,
    separator: ''
	});

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

	return { index, username, password };
};

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

		let form = await fd(request);
		let { profile, username, password, cipher, salt, pubkey, loginRedirect } = form;
		let 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) {
			console.log(e);
			if (e.message.includes('taken')) error = e.message;
		}

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

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