2024-10-09 19:40:55 -05:00
|
|
|
import { useEffect } from 'react';
|
2024-10-09 21:04:49 -05:00
|
|
|
import { App } from '../../../stores/app';
|
2024-10-09 19:40:55 -05:00
|
|
|
|
|
|
|
|
export const AUTH_PROVIDERS = ['wargaming', 'patreon'] as const;
|
|
|
|
|
|
|
|
|
|
type AuthProvider = (typeof AUTH_PROVIDERS)[number];
|
|
|
|
|
|
|
|
|
|
export const AUTH_PROVIDER_NAMES: Record<AuthProvider, string> = {
|
|
|
|
|
patreon: 'Patreon',
|
|
|
|
|
wargaming: 'Wargaming',
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export interface PatreonAuthResponse {
|
|
|
|
|
access_token: string;
|
|
|
|
|
expires_in: number;
|
|
|
|
|
token_type: 'Bearer';
|
|
|
|
|
scope: string;
|
|
|
|
|
refresh_token: string;
|
|
|
|
|
version: string;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
interface AuthorizeProps {
|
|
|
|
|
provider: AuthProvider;
|
|
|
|
|
}
|
|
|
|
|
|
2024-10-10 15:23:30 -05:00
|
|
|
export function Authorize(props: AuthorizeProps) {
|
|
|
|
|
return (
|
|
|
|
|
<App.Provider>
|
|
|
|
|
<Content {...props} />
|
|
|
|
|
</App.Provider>
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function Content({ provider }: AuthorizeProps) {
|
2024-10-09 21:04:49 -05:00
|
|
|
const mutateApp = App.useMutation();
|
|
|
|
|
|
2024-10-09 19:40:55 -05:00
|
|
|
useEffect(() => {
|
|
|
|
|
(async () => {
|
|
|
|
|
const searchParams = new URLSearchParams(window.location.search);
|
|
|
|
|
|
|
|
|
|
switch (provider) {
|
|
|
|
|
case 'wargaming': {
|
|
|
|
|
if (
|
|
|
|
|
!searchParams.has('expires_at') ||
|
|
|
|
|
!searchParams.has('access_token') ||
|
|
|
|
|
!searchParams.has('account_id')
|
|
|
|
|
) {
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
|
2024-10-09 21:09:59 -05:00
|
|
|
mutateApp((draft) => {
|
|
|
|
|
draft.logins.wargaming = {
|
|
|
|
|
expires: Number(searchParams.get('expires_at')) * 1000,
|
|
|
|
|
token: searchParams.get('access_token')!,
|
|
|
|
|
id: Number(searchParams.get('account_id'))!,
|
|
|
|
|
};
|
2024-10-09 19:40:55 -05:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
case 'patreon': {
|
|
|
|
|
if (!searchParams.get('code')) break;
|
|
|
|
|
|
2024-10-12 23:17:32 -05:00
|
|
|
const response = await fetch('/api/patreon/auth', {
|
|
|
|
|
headers: { code: searchParams.get('code')! },
|
|
|
|
|
});
|
2024-10-09 19:40:55 -05:00
|
|
|
const data = (await response.json()) as PatreonAuthResponse;
|
|
|
|
|
|
2024-10-09 21:04:49 -05:00
|
|
|
mutateApp((draft) => {
|
|
|
|
|
draft.logins.patreon = {
|
|
|
|
|
token: data.access_token,
|
|
|
|
|
refreshToken: data.refresh_token,
|
|
|
|
|
expires: Date.now() + data.expires_in * 1000,
|
|
|
|
|
};
|
2024-10-09 19:40:55 -05:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
default:
|
|
|
|
|
throw new Error(`Unknown provider: ${provider}`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
window.location.href = searchParams.get('return') ?? '/';
|
|
|
|
|
})();
|
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
|
|
return null;
|
|
|
|
|
}
|