-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdiscord.ts
172 lines (142 loc) · 4.29 KB
/
discord.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
import {
RESTGetAPIOAuth2CurrentAuthorizationResult,
RESTPostOAuth2AccessTokenResult,
RESTPostOAuth2RefreshTokenResult,
Snowflake,
} from 'discord-api-types/v10';
import { Bindings } from './worker-configuration';
import * as storage from './storage';
export function getOAuthUrl(env: any) {
const state = crypto.randomUUID();
const url = new URL('https://discord.com/api/oauth2/authorize');
url.searchParams.set('client_id', env.DISCORD_APPLICATION_ID);
url.searchParams.set('redirect_uri', env.WORKER_URL + '/oauth-callback');
url.searchParams.set('response_type', 'code');
url.searchParams.set('state', state);
url.searchParams.set(
'scope',
'role_connections.write identify guilds email'
);
url.searchParams.set('prompt', 'consent');
return {
state,
url: url.toString(),
};
}
export async function getOAuthTokens(code: string | undefined, env: Bindings) {
if (!code) {
throw new Error('no code provided');
}
const url = 'https://discord.com/api/v10/oauth2/token';
const body = new URLSearchParams({
client_id: env.DISCORD_APPLICATION_ID,
client_secret: env.DISCORD_CLIENT_SECRET,
grant_type: 'authorization_code',
code: code,
redirect_uri: env.WORKER_URL + '/oauth-callback',
});
const response = await fetch(url, {
body,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});
if (response.ok) {
const data = await response.json() as RESTPostOAuth2AccessTokenResult;
return data;
} else {
console.error('error at fetching OAuth tokens');
console.error(await response.json());
}
}
export async function getAccessToken(
userId: Snowflake,
tokens: storage.Tokens,
env: Bindings
) {
if (Date.now() > tokens.expires_in) {
const url = 'https://discord.com/api/v10/oauth2/token';
const body = new URLSearchParams({
client_id: env.DISCORD_APPLICATION_ID,
client_secret: env.DISCORD_CLIENT_SECRET,
grant_type: 'refresh_token',
refresh_token: tokens.refresh_token,
});
const response = await fetch(url, {
body,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});
if (response.ok) {
const tokens = await response.json() as RESTPostOAuth2RefreshTokenResult;
tokens.expires_in = Date.now() + tokens.expires_in * 1000;
await storage.storeDiscordTokens(userId, tokens, env.TOKEN_STORE);
return tokens.access_token;
} else {
console.error('error at refreshing token');
console.error(await response.json());
}
}
return tokens.access_token;
}
export async function getUserData(tokens: RESTPostOAuth2AccessTokenResult) {
const url = 'https://discord.com/api/v10/oauth2/@me';
const response = await fetch(url, {
headers: {
Authorization: `Bearer ${tokens.access_token}`,
},
});
if (response.ok) {
const data =
await response.json() as RESTGetAPIOAuth2CurrentAuthorizationResult;
return data;
} else {
console.error('error at fetching user data');
console.error(await response.json());
}
}
export async function getMetadata(
userId: Snowflake,
tokens: any,
env: Bindings
) {
const url = `https://discord.com/api/v10/users/@me/applications/${env.DISCORD_APPLICATION_ID}/role-connection`;
const accessToken = await getAccessToken(userId, tokens, env);
const response = await fetch(url, {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
if (response.ok) {
const data = await response.json();
console.log('ok');
return data;
} else {
console.error('error at getting metadata');
console.error(await response.json());
}
}
export async function pushMetadata(
userId: Snowflake,
tokens: storage.Tokens,
body: Object,
env: Bindings
) {
const url = `https://discord.com/api/v10/users/@me/applications/${env.DISCORD_APPLICATION_ID}/role-connection`;
const accessToken = await getAccessToken(userId, tokens, env);
const response = await fetch(url, {
method: 'PUT',
body: JSON.stringify(body),
headers: {
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
});
if (!response.ok) {
console.error('error at pushing metadata');
console.error(await response.json());
}
}