aboutsummaryrefslogtreecommitdiffstats
path: root/src/routes/+layout.server.js
blob: 9edc43e14d000efd66df263d339a89751981eaea (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
import { error, redirect } from '@sveltejs/kit';
import cookie from 'cookie';
import { protectedRoutes } from '$lib/utils';
import { get, post, auth } from '$lib/utils';

const btc = import.meta.env.VITE_BTC;

export async function load({ request, setHeaders, url, params }) {
	let { token } = cookie.parse(request.headers.get('cookie') || '');
	let user;
	let rates;

	if (token) {
		try {
			user = await get('/me', { accept: 'application/json', authorization: `Bearer ${token}` });
		} catch (e) {
			throw redirect(301, '/logout');
		}

		if (protectedRoutes.find((p) => url.pathname.match(p))) {
			if (user.username !== params.username) throw error(404, 'user not found');
		}

		let account = user.accounts.find((a) => a.asset === btc && !a.pubkey);
		if (account) {
			let { id } = account;
			if (user.account_id !== id) {
				user = await post('/shiftAccount', { id }, auth(request));
			}
		}
	}

	rates = await get('/rates');

	return { user, token, rates };
}