43 lines
1.4 KiB
TypeScript
43 lines
1.4 KiB
TypeScript
import { BASE_URL } from '$env/static/private';
|
|
import { Logger } from '$lib/log';
|
|
import { SpotifyPlaylistAdder } from '$lib/server/playlist/spotifyPlaylistAdder';
|
|
import { redirect } from '@sveltejs/kit';
|
|
import type { PageServerLoad } from './$types';
|
|
const { DEV } = import.meta.env;
|
|
|
|
const logger = new Logger('SpotifyAuth');
|
|
|
|
export const load: PageServerLoad = async ({ url, request }) => {
|
|
const forwardedHost = request.headers.get('X-Forwarded-Host');
|
|
let redirect_base;
|
|
if (DEV) {
|
|
redirect_base = url.origin;
|
|
} else if (forwardedHost) {
|
|
redirect_base = `${url.protocol}//${forwardedHost}`;
|
|
} else {
|
|
redirect_base = BASE_URL;
|
|
}
|
|
const redirect_uri = new URL(`${redirect_base}${url.pathname}`);
|
|
|
|
const adder = new SpotifyPlaylistAdder();
|
|
if (url.hostname === 'localhost' && DEV) {
|
|
redirect_uri.hostname = '127.0.0.1';
|
|
}
|
|
logger.debug(url.searchParams, url.hostname);
|
|
if (url.searchParams.has('code')) {
|
|
await adder.receivedAuthCode(url.searchParams.get('code') || '', redirect_uri);
|
|
redirect(307, '/');
|
|
} else if (url.searchParams.has('error')) {
|
|
logger.error('received error', url.searchParams.get('error'));
|
|
return;
|
|
}
|
|
|
|
if (await adder.authCodeExists()) {
|
|
redirect(307, '/');
|
|
}
|
|
|
|
const authUrl = adder.constructAuthUrl(redirect_uri);
|
|
logger.debug('+page.server.ts', authUrl.toString());
|
|
redirect(307, authUrl);
|
|
};
|