Skip to content

Commit

Permalink
Add checks to make sure user only has one token.
Browse files Browse the repository at this point in the history
This commit implements fixes for the issues talked about in comment: #301 (comment)
Also changed the migration back to unique
  • Loading branch information
daanbreur committed Jul 25, 2024
1 parent 8b22bd2 commit 6d44414
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 3 deletions.
2 changes: 1 addition & 1 deletion api/migrations/55-discord-account-invitation-link.sql
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
ALTER TABLE ctfnote_private.invitation_link
ADD COLUMN "discord_id" TEXT DEFAULT NULL;
ADD COLUMN "discord_id" TEXT UNIQUE DEFAULT NULL;

DROP FUNCTION ctfnote.create_invitation_link ("role" ctfnote.role);
CREATE OR REPLACE FUNCTION ctfnote.create_invitation_link ("role" ctfnote.role, "discord_id" text default null)
Expand Down
18 changes: 18 additions & 0 deletions api/src/discord/commands/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,24 @@ async function createAccountLogic(
return;
}

const existing_invitation_code = await getInvitationTokenForDiscordId(
interaction.user.id
);
if (existing_invitation_code != null) {
const invitation_url = await getInvitationUrl(existing_invitation_code);
if (invitation_url == "") {
await interaction.editReply({
content: "Something went wrong.", // TODO: Meaningful error messages?
});
return;
}

await interaction.editReply({
content: `Your personal invitation url: ${invitation_url}. If you already have a CTFNote account you should link it using the /link command instead.`,
});
return;
}

await interaction.editReply({
content:
"Generating private invitation url... If you already have a CTFNote account you should link it using the /link command instead.",
Expand Down
23 changes: 21 additions & 2 deletions api/src/discord/database/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,27 @@ type AllowedRoles =
| "user_manager"
| "user_admin";

export async function createInvitationURLForDiscordId(
role: AllowedRoles,
export async function getInvitationTokenForDiscordId(
discordId: string,
pgClient: PoolClient | null = null
): Promise<string | null> {
const useRequestClient = pgClient != null;
if (pgClient == null) pgClient = await connectToDatabase();

try {
const query =
"SELECT token FROM ctfnote_private.invitation_link WHERE discord_id = $1";
const values = [discordId];
const queryResult = await pgClient.query(query, values);

return queryResult.rows[0].token as string;
} catch (error) {
return null;
} finally {
if (!useRequestClient) pgClient.release();
}
}

discordId: string,
pgClient: PoolClient | null = null
): Promise<string | null> {
Expand Down

0 comments on commit 6d44414

Please sign in to comment.