Skip to content

[#370] Automatically add members to KH Discord server#373

Merged
DVidal1205 merged 7 commits intomainfrom
blade/auto-add-users
Feb 17, 2026
Merged

[#370] Automatically add members to KH Discord server#373
DVidal1205 merged 7 commits intomainfrom
blade/auto-add-users

Conversation

@danrmzz
Copy link
Contributor

@danrmzz danrmzz commented Feb 17, 2026

Why

Users aren't guaranteed to be in the Knight Hacks discord server while interacting with Blade. This can cause issues i.e., users not properly being assigned roles upon submitting a form.

What

Issue(s): #370

  • Added Discord join helpers in API util
    • addMemberToServer
    • handleDiscordOAuthCallback
  • Added Better Auth databaseHooks to trigger Discord auto join
    • Implemented session.create.after hook that reads user.discordUserId and invokes handleDiscordOAuthCallback so users are automatically added to the Discord server after logging in
  • Updated Discord auth scope to include guilds.join

Test Plan

370.mp4

Checklist

  • Database: No schema changes, OR I have contacted the Development Lead to run db:push before merging
  • Environment Variables: No environment variables changed, OR I have contacted the Development Lead to modify them on Coolify BEFORE merging.

Summary by CodeRabbit

  • New Features
    • Streamlined Discord integration: session creation now triggers automatic OAuth callback handling for linked Discord accounts.
    • Automatic Discord server member management: users can be added to Discord servers after linking.
    • Expanded Discord authorization scope to support guilds.join for server-level operations.

@danrmzz danrmzz self-assigned this Feb 17, 2026
@danrmzz danrmzz added Feature New Feature or Request Blade Change modifies code in Blade app labels Feb 17, 2026
@coderabbitai
Copy link

coderabbitai bot commented Feb 17, 2026

📝 Walkthrough

Walkthrough

Adds Discord OAuth handling: two new utility functions to process OAuth callbacks and add users to a guild, plus a post-session database hook that triggers this flow. The Discord social provider scope now includes guilds.join.

Changes

Cohort / File(s) Summary
Discord OAuth Utilities
packages/api/src/utils.ts
Added addMemberToServer(discordUserId, accessToken) and handleDiscordOAuthCallback(discordUserId) with try/catch logging; expanded imports to include desc (drizzle-orm) and Account (auth schemas). Functions query DB for Discord account, check scopes, and call Discord API to join a guild.
Auth config & hooks
packages/auth/src/config.ts
Added guilds.join to Discord provider scope. Introduced databaseHooks on auth that runs after session creation: it looks up the user, extracts discordUserId, and calls handleDiscordOAuthCallback(discordUserId) when present. Also added eq import and reference to utils handler.
TS config
packages/auth/tsconfig.json
Updated TypeScript lib target from ES2015 to ES2021.

Sequence Diagram

sequenceDiagram
    participant Auth as Auth System
    participant DB as Database
    participant Util as API Utils
    participant Discord as Discord API

    Auth->>DB: create session for user
    Auth->>Util: handleDiscordOAuthCallback(discordUserId)
    Util->>DB: query User and Account (latest Discord account)
    alt account exists & has guilds.join scope
        Util->>Util: extract access token
        Util->>Discord: POST /users/@me/guilds/{guildId} (add member) with token
        Discord-->>Util: response (success/failure)
        Util-->>Auth: log success/failure
    else missing account or scope
        Util-->>Auth: log no-op / error
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

Suggested labels

API, Major

🚥 Pre-merge checks | ✅ 5 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title follows the required format with issue number [#370], is concise, and directly describes the main change of automatically adding members to the Discord server.
No Hardcoded Secrets ✅ Passed No hardcoded secrets, API keys, passwords, or tokens found. Sensitive data properly handled via parameters and environment sources.
Validated Env Access ✅ Passed PR adheres to codebase convention of using validated environment imports instead of direct process.env access across all modified files.
No Typescript Escape Hatches ✅ Passed The PR avoids TypeScript escape hatches with proper optional chaining, type guards, and error handling; no any types or non-null assertions.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch blade/auto-add-users

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/blade/src/app/api/auth/callback/discord/route.ts`:
- Around line 12-26: Don't query the globally most-recent Discord account (the
db.query.Account.findFirst call with Account.provider === "discord"); instead
import betterAuthInstance from your auth config, extract the session tied to
this callback by reading the response's Set-Cookie header, use that session to
look up the authenticated user/account, and pass that user's discordUserId into
handleDiscordOAuthCallback so the callback runs for the current OAuth session
rather than the latest DB record.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/auth/src/config.ts`:
- Around line 63-75: The post-session hook (databaseHooks.session.create.after)
can throw during the DB lookup (db.query.User.findFirst using User.id and
session.userId) and should be made resilient: wrap the entire async hook body in
a try/catch, call handleDiscordOAuthCallback(discordUserId) as before but catch
and log any errors (using the existing logger) and ensure the function
returns/ends without re-throwing so session creation is not blocked by failures.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/auth/tsconfig.json`:
- Line 5: Update the tsconfig "lib" entry to match the project standard: replace
"ES2021", "DOM", "DOM.Iterable" with "ES2022", "dom", "dom.iterable" so the
packages/auth tsconfig aligns with other configs; edit the "lib" array in
packages/auth's tsconfig.json accordingly to use ES2022 and lowercase dom
entries.

Copy link

@DVidal1205-Crest DVidal1205-Crest left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

genuinely beautiful

Copy link
Contributor

@DVidal1205 DVidal1205 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what he said

@DVidal1205 DVidal1205 added this pull request to the merge queue Feb 17, 2026
Merged via the queue into main with commit 8a8869f Feb 17, 2026
8 checks passed
@DVidal1205 DVidal1205 deleted the blade/auto-add-users branch February 17, 2026 20:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Blade Change modifies code in Blade app Feature New Feature or Request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants