-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path+server.ts
96 lines (87 loc) · 2.9 KB
/
+server.ts
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import { env } from '$env/dynamic/private';
import { env as pubEnv } from '$env/dynamic/public';
import { redirect } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { DateTime } from "luxon";
import { isUserEligible } from 'config';
import type { OsuUser } from '$lib/OsuUser';
async function getOAuthTokens(code: string) {
const url = 'https://osu.ppy.sh/oauth/token';
const body = JSON.stringify({
client_id: `${pubEnv.PUBLIC_OSU2_CLIENT_ID}`,
client_secret: `${env.OSU2_CLIENT_SECRET}`,
grant_type: 'authorization_code',
code,
redirect_uri: `${pubEnv.PUBLIC_BASE_URL}/auth/osu/callback`,
});
const response = await fetch(url, {
body,
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
});
if (response.ok) {
const data = await response.json();
return data;
} else {
throw new Error(`Error fetching OAuth tokens: [${response.status}] ${response.statusText}`);
}
}
async function getUserData(tokens: {
access_token: string;
token_type: string;
}) {
const url = 'https://osu.ppy.sh/api/v2/me';
const response = await fetch(url, {
headers: {
Authorization: `Bearer ${tokens.access_token}`,
},
});
if (response.ok) {
const data = await response.json();
return data;
} else {
throw new Error(`Error fetching user data: [${response.status}] ${response.statusText}`);
}
}
// Write cookie for the state which will be used to compare later for the linked role stuff.
export const GET = (async ({ url, locals }) => {
try {
const code = url.searchParams.get('code');
if (!code) throw new Error('No code provided');
const tokens = await getOAuthTokens(code);
const meData = await getUserData(tokens) as OsuUser;
await locals.session.set({
osu: {
id: meData.id.toString(),
username: meData.username,
joinDate: DateTime.fromISO(meData.join_date)
}
});
if (isUserEligible(meData)) {
return new Response(null, {
status: 302,
headers: {
location: "/checks/discord"
}
});
}
await locals.session.update((data) => {
data.error = `osu! account is not older than 6 months yet (account age is ${DateTime.fromISO(meData.join_date).toISODate()})`
return data;
});
return new Response(null, {
status: 302,
headers: {
location: "/checks/manual"
}
})
} catch (e) {
console.error('Error parsing JSON', e);
locals.session.set({
error: "Error reading osu! profile data"
});
throw redirect(302, '/');
}
}) satisfies RequestHandler;