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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
|
/** @jsx h */
import {
deleteCookie,
getCookies,
h,
setCookie,
Status,
} from "../../deps_server.ts";
import { DISCORD_URL, renderPage } from "../utils.ts";
import { client } from "../client.ts";
import { config } from "../config.ts";
import { SpeedRunBot } from "../standalone_client.ts";
import { commands } from "../srcom/slash_commands.ts";
// User structure that comes from discord
interface User {
id: string;
username: string;
discriminator: string;
avatar: string;
verified: boolean;
email: string;
flags: number;
banner: string;
accent_color: number;
premium_type: number;
public_flags: number;
}
// Access token response from discord
interface AccessTokenResponse {
access_token: string;
token_type: "Bearer";
expires_in: number;
refresh_token: string;
scope: string;
}
// The application has the team/owner of the bot
// Which is used to see if the client has permission to reload the commands
const application = await client.fetchApplication();
export default async (req: Request): Promise<Response> => {
const { pathname, searchParams, origin } = new URL(req.url);
const location = `${origin}${pathname}`;
const code = searchParams.get("code");
const access_token = getCookies(req.headers).access_token;
if (req.method === "DELETE") {
const headers = new Headers();
deleteCookie(headers, "access_token");
return renderPage(
<Admin location={location} message={"Logged out!"} />,
);
} // The user has triggered a reload
else if (req.method === "POST") {
if (!access_token) {
return renderPage(
<Admin location={location} message={"Not logged in"} />,
);
}
const user = await getUserFromToken(access_token);
if (isUserAnOwner(user)) {
// reload commands
const client = new SpeedRunBot({
intents: [],
token: config.TOKEN,
});
await client.connect();
await client.interactions.commands.bulkEdit(
commands,
config.TEST_SERVER,
);
return renderPage(
<Admin location={location} message={"Commands succesfully updated!"} />,
);
} else {
return renderPage(
<Admin location={location} message={"Access denied"} />,
);
}
} // The user just came back from discord
// And authorized the app
else if (code) {
const headers = new Headers({
"Location": location,
});
const access_token = await exchangeCodeForToken(code, location);
setCookie(headers, {
name: "access_token",
httpOnly: true,
value: access_token,
});
return new Response(null, {
headers,
status: Status.TemporaryRedirect,
});
} // The user is now logged in
else if (access_token) {
const user = await getUserFromToken(access_token);
return renderPage(<Admin location={location} user={user} />);
} else return renderPage(<Admin location={location} />);
};
export function Admin(
{ user, location, message }: {
user?: User;
location: string;
message?: string;
},
) {
return (
<div>
<h1>
Speedrun.bot admin panel
</h1>
<h2>
{message}
</h2>
{!user
? (client.id
? (
<a
href={`${DISCORD_URL}/oauth2/authorize?client_id=${client.id}&scope=identify&response_type=code&redirect_uri=${
encodeURIComponent(location)
}`}
>
Click here to log in
</a>
)
: "Loading...")
: (
// If the authorized user is in the team
// Or is the owner of the application
// Allow them to reload commands
isUserAnOwner(user)
? (
<form method="POST">
<button type="submit">
Reload commands?
</button>
</form>
)
: "Access denied"
)}
{user && (
<form action="/logout">
<button type="submit">
Log out
</button>
</form>
)}
</div>
);
}
async function exchangeCodeForToken(
code: string,
redirect_uri: string,
): Promise<string> {
const client_secret = config.CLIENT_SECRET;
if (!client_secret) {
throw new Error(
"CLIENT_SECRET is not set!!! Tell an admin about this. Wait, you're the admin?",
);
}
// https://discord.com/developers/docs/topics/oauth2#authorization-code-grant-access-token-response
const res = await fetch(`${DISCORD_URL}/oauth2/token`, {
method: "POST",
body: new URLSearchParams({
"client_id": typeof client.id === "function" ? client.id() : client.id,
client_secret,
"grant_type": "authorization_code",
code,
redirect_uri,
}).toString(),
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
});
const data = await res.json() as AccessTokenResponse;
return data.access_token;
}
async function getUserFromToken(access_token: string): Promise<User> {
const res = await fetch(`${DISCORD_URL}/users/@me`, {
headers: {
"Authorization": `Bearer ${access_token}`,
},
});
const user = await res.json() as User;
return user;
}
function isUserAnOwner(user: User): boolean {
return application.team?.members.map((user) => user.id).includes(user.id) ||
application.owner?.id === user.id;
}
|