aboutsummaryrefslogtreecommitdiff
path: root/src/lib/Utility/anilistOauth.ts
blob: 9bb570fb671743f925cceae86d6e5c5236a66cd9 (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
import { env } from "$env/dynamic/private";
import { env as publicEnv } from "$env/dynamic/public";

// Exchange a refresh token for a fresh access token WITHOUT touching the auth
// cookie — used by the RSS feed, which is polled by an unattended reader that
// has no session, so there is no cookie to re-set.
export const refreshAniListToken = async (
	refreshToken: string,
): Promise<string | null> => {
	const formData = new FormData();

	formData.append("grant_type", "refresh_token");
	formData.append("client_id", publicEnv.PUBLIC_ANILIST_CLIENT_ID as string);
	formData.append("client_secret", env.ANILIST_CLIENT_SECRET as string);
	formData.append("refresh_token", refreshToken);

	const response = await fetch("https://anilist.co/api/v2/oauth/token", {
		method: "POST",
		body: formData,
	});

	if (!response.ok) return null;

	const payload = (await response.json()) as { access_token?: string };

	return payload.access_token ?? null;
};