-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
1551 lines (1384 loc) · 59.6 KB
/
index.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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
Client, GatewayIntentBits, EmbedBuilder, ButtonBuilder, ActionRowBuilder, ButtonStyle, PermissionFlagsBits,
Interaction, GuildMember, GuildMemberRoleManager, Message,
ButtonInteraction,
TextChannel,
MessageCreateOptions,
InteractionReplyOptions,
ChatInputCommandInteraction,
ApplicationCommandOptionType,
Role,
Guild,
ContextMenuCommandBuilder,
ApplicationCommandType,
ContextMenuCommandType,
InteractionContextType,
UserContextMenuCommandInteraction,
MessageContextMenuCommandInteraction,
PermissionsBitField
} from 'discord.js';
import express from 'express';
import env from './env';
import { encryptUserId, decryptUserId, generateRandomToken } from './encryption';
import getTemplate from './template';
import { sendEmail } from './email';
import * as sheet from './spreadsheet';
import { GoogleSpreadsheetRow } from 'google-spreadsheet';
import Logger from './logging';
import * as utils from './utils';
type BotInteraction =
ButtonInteraction |
ChatInputCommandInteraction |
MessageContextMenuCommandInteraction |
UserContextMenuCommandInteraction;
const app: express.Application = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
]
});
const logger = new Logger(client);
interface verificationInfo {
timestamp: number,
interaction: BotInteraction, // The interaction context,
expiry: number, // The timestamp when the verification link expires
watiam?: string, // The watiam of the user
emailSent?: number, // The timestamp when the email was sent, if not sent, it's undefined,
retries?: number, // Number of retries
nextRetry?: number, // The verification token in the email
token?: string // The token for email verification
}
const verificationPool = new Map<string, verificationInfo>();
const checkExpired = () => {
const now = Date.now();
for (const [userId, verificationInfo] of verificationPool.entries()) {
if (!verificationInfo.expiry) continue;
if (now > verificationInfo.expiry) {
verificationPool.delete(userId);
}
}
}
const PORT = process.env.PORT || 3000;
// Define static routes, ./static/* will be served as /static/*
app.use('/static', express.static('static'));
app.use((req, res, next) => {
checkExpired();
next();
});
// Main routes
app.get('/verify/:encryptedUserId', async (req: express.Request, res: express.Response): Promise<any> => {
const encryptedUserId = req.params.encryptedUserId;
const userId = decryptUserId(encryptedUserId);
if (!userId) {
return res.send(getTemplate('error', { message: 'Invalid verification link. It may have expired or corrupted. Try getting a new one from the server.' }));
}
try {
const guild = await client.guilds.fetch(env.SERVER_ID);
const member = await guild.members.fetch(userId);
const username = member?.user?.username ?? userId;
const verificationInfo = verificationPool.get(userId);
if (!verificationInfo) {
return res.send(getTemplate('error', { message: 'Verification link does not exist or has expired. Try getting a new one from the server.' }));
}
res.send(getTemplate('verification', {
discordId: encryptedUserId,
discordUsername: username,
watiam: verificationInfo.watiam ?? '',
emailSent: !!verificationInfo.emailSent,
nextRetry: verificationInfo.nextRetry ?? false,
}));
} catch (error) {
console.error('Error during verification:', error);
res.send(getTemplate('error', { message: 'An error occurred during verification. Please try again.' }));
}
});
app.post('/send-verification-email', async (req: express.Request, res: express.Response): Promise<any> => {
const { discordId, watiam } = req.body;
if (!discordId || !watiam) {
return res.send({ status: 'error', message: 'Invalid request. Missing parameters.' });
}
const userId = decryptUserId(discordId);
if (!userId) {
return res.send('Invalid verification link. It may have expired or corrupted. Try getting a new one from the server.');
}
if (watiam.length > 8 || !watiam.match(/^[a-z]{1,}\d*[a-z]{1,}$/i)) {
return res.send({ status: 'error', message: 'Invalid WatIAM ID. Please enter a valid WatIAM ID.' });
}
const verificationInfo = verificationPool.get(userId);
if (!verificationInfo) {
return res.send({ status: 'error', message: 'Verification link does not exist or has expired. Try getting a new one from the server.' });
}
// Check if its before the next retry
let nextRetry = verificationInfo.nextRetry;
if (nextRetry && Date.now() < nextRetry) {
return res.send({ status: 'error', message: `You cannot send email until the next retry. Please wait.` });
} else if (nextRetry === -1) {
return res.send({ status: 'error', message: `You have reached the maximum number of retries. Please try again later.` });
}
// Generate a random token for verification
if (!verificationInfo.token) {
verificationInfo.token = generateRandomToken();
verificationPool.set(userId, verificationInfo);
}
// Send email to the user
const token = verificationInfo.token;
const link = `${env.URL}/email-verify/${discordId}/${token}`;
const text = `Click the link to verify your email: ${link}. The link will expire in 1 hour. If you did not request this, please DO NOT click the link and ignore this email.`;
const html = getTemplate('email', { verificationLink: link }); // TODO: Make the email template beautiful
const to = `${watiam}@uwaterloo.ca`;
console.log('Sending email to:', to);
console.log('With verification link:', link);
try {
await sendEmail(to, 'Email Verification', text, html);
} catch (error) {
console.error('Error sending email:', error);
return res.send({ status: 'error', message: 'An error occurred while sending the email. Please try again. If the problem persists, please contact the club executives to get verified manually.' });
}
// Update the verification pool
verificationInfo.watiam = watiam;
verificationInfo.emailSent = Date.now();
verificationInfo.expiry = Date.now() + 60 * 60 * 1000;
// Calculate the next retry time
const retries = verificationInfo.retries ?? 0;
nextRetry = verificationInfo.emailSent;
if (nextRetry) {
if (retries <= 4) {
nextRetry += [0.5, 1, 2, 3, 5][retries] * 60 * 1000;
} else {
nextRetry = -1;
}
verificationInfo.nextRetry = nextRetry;
}
verificationInfo.retries = retries + 1;
verificationPool.set(userId, verificationInfo);
// Logging
logger.verbose(verificationInfo.interaction.member as GuildMember, 'Sent a verification email', 'They have requested a verification email to verify.', embed => {
embed.addFields(
{ name: 'WatIAM', value: watiam },
{ name: 'Next Retry', value: nextRetry > 0 ? `<t:${Math.floor(nextRetry / 1000)}:R>` : 'Until the verification link expires' }
);
});
// Send a success response
res.send({
status: 'success',
emailSent: verificationInfo.emailSent,
nextRetry: nextRetry
});
});
app.get('/email-verify/:encryptedUserId/:token', async (req: express.Request, res: express.Response): Promise<any> => {
const encryptedUserId = req.params.encryptedUserId;
const token = req.params.token;
const userId = decryptUserId(encryptedUserId);
if (!userId) {
return res.send(getTemplate('error', { message: 'Invalid verification link. It may have expired or corrupted. Try getting a new one from the server.' }));
}
const verificationInfo = verificationPool.get(userId);
if (!verificationInfo) {
return res.send(getTemplate('error', { message: 'Verification link does not exist or has expired. Try getting a new one from the server.' }));
}
if (verificationInfo.token !== token) {
return res.send(getTemplate('error', { message: 'Invalid verification token.' }));
}
const guild = await client.guilds.fetch(env.SERVER_ID);
const member = await guild.members.fetch(userId);
if (!member) {
return res.send(getTemplate('error', { message: 'Cannot find the user in the server. Please join the server first.' }));
}
// Remove the user from the verification pool
verificationPool.delete(userId);
// Give the verified role to the user
await member.roles.add(env.ROLE_ID.VERIFIED);
await member.roles.add(env.ROLE_ID.CURRENT_UW_STUDENT);
// Send a success message to the user
//sendExclusiveMessage('You have been successfully verified! Welcome to osu!uwaterloo!', member);
verificationInfo.interaction.followUp({ content: 'You have been successfully verified! Welcome to osu!uwaterloo!', ephemeral: true });
// Update the sheet
try {
await sheet.addMember(userId, member.user.username, verificationInfo.watiam!);
} catch (error) {
console.error('Error adding member to the sheet:', error);
}
// Logging
logger.success(member, 'Has been verified', 'They have completed the email verification process and have been verified as a current UW student.', embed => {
embed.addFields(
{ name: 'WatIAM', value: verificationInfo.watiam ?? 'Unknown' }
);
});
// Get a membership management link
const key = `${userId}-${Date.now() + 24 * 60 * 60 * 1000}`;
const link = `${env.URL}/membership/${encryptUserId(key)}?verified=true`;
res.redirect(link);
});
// restore verification status for rejoining members
async function restoreVerificationStatus(member: GuildMember) {
const userId = member.id;
const row = await sheet.tryFindRowByMultipleKeyValues([
['discord_id', userId],
['discord_username', member.user.username]
]);
if (!row) return false;
if (row.get('watiam')) {
// give the verified role to the user
await member.roles.add(env.ROLE_ID.VERIFIED);
await member.roles.add(env.ROLE_ID.CURRENT_UW_STUDENT);
addMissingFieldsToLegacyRow(member, row);
return true;
} else {
await sheet.deleteRow(row);
return false;
}
}
// Listen for new members
client.on('guildMemberAdd', async (member) => {
if (member.guild.id !== env.SERVER_ID) return;
if (await restoreVerificationStatus(member)) {
await sendExclusiveMessage('Welcome back to osu!uwaterloo! Your have been verified.', member);
logger.success(member, 'Has been verified', 'The user has been verified as a current UW student before. They rejoined the server and have been given the verified role automatically.');
}
});
// Setup verification button in announcements
async function setupVerificationButtonMessage(message: Message) {
const embed = new EmbedBuilder()
.setColor('#feeb1d')
.setDescription(`
# Verification
In order to chat in this server, you must be given the <@&${env.ROLE_ID.VERIFIED}> tag.
## You are a UWaterloo student
**If you are a Waterloo student, you can click on the button below to validate yourself as a current student**, which will verify you as well as grant you access to a dedicated section of the server just for actual club members. It also grants you tracking on the scores-feed, posts your stream to the stream-hype channel, and gets you added to our club website!
## You are not a UWaterloo student
If you are not a Waterloo student, just let us know how you found your way here and if possible, who invited you, in #manual-verify channel. Ping @Club Executive after doing this and you’ll be given the role ASAP.`
.replace(/^[ \t\r\f\v]+/gm, '').trim());
const verifyButton = new ButtonBuilder()
.setCustomId('verify_request')
.setLabel('Request Verification Link')
.setStyle(ButtonStyle.Primary);
const row = new ActionRowBuilder<ButtonBuilder>().addComponents(verifyButton);
return await (message.channel as TextChannel).send({
embeds: [embed],
components: [row]
});
}
async function onVerifyRequest(interaction: ButtonInteraction) {
// get all the roles of the user
const roles = (interaction.member!.roles as GuildMemberRoleManager).cache;
const isVerified = roles.has(env.ROLE_ID.VERIFIED);
const isCurrentUWStudent = roles.has(env.ROLE_ID.CURRENT_UW_STUDENT);
if (isCurrentUWStudent) {
if (!isVerified) {
// This circumstance should never happen, but just in case, give them the verified role
await (interaction.member!.roles as GuildMemberRoleManager).add(env.ROLE_ID.VERIFIED);
await interaction.reply({
content: 'You are already a current UW student. I have given you the verified role.',
ephemeral: true
});
} else {
await interaction.reply({
content: 'You are already verified as a current UW student.',
ephemeral: true
});
}
return;
}
const hasSkipRole = roles.some(role => env.SKIP_ROLE_IDS.includes(role.id));
if (hasSkipRole) {
await interaction.reply({
content: 'You are already verified as other roles such as Alumni. You do not need to verify again.',
ephemeral: true
});
return;
}
// If they are already verified before, give them the role
if (await restoreVerificationStatus(interaction.member as GuildMember)) {
await interaction.reply({
content: 'Welcome back to osu!uwaterloo! Your have been verified.',
ephemeral: true
});
logger.success(interaction.member as GuildMember, 'Has been verified', 'The user has been verified as a current UW student before. They made a verification request and have been given the verified role automatically.');
return;
}
// Generate a verification link and send it to the user
const member = interaction.member as GuildMember;
const verificationLink = getVerificationLink(interaction.member as GuildMember);
verificationPool.set(member.id, {
timestamp: Date.now(),
interaction: interaction,
expiry: Date.now() + 60 * 60 * 1000
});
const embed = new EmbedBuilder()
.setColor('#5865f2')
.setTitle('Verification Link')
.setDescription('Click the button below and login with your UWaterloo account to verify');
if (isVerified) {
embed.addFields({ name: 'Note', value: 'You are already verified, but not as a current UW student. If you are an UW student now, complete the verification process will grant you the current UW student role.' });
}
const verifyButton = new ButtonBuilder()
.setURL(verificationLink)
.setLabel('Verify')
.setStyle(ButtonStyle.Link);
const row = new ActionRowBuilder<ButtonBuilder>().addComponents(verifyButton);
await interaction.reply({
embeds: [embed],
components: [row],
ephemeral: true
});
}
function getVerificationLink(member: GuildMember) {
const encryptedUserId = encryptUserId(member.id);
return `${env.URL}/verify/${encryptedUserId}`;
}
// Send an exclusive message to the user via DM
// if DM fails, send an ephemeral message in the channel
async function sendExclusiveMessage(message: string | MessageCreateOptions | InteractionReplyOptions, member: GuildMember, interaction: BotInteraction | null = null) {
try {
// try DM first
await member.send(message as (string | MessageCreateOptions));
return true;
} catch (error) {
// if DM fails, send an ephemeral message in the channel
try {
if (interaction) {
if (typeof message === 'string') {
message = { content: message };
}
await interaction.reply({
...message as InteractionReplyOptions,
ephemeral: true
});
return true;
}
} catch (error) {
console.error('Error sending exclusive message:', error);
return false;
}
}
return false;
}
// The sheet has 2 fields: discord_id and discord_username
// We mainly use discord_id to identify the user, but the old entries only have discord_username
// This function will add whatever missing fields to the row
async function addMissingFieldsToLegacyRow(member: GuildMember, row: GoogleSpreadsheetRow | null = null) : Promise<boolean> {
const userId = member.id;
const username = member.user.username;
if (!row) {
row = await sheet.tryFindRowByMultipleKeyValues([
['discord_id', userId],
['discord_username', username]
]);
}
if (!row) return false;
if (row.get('watiam')) {
if (row.get('discord_id') !== userId || row.get('discord_username') !== username) {
await sheet.updateRow(row, {
discord_id: userId,
discord_username: username
});
}
return true;
} else {
return false;
}
}
// Manage membership slash command callback
const onSlashCommandManageMembership = async (interaction: ChatInputCommandInteraction) => {
// Check if the user has the verified role
const roles = (interaction.member!.roles as GuildMemberRoleManager).cache;
const isVerified = roles.has(env.ROLE_ID.VERIFIED);
const isCurrentUWStudent = roles.has(env.ROLE_ID.CURRENT_UW_STUDENT);
if (!isCurrentUWStudent || !isVerified) {
await interaction.reply({
content: 'You need to be a verified current UW student to manage your membership.',
ephemeral: true
});
return;
}
// Check if the user has a verified WatIAM in the sheet
await addMissingFieldsToLegacyRow(interaction.member as GuildMember);
const userId = (interaction.member as GuildMember).id;
const row = await sheet.findRowByKeyValue('discord_id', userId);
if (!row) {
await interaction.reply({
content: 'Please contact the club executives to get your data migrated. You have record with outdated discord username.',
ephemeral: true
});
return;
}
// Send the user a link to manage their membership
const expiry = Date.now() + 12 * 60 * 60 * 1000;
const key = `${userId}-${expiry}`;
const link = `${env.URL}/membership/${encryptUserId(key)}`;
const embed = new EmbedBuilder()
.setColor('#5865f2')
.setTitle('Manage Membership')
.setDescription(`Click the button below to manage your membership. This link will expire <t:${Math.floor(expiry / 1000)}:R>.`);
const manageButton = new ButtonBuilder()
.setURL(link)
.setLabel('Manage Membership')
.setStyle(ButtonStyle.Link);
const actionRow = new ActionRowBuilder<ButtonBuilder>().addComponents(manageButton);
await interaction.reply({
embeds: [embed],
components: [actionRow],
ephemeral: true
});
}
// Membership management routes
const getDataByEncryptedUserIdAndExpiry = async (encryptedUserIdAndExpiry: string | undefined, res: express.Response) => {
const userIdAndExpiry = decryptUserId(encryptedUserIdAndExpiry);
if (!userIdAndExpiry) {
res.send(getTemplate('error', { message: 'Invalid membership management link. It may be corrupted. Please use <code>/manage_membership</code> in the server to get a new link.' }));
return null;
}
const userId = userIdAndExpiry.split('-')[0];
const expiry = parseInt(userIdAndExpiry.split('-')[1]);
if (!userId) {
res.send(getTemplate('error', { message: 'Invalid membership management link. It may be corrupted. Please use <code>/manage_membership</code> in the server to get a new link.' }));
return null;
}
if (Date.now() > expiry) {
res.send(getTemplate('error', { message: 'Membership management link has expired for security reasons. Please use <code>/manage_membership</code> in the server to get a new link.' }));
return null;
}
const row = await sheet.findRowByKeyValue('discord_id', userId);
if (!row) {
res.send(getTemplate('error', { message: 'User not found in the database. Please contact the club executives to get your data migrated.' }));
return null;
}
return { userId, expiry, row };
}
// Member social media related types and constants
// TODO: move these to a separate file
// Update social media links
type SocialMediaField = {
id: string,
name: string,
description: string,
regex: string,
immutable?: boolean
};
// SocialLink is SocialMediaField with actual value
type SocialLink = SocialMediaField & {
enabled?: boolean,
value?: string
};
// Pre-defined social media fields
const socialMediaFields: SocialMediaField[] = [
{
id: "discord",
name: "Discord",
description: "Username",
regex: "^[a-zA-Z0-9_]{2,32}$"
},
{
id: "personal-website",
name: "Personal Website",
description: "URL (with http(s)://)",
regex: "^(https?://)?([a-zA-Z0-9]+\\.)?[a-zA-Z0-9][a-zA-Z0-9-]+\\.[a-zA-Z]{2,6}(\\.[a-zA-Z]{2,6})?(/.*)?$"
},
{
id: "github",
name: "GitHub",
description: "Username",
regex: "^[a-zA-Z0-9-]{1,39}$"
},
{
id: "twitch",
name: "Twitch",
description: "Username",
regex: "^[a-zA-Z0-9_]{4,25}$"
},
{
id: "youtube",
name: "YouTube",
description: "Channel Handle",
regex: "^[a-zA-Z0-9_]{1,39}$"
}
];
// membership management page
app.get('/membership/:encryptedUserIdAndExpiry', async (req: express.Request, res: express.Response): Promise<any> => {
const encryptedUserIdAndExpiry = req.params.encryptedUserIdAndExpiry;
const reqData = await getDataByEncryptedUserIdAndExpiry(encryptedUserIdAndExpiry, res);
if (!reqData) return;
const { userId, expiry, row } = reqData;
// Get the osu account id
const rawOsu = (row.get('osu') ?? '').trim();
let osuAccountId = '';
if (rawOsu.match(/^\d+$/)) {
osuAccountId = rawOsu;
} else if (rawOsu.includes('osu.ppy.sh')) {
osuAccountId = rawOsu.match(/\d+/)[0];
}
// Generate social links json
const socialLinksInSheetJson = (() => {
const raw = row.get('social_links');
if (!raw) return {};
try {
return JSON.parse(raw);
} catch (error) {
return {};
}
})();
const discordUsername = row.get('discord_username') ?? '';
const socialLinks: SocialLink[] = socialMediaFields.map(field => {
if (field.id === 'discord' && discordUsername) {
// If there is a discord username in record, use it and make it immutable
return {
...field,
enabled: socialLinksInSheetJson['discord'] !== '',
value: discordUsername,
immutable: true
};
}
if (socialLinksInSheetJson[field.id]) {
return {
...field,
enabled: true,
value: socialLinksInSheetJson[field.id]
};
} else {
return {
...field,
enabled: false
};
}
});
// Send the membership management page
res.send(getTemplate('membership', {
token: encryptedUserIdAndExpiry,
membershipManagementBaseUrl: `${env.URL}/membership/${encryptedUserIdAndExpiry}`,
discordId: userId,
discordUsername: row.get('discord_username'),
watiam: row.get('watiam') ?? 'Unknown',
osuAccount: osuAccountId,
displayOnWebsite: utils.parseHumanBool(row.get('display_on_website'), false),
socialMedia: JSON.stringify(socialLinks)
}));
});
// link osu account oauth redirect
app.get('/membership/:encryptedUserIdAndExpiry/link-osu-account', async (req: express.Request, res: express.Response): Promise<any> => {
const encryptedUserIdAndExpiry = req.params.encryptedUserIdAndExpiry;
const reqData = await getDataByEncryptedUserIdAndExpiry(encryptedUserIdAndExpiry, res);
if (!reqData) return;
const { userId, expiry, row } = reqData;
// Get the osu account id
const rawOsu = (row.get('osu') ?? '').trim();
let osuAccountId = '';
if (rawOsu.match(/^\d+$/)) {
osuAccountId = rawOsu;
} else if (rawOsu.includes('osu.ppy.sh')) {
osuAccountId = rawOsu.match(/\d+/)[0];
}
if (osuAccountId) {
return res.send(getTemplate('error', { message: 'You have already linked an osu account. If you want to change it, please unlink it in the membership management page first.' }));
}
const redirectUri = `${env.URL}/osu-auth-callback`;
const link = `https://osu.ppy.sh/oauth/authorize?client_id=${env.OSU_CLIENT_ID}&redirect_uri=${redirectUri}&response_type=code&scope=identify&state=${encryptedUserIdAndExpiry}`;
res.redirect(link);
});
// osu oauth callback
app.get('/osu-auth-callback', async (req: express.Request, res: express.Response): Promise<any> => {
const { code, state } = req.query;
const encryptedUserIdAndExpiry = state as string;
const reqData = await getDataByEncryptedUserIdAndExpiry(encryptedUserIdAndExpiry, res);
if (!reqData) return;
const { userId, expiry, row } = reqData;
const res2 = await fetch('https://osu.ppy.sh/oauth/token', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
client_id: env.OSU_CLIENT_ID,
client_secret: env.OSU_CLIENT_SECRET,
code,
grant_type: 'authorization_code',
redirect_uri: `${env.URL}/osu-auth-callback`
})
});
const data = await res2.json();
if (data.error) {
return res.send(getTemplate('error', { message: `Error linking osu account. Please try again later. Error: ${data.error}` }));
}
const accessToken = data.access_token;
const res3 = await fetch('https://osu.ppy.sh/api/v2/me', {
headers: {
Authorization: `Bearer ${accessToken}`
}
});
const userData = await res3.json();
const osuAccountId = userData.id.toString();
// Update the row
await sheet.updateRow(row, {
osu: `https://osu.ppy.sh/users/${osuAccountId}`
});
// Logging
logger.info(null, 'Linked osu! account', 'They have linked their osu! account.', embed => {
embed.setAuthor({ name: `@${row.get('discord_username')}`, url: `https://discord.com/users/${userId}` });
embed.setFooter({ text: `ID: ${userId}` });
embed.setThumbnail(`https://a.ppy.sh/${osuAccountId}`);
embed.addFields(
{ name: 'osu! UID', value: osuAccountId, inline: true },
{ name: 'osu! username', value: userData.username, inline: true }
);
}, () => {
const row = new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setLabel('osu! Profile')
.setStyle(ButtonStyle.Link)
.setURL(`https://osu.ppy.sh/users/${osuAccountId}`)
);
return row;
} );
// Redirect to the membership management page
res.redirect(`${env.URL}/membership/${encryptedUserIdAndExpiry}`);
});
// unlink osu account
app.post('/membership/:encryptedUserIdAndExpiry/unlink-osu-account', async (req: express.Request, res: express.Response): Promise<any> => {
const encryptedUserIdAndExpiry = req.params.encryptedUserIdAndExpiry;
const reqData = await getDataByEncryptedUserIdAndExpiry(encryptedUserIdAndExpiry, res);
if (!reqData) return;
const { userId, expiry, row } = reqData;
// Get the osu account id
const rawOsu = (row.get('osu') ?? '').trim();
let osuAccountId = '';
if (rawOsu.match(/^\d+$/)) {
osuAccountId = rawOsu;
} else if (rawOsu.includes('osu.ppy.sh')) {
osuAccountId = rawOsu.match(/\d+/)[0];
}
if (!osuAccountId) {
return res.send({ status: 'error', message: 'You have not linked an osu account yet.' });
}
// Delete the osu account from the row
await sheet.updateRow(row, {
osu: ''
});
// Logging
logger.info(null, 'Unlinked osu! account', 'They have unlinked their osu! account.', embed => {
embed.setAuthor({ name: `@${row.get('discord_username')}`, url: `https://discord.com/users/${userId}` });
embed.setFooter({ text: `ID: ${userId}` });
embed.setThumbnail(`https://a.ppy.sh/${osuAccountId}`);
embed.addFields({ name: 'osu! UID', value: osuAccountId });
}, () => {
const row = new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setLabel('osu! Profile')
.setStyle(ButtonStyle.Link)
.setURL(`https://osu.ppy.sh/users/${osuAccountId}`)
);
return row;
});
// Return success
res.send({ status: 'success' });
});
// Update display on website status
app.post('/membership/:encryptedUserIdAndExpiry/update-display-on-website', async (req: express.Request, res: express.Response): Promise<any> => {
const encryptedUserIdAndExpiry = req.params.encryptedUserIdAndExpiry;
const reqData = await getDataByEncryptedUserIdAndExpiry(encryptedUserIdAndExpiry, res);
if (!reqData) return;
const { userId, expiry, row } = reqData;
const displayOnWebsite = req.body.displayOnWebsite;
await sheet.updateRow(row, {
display_on_website: displayOnWebsite.toString()
});
// Return success
res.send({ status: 'success' });
});
// Update social media links
app.post('/membership/:encryptedUserIdAndExpiry/update-social-links', async (req: express.Request, res: express.Response): Promise<any> => {
const encryptedUserIdAndExpiry = req.params.encryptedUserIdAndExpiry;
const reqData = await getDataByEncryptedUserIdAndExpiry(encryptedUserIdAndExpiry, res);
if (!reqData) return;
const { userId, expiry, row } = reqData;
const socialLinks = req.body.socialLinks;
const discordUsernameInSheet = row.get('discord_username') ?? '';
// Validate
for (const key in socialLinks) {
const field = socialMediaFields.find(field => field.id === key);
const value = socialLinks[key];
if (!field) {
return res.send({ status: 'error', message: `Invalid social media field: ${key}` });
}
if (typeof value !== 'string') {
return res.send({ status: 'error', message: `Invalid value for ${field.name}` });
}
if (key === 'discord' && discordUsernameInSheet) {
// If they have a discord username in record, special check for discord later
continue;
}
if (!value.match(new RegExp(field.regex))) {
return res.send({ status: 'error', message: `Invalid value for ${field.name}` });
}
}
// Validate discord username
if ('discord' in socialLinks && discordUsernameInSheet) {
const value = socialLinks['discord'];
if (value !== discordUsernameInSheet && value !== '') {
return res.send({ status: 'error', message: 'Invalid value for Discord username.' });
}
if (value === discordUsernameInSheet) {
delete socialLinks['discord'];
}
}
// Update the row
await sheet.updateRow(row, {
social_links: JSON.stringify(socialLinks)
});
// Return success
res.send({ status: 'success' });
});
// Server custom colour roles self-assign
const getServerColourRoles = async (guild: Guild): Promise<{
range: [number, number] | null, // (startPosition, endPosition), exclusive
colourRoles: Role[]
}> => {
let allServerRoles = await guild.roles.fetch();
allServerRoles = allServerRoles.sort((a, b) => b.position - a.position);
const array = Array.from(allServerRoles.values());
let startIndex = -1, endIndex = -1;
let startPosition = -1, endPosition = -1;
for (let i = 0; i < array.length; i++) {
const role = array[i];
if (role.id === env.COLOUR_ROLE_IDS.COLOUR_ROLE_SECTION_BEGIN) {
startIndex = i;
startPosition = role.position;
if (endIndex !== -1) break;
} else if (role.id === env.COLOUR_ROLE_IDS.COLOUR_ROLE_SECTION_END) {
endIndex = i;
endPosition = role.position;
if (startIndex !== -1) break;
}
}
// notice higher roles also have higher positions
if (startIndex === -1 || endIndex === -1) {
return { range: null, colourRoles: [] };
}
if (startIndex > endIndex) {
[startIndex, endIndex] = [endIndex, startIndex];
[startPosition, endPosition] = [endPosition, startPosition];
}
return {
range: [startPosition, endPosition],
colourRoles: array.slice(startIndex + 1, endIndex)
};
}
async function onSlashCommandSetNameColour(interaction: ChatInputCommandInteraction) {
// If the user is not verified, reject
const member = interaction.member as GuildMember;
const roles = member.roles.cache.sort((a, b) => b.position - a.position);
const isVerified = roles.has(env.ROLE_ID.VERIFIED);
if (!isVerified) {
await interaction.reply({
content: 'You need to be verified to set a custom name colour.',
ephemeral: true
});
return;
}
// Parse the hex colour
const hex = utils.parseHexColour(interaction.options.getString('hex', true));
if (!hex) {
await interaction.reply({
content: 'Please enter a valid hex colour code. Example: `#ff66ab`.',
ephemeral: true
});
return;
}
// Check if it is #000000
if (hex === '#000000') {
await interaction.reply({
content: 'Discord does not allow setting the name colour to black, as it represents the default colour (no colour) of the role. Please choose a different colour.',
ephemeral: true
});
return;
}
// Check colour contrast
const contrastDark = utils.calculateColourContrast(hex, '#313338');
const contrastLight = utils.calculateColourContrast(hex, '#ffffff');
if (contrastDark < 2 || contrastLight < 1.25) {
await interaction.reply({
content: `
The colour you have chosen does not have enough contrast with the background. Please choose a colour with better contrast.
WCAG Contrast Ratio:
**Dark Theme:** ${contrastDark.toFixed(2)} ${contrastDark >= 2 ? '✅' : '❌'} (>= 2 Required)
**Light Theme:** ${contrastLight.toFixed(2)} ${contrastLight >= 1.25 ? '✅' : '❌'} (>= 1.25 Required)
You can use [this tool](https://webaim.org/resources/contrastchecker/?fcolor=${contrastDark < 2 ? '313338' : 'ffffff'}&bcolor=${hex.slice(1)}) to check the contrast.
If you really want to use this colour, please contact an executive.
`.replace(/^[ \t\r\f\v]+/gm, '').trim(),
ephemeral: true
});
return;
}
// Get server colour roles
const guild = interaction.guild!;
const {
range: serverColourRoleRange,
colourRoles: serverColourRoles
} = await getServerColourRoles(guild);
if (!serverColourRoleRange) {
await interaction.reply({
content: 'Server colour roles are not set up properly. Please contact the server administrators.',
ephemeral: true
});
return;
}
const [startPosition, endPosition] = serverColourRoleRange;
// Get member's top coloured role
let topColourRole = null;
for (const role of roles.values()) {
if (role.color !== 0) {
topColourRole = role;
break;
}
}
// If top colour role is higher than the server colour roles, reject
if (topColourRole && topColourRole.position > startPosition) {
await interaction.reply({
content: 'You already have coloured role(s) that has higher priority than the server colour roles. Please contact an executive if you want to set a custom colour.',
ephemeral: true
});
return;
}
// If their colour role is in the server colour roles and has >= 2 people using it, remove it first
if (
topColourRole &&
topColourRole.position < startPosition && topColourRole.position > endPosition &&
topColourRole.members.size > 1
) {
await member.roles.remove(topColourRole);
topColourRole = null;
}
// If their colour role is in the server colour roles and has 1 person using it, update it
if (
topColourRole &&
topColourRole.position < startPosition && topColourRole.position > endPosition &&
topColourRole.members.size === 1
) {
const isHexName = topColourRole.name.match(/^#?[0-9a-fA-F]{6}$/);
if (isHexName) {
await topColourRole.edit({ name: hex, color: hex });
} else {
await topColourRole.edit({ color: hex });
}
await interaction.reply({
content: `Your name colour has been set to \`${hex}\`.`,
ephemeral: true
});
logger.info(member, 'Set custom name colour', `Set their name colour to ${hex}.\nColour role: <@&${topColourRole.id}>`);
return;
}
// If they dont have a top colour role, or their top colour role is lower than the server colour roles