-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathverification.ts
431 lines (396 loc) · 17.4 KB
/
verification.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
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
import got from 'got';
import pepper = require('./pepper');
import { sha256 } from "js-sha256";
import { Client, Guild, GuildMember, Message, MessageReaction, Role, Snowflake, TextChannel, User, PartialUser } from "discord.js";
import * as fs from 'fs';
interface VerifySetup {
guild_2025: Snowflake,
guild_2026: Snowflake,
verification: VerifyConfig,
}
interface VerifyConfig {
guild_2025: Snowflake,
role_for_2026s_in_2025_server: Snowflake,
guild_2026: Snowflake,
verified_role: Snowflake,
verified_role_2026: Snowflake,
target_channel: Snowflake,
target_role: Snowflake,
}
interface CacheEntry {
channel: TextChannel,
role: Role,
}
/**
* there are 3 verification types:
* - 2025/26 verification: they will send you to `verify2025.php` or `verify2026.php`, for '25/'26 server
* - 2025-affiliated servers verification: automatically give verified role to people in other '25 servers
* - general kerb verification: for any other MIT server. will currently give verified role to anyone with a kerb
* the idea is to add moira list verification so more groups can use it
* because for now otherwise there would be little point because busy beavers et al now just verify people who are in the discord student hub
*/
type VerifierFn = (id: Snowflake) => Promise<void>;
/**
* Generates a function that checks if a given user ID is verified enough (i.e. is in the given guild and has the given role, if given)
* @param client The client
* @param guild_id The guild to check if the user is in
* @param role_id The role to check if the user has (if not given, no roles are checked)
* @returns A function that resolves with a nullary value, or rejects with an error message.
*/
export function generateVerifierFn(client: Client, guild_id: Snowflake, role_id: Snowflake | undefined) {
return async (id: Snowflake) => {
const guild = client.guilds.cache.get(guild_id);
const guildMember = guild!.members.cache.get(id);
if (!guildMember) {
throw `You're not in "${guild?.name}"`;
} else {
if (role_id) {
const role = guildMember.roles.cache.get(role_id);
const role_name = guild?.roles.cache.get(role_id)!.name;
if (!role) {
throw `You do not have the role "${role_name}", which is required to run the command`;
}
}
}
}
}
// TODO: maybe separate the code into different classes? like the main class would be `Verifier`
// but the code could be in 3 other classes
// And also, some of the code is in `bot.ts`, so uh, yeah.
export class Verifier {
base_guild: Guild;
guild_2026: Guild;
config: VerifyConfig;
verify_cache: { [key: string]: CacheEntry };
is2025Commit: VerifierFn;
is2026Commit: VerifierFn;
constructor(client: Client, config: VerifySetup) {
this.base_guild = client.guilds.cache.get(config.guild_2025)!;
this.guild_2026 = client.guilds.cache.get(config.guild_2026)!;
this.config = config.verification;
this.verify_cache = {};
// Generate verification functions
this.is2025Commit = generateVerifierFn(client, config.guild_2025, config.verification.verified_role);
this.is2026Commit = generateVerifierFn(client, config.guild_2026, config.verification.verified_role_2026);
if (!this.base_guild) {
throw new Error(`Could not find base guild (id ${config.guild_2025})!`);
}
}
/**
* Gets the list of servers that have kerb verification enabled (i.e. any kerb)
*/
async getKerbVerificationServers(): Promise<string[]> {
const json: string = fs.readFileSync('servers.json', 'utf8');
const dict: object = JSON.parse(json);
const servers: string[] = [];
for (const [server, props] of Object.entries(dict)) {
if (props !== undefined && props['enabled']) {
servers.push(server);
}
}
return servers;
}
async setKerbVerificationConfig(serverId: string, key: 'enabled' | 'role' | 'moira' | 'message', value: any) {
let json: string = fs.readFileSync('servers.json', 'utf8');
const dict: any = JSON.parse(json); // TODO: use stronger type annotation - maybe an interface
if (dict[serverId] === undefined) {
dict[serverId] = {};
}
dict[serverId][key] = value;
json = JSON.stringify(dict);
fs.writeFileSync('servers.json', json);
}
async getKerbVerificationConfig(serverId: string, key: 'enabled' | 'role' | 'moira' | 'message') {
let json: string = fs.readFileSync('servers.json', 'utf8');
const dict: any = JSON.parse(json); // TODO: use stronger type annotation - maybe an interface
if (dict[serverId] === undefined) {
return undefined;
} else {
return dict[serverId][key];
}
}
/**
* Enables kerb verification for server `serverId`
* @param serverId discord id of the server
*/
async enableKerbVerification(serverId: string) {
await this.setKerbVerificationConfig(serverId, 'enabled', true);
}
/**
* Disables kerb verification for server `serverId`
* @param serverId discord id of the server
*/
async disableKerbVerification(serverId: string) {
await this.setKerbVerificationConfig(serverId, 'enabled', false);
}
/**
*
* @param serverId
*/
async isKerbVerificationEnabled(serverId: string): Promise<boolean> {
return await this.getKerbVerificationConfig(serverId, 'enabled') || false;
}
/**
* Set verified role for server
* @param serverId discord id of the server
* @param roleId discord id of the role
*/
async setKerbVerificationRole(serverId: string, roleId: string) {
await this.setKerbVerificationConfig(serverId, 'role', roleId);
}
/**
* Set message to reply to recently verified user for server
* @param serverId discord id of the server
* @param message message
*/
async setKerbVerificationSuccessMessage(serverId: string, message: string) {
await this.setKerbVerificationConfig(serverId, 'message', message);
}
/**
* Set moira list to check against. If undefined, will check for any kerb.
* @param serverId discord id of the server
* @param list name of the moira list for allowed members
*/
async setKerbVerificationMoiraList(serverId: string, list: string | undefined) {
/// TODO: implement this on the server side so it actually does something
await this.setKerbVerificationConfig(serverId, 'moira', list);
}
get_cached(guild: Guild) {
// ensure entry exists
this.verify_cache[guild.id] = (this.verify_cache[guild.id] || {});
const cached = this.verify_cache[guild.id];
// if they don't exist, try populating them
cached.channel = (cached.channel || guild.channels.cache.find(c => c.name === this.config.target_channel) as TextChannel); // TODO check cast
cached.role = (cached.role || guild.roles.cache.find(r => r.name === this.config.target_role));
// return the values we got
return cached;
}
async verify(guildMember: GuildMember) {
const guild = guildMember.guild;
if (guild == this.base_guild) {
/// Give 2026 role to 2026s who join the 2025 server
try {
await this.is2026Commit(guildMember.id);
const role_2026 = guild.roles.resolve(this.config.role_for_2026s_in_2025_server)!; // TODO check cast
guildMember.roles.add(role_2026);
return true;
} catch (e) {
console.log(e);
return false;
}
} else {
/// Give verified role to 2025s who join 2025-affiliated servers
const { channel, role } = this.get_cached(guild);
/// Don't try to verify if #landing-pad doesn't exist
if (!channel) {
return;
}
try {
await this.is2025Commit(guildMember.id);
if (role) {
guildMember.roles.add(role);
return true;
} else {
channel.send(`Could not find verified role in ${guild.name}`);
return false;
}
} catch (error) {
if (!await this.isKerbVerificationEnabled(guildMember.guild.id)) {
channel.send(`${guildMember}: ${error}`);
}
return false;
}
}
}
}
/**
* Get a verification link for the Discord user
* @param {*} id Discord ID of the person verifying
* @param {*} classOf Class of the person verifying (2025 or 2026)
* @returns The link that will verify this specific user
*/
export const getClassVerifyLink = (id: string, classOf: string) => {
return `https://discord2025.mit.edu:444/verify${classOf}.php?id=${id}&auth=${sha256(`${pepper}:${id}`)}`;
}
export const getVerifyLink = (id: string, serverId: string) => {
return `https://discord2025.mit.edu:444/verify.php?id=${id}&server=${serverId}&auth=${sha256(`${pepper}:${id}`)}`;
}
// I know singletons are discouraged,
// but in this case we really do only need one verifier.
// It's cleaner than passing around one per client, at any rate
let verifier: Verifier | null = null;
const sendClassVerificationDm = (user: User | PartialUser, classOf: string) => {
user.send(`To verify that you're a comMIT please click on the following link: ${getClassVerifyLink(user.id, classOf)}`);
};
const sendVerificationDm = (user: User | PartialUser, serverId: string) => {
user.send(`To get access to the server please click on the following link: ${getVerifyLink(user.id, serverId)}`);
}
const genCommands = (verifier: Verifier, config: VerifySetup) => [
{
name: 'verify',
call: (msg: Message) => {
const id = msg.author.id;
if (msg.channel.type === 'dm' || msg.guild?.id == config.guild_2025) {
sendClassVerificationDm(msg.author, '2025');
} else {
const guildMember = msg.guild?.members.cache.get(id);
if (guildMember) {
verifier.verify(guildMember);
}
}
}
}, {
name: 'whitelist',
unprefixed: true,
call: (msg: Message, args: string[]) => {
if (!args[1]) {
msg.reply("Please specify a username after `whitelist` to get whitelisted");
} else {
const username = args[1];
const id = msg.author.id;
const url = `https://rgabriel.mit.edu/mc/prefrosh.php?name=${username}&discord=${id}&auth=${pepper}`;
const verificationStatus = verifier.is2026Commit(id);
if (id == '600463130174423053') {
msg.reply('Almost done! To finish verifying, go to the following link: https://mitcraft.ml/prefrosh');
} else {
verificationStatus
.then(() => got(url).then(response => msg.channel.send(`${response.body}`)))
.catch(error => msg.reply(`${error} If you're not a prefrosh, go to https://mitcraft.ml to get whitelisted. Go to #help if you're having trouble.`));
}
}
}
}, {
name: 'enableVerification',
call: async (msg: Message) => {
if (msg.guild != null) {
if (!msg.member!.hasPermission('MANAGE_GUILD')) {
msg.reply(`Permission denied. You need to be a mod of "${msg.guild.name}" to enable verification (i.e. have manage server permission).`);
return;
}
try {
const id: string = msg.guild.id;
await verifier.enableKerbVerification(id);
const { role } = verifier.get_cached(msg.guild);
if (role === undefined) {
msg.reply(`Please either:
* create a role called "verified" to give to people once they verify, and then run \`tim.enableVerification\` again afterward
* or set a verified role using \`tim.setVerificationRole ROLE_ID_GOES_HERE\``);
} else {
await verifier.setKerbVerificationRole(id, role.id);
msg.reply(`Verification has been enabled for ${msg.guild.name}`);
}
} catch (e) {
msg.reply(`${e}`);
}
}
},
}, {
name: 'disableVerification',
call: async (msg: Message) => {
if (msg.guild != null) {
if (!msg.member!.hasPermission('MANAGE_GUILD')) {
msg.reply(`Permission denied. You need to be a mod of "${msg.guild.name}" to enable verification (i.e. have manage server permission).`);
return;
}
const id: string = msg.guild.id;
await verifier.disableKerbVerification(id);
msg.reply(`Verification has been disabled for ${msg.guild.name}`);
}
}
}, {
name: 'setVerificationRole',
call: async (msg: Message, args: string[]) => {
if (msg.guild != null) {
if (!msg.member!.hasPermission('MANAGE_GUILD')) {
msg.reply(`Permission denied. You need to be a mod of "${msg.guild.name}" to enable verification (i.e. have manage server permission).`);
return;
}
if (!args[1]) {
msg.reply("Please specify a role id for the verified role id.")
} else {
await verifier.setKerbVerificationRole(msg.guild.id, args[1]);
msg.reply(`Verified role successfully set to <@&${args[1]}>!`)
}
}
}
}, {
/// TODO: there is a lot of code repetition... fix this perhaps?
name: 'setVerificationMoiraList',
call: async (msg: Message, args: string[]) => {
if (msg.guild != null) {
if (!msg.member!.hasPermission('MANAGE_GUILD')) {
msg.reply(`Permission denied. You need to be a mod of "${msg.guild.name}" to enable verification (i.e. have manage server permission).`);
return;
}
if (!args[1]) {
msg.reply("Please specify a moira list to check against.")
} else {
await verifier.setKerbVerificationMoiraList(msg.guild.id, args[1]);
msg.reply(`List successfully set to ${args[1]}!`);
}
}
}
}, {
name: 'setVerificationMessage',
call: async (msg: Message, args: string[]) => {
if (msg.guild != null) {
if (!msg.member!.hasPermission('MANAGE_GUILD')) {
msg.reply(`Permission denied. You need to be a mod of "${msg.guild.name}" to enable verification (i.e. have manage server permission).`);
return;
}
let text = msg.content.substr(args[0].length + 1).trim();
await verifier.setKerbVerificationSuccessMessage(msg.guild.id, text);
msg.reply(`Message successfully set!`);
}
}
}, {
name: 'getVerificationServers',
call: async (msg: Message) => {
const servers: string[] = await verifier.getKerbVerificationServers();
msg.reply(servers.toString());
}
}
];
const setup = (client: Client, config: any) => {
if (verifier) {
throw new Error("Verifier already setup!");
}
verifier = new Verifier(client, config as VerifySetup);
client.on('guildMemberAdd', async (member: GuildMember) => {
const roleSuccess = await verifier!.verify(member);
/// don't make 2026s get a DM asking them to verify as 2025s
if (roleSuccess) {
return;
}
if (member.guild.id == config.guild_2025) {
member.send(`Hi! I'm Tim. In order to get verified as a member of the class of 2025, please click on the following link:
${getClassVerifyLink(member.id, '2025')}
Once you're in the server, please check out #rules-n-how-to-discord, get roles in #roles, and don't forget to introduce yourself to your fellow adMITs in #introductions!`);
}
const kerbVerificationServers = await verifier!.getKerbVerificationServers();
if (kerbVerificationServers.includes(member.guild.id)) {
member.send(`Hi! I'm Tim. To get access to "${member.guild.name}", please click on the following link:
${getVerifyLink(member.id, member.guild.id)}`);
}
});
client.on('messageReactionAdd', (reaction: MessageReaction, user: User | PartialUser) => {
if (reaction.emoji.name === 'verifyme') {
const rxn_id = reaction.message.guild?.id;
if (rxn_id == config.guild_2025) {
sendClassVerificationDm(user, '2025');
} else if (rxn_id == config.guild_2026) {
sendClassVerificationDm(user, '2026');
} else if (reaction.message.guild != null) {
sendVerificationDm(user, reaction.message.guild.id);
}
}
});
// Commands
return genCommands(verifier, config);
};
module.exports = {
setup,
Verifier,
getVerifyLink: getClassVerifyLink,
generateVerifierFn,
};