aboutsummaryrefslogtreecommitdiffstats
path: root/src/routes/(static)/login/+page.server.ts
blob: ce343790654c1b565c97151d8b2cac881142ea60 (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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import { PUBLIC_COINOS_URL } from "$env/static/public";
import { fd, get, login, post } from "$lib/utils";
import { fail, redirect } from "@sveltejs/kit";

export const load = async ({ parent }) => {
	const { user } = await parent();
	if (user?.pubkey) redirect(307, `/${user.username}`);
	const { challenge } = await get("/challenge");
	return { challenge };
};

export const actions = {
	login: async ({ cookies, request }) => {
		const form = await fd(request);
		let { username, password, token, loginRedirect, recaptcha } = form;
    username = username.split("@")[0];

		const user = {
			username,
			password,
			token,
			recaptcha,
		};

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

		try {
			await login(user, cookies, request.headers.get("cf-connecting-ip"), request.headers.get("host"));
		} catch (e) {
			const { message } = e as Error;
			return fail(400, { error: "Login failed", message, ...form });
		}

		redirect(307, loginRedirect || `/${user.username}`);
	},

	nostr: async ({ cookies, fetch, request }) => {
		const form = await fd(request);
		let { challenge, event, loginRedirect, recaptcha } = form;
		if (loginRedirect === "null") loginRedirect = undefined;
		event = JSON.parse(event);

		const maxAge = 380 * 24 * 60 * 60;

		const res = await fetch(`${PUBLIC_COINOS_URL}/nostrAuth`, {
			method: "POST",
			body: JSON.stringify({ challenge, event, recaptcha }),
			headers: {
				"content-type": "application/json",
				accept: "application/json",
				"cf-connecting-ip": request.headers.get("cf-connecting-ip"),
				"x-forwarded-host": request.headers.get("host"),
			},
		});

		const text = await res.text();

		if (res.status === 401) {
			if (text.startsWith("2fa")) throw new Error("2fa");
			throw new Error(text);
		}

		const { user, token } = JSON.parse(text);
		if (!token) throw new Error("Login failed");
		const { username, language } = user;

		const expires = new Date();
		expires.setSeconds(expires.getSeconds() + maxAge);

		const opts = { path: "/", expires };
		if (language) cookies.set("lang", language, opts);
		cookies.set("username", username, opts);
		cookies.set("token", token, opts);

		redirect(307, loginRedirect || `/${username}`);
	},
};