-
Notifications
You must be signed in to change notification settings - Fork 10
feat: add GitHub OAuth login and registration #44
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
HarshYadav152
merged 6 commits into
HarshYadav152:main
from
SakethSumanBathini:feat/github-oauth
Jun 8, 2026
Merged
Changes from 1 commit
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
2e7e313
feat: add GitHub OAuth login and registration
SakethSumanBathini 2535202
fix(auth): link GitHub accounts only on verified email, add conflict …
SakethSumanBathini 7eacd1c
fix(auth): confirm session at /auth/success before redirecting to /vault
SakethSumanBathini 95254d8
fix(auth/success): remove startedRef StrictMode guard, add per-fetch …
SakethSumanBathini 55484a4
fix(auth/success): move page into (auth) group for consistency
SakethSumanBathini e4f498e
fix(auth/callback): cap username dedup loop + add path:'/' to authTok…
SakethSumanBathini File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,154 @@ | ||
| import { NextResponse } from 'next/server'; | ||
| import connectingtoDB from '@/lib/db/mongodb'; | ||
| import User from '@/lib/models/User'; | ||
| import { generateAccessToken } from '@/lib/utils/jwt'; | ||
|
|
||
| const STATE_COOKIE = 'github_oauth_state'; | ||
| const GITHUB_TOKEN_URL = 'https://github.com/login/oauth/access_token'; | ||
| const GITHUB_USER_URL = 'https://api.github.com/user'; | ||
| const GITHUB_EMAILS_URL = 'https://api.github.com/user/emails'; | ||
|
|
||
| function loginRedirect(errorCode) { | ||
| const base = process.env.NEXT_PUBLIC_API_HOST || 'http://localhost:3000'; | ||
| const url = new URL('/login', base); | ||
| if (errorCode) url.searchParams.set('error', errorCode); | ||
| return NextResponse.redirect(url); | ||
| } | ||
|
|
||
| // GET /api/v1/auth/github/callback | ||
| // Validates the CSRF state, exchanges the code for a token, resolves the GitHub | ||
| // profile + verified email, links or creates the user, and issues the same | ||
| // session cookie the password login uses. | ||
| export async function GET(req) { | ||
| try { | ||
| const { searchParams } = new URL(req.url); | ||
| const code = searchParams.get('code'); | ||
| const state = searchParams.get('state'); | ||
|
|
||
| // 1. CSRF: state must be present and match the cookie set at initiation. | ||
| const storedState = req.cookies.get(STATE_COOKIE)?.value; | ||
| if (!code || !state || !storedState || state !== storedState) { | ||
| return loginRedirect('github_state_mismatch'); | ||
| } | ||
|
|
||
| const clientId = process.env.GITHUB_OAUTH_CLIENT_ID; | ||
| const clientSecret = process.env.GITHUB_OAUTH_CLIENT_SECRET; | ||
| const callbackUrl = process.env.GITHUB_OAUTH_CALLBACK_URL; | ||
| if (!clientId || !clientSecret || !callbackUrl) { | ||
| return loginRedirect('github_oauth_not_configured'); | ||
| } | ||
|
|
||
| // 2. Exchange the authorization code for an access token. | ||
| const tokenRes = await fetch(GITHUB_TOKEN_URL, { | ||
| method: 'POST', | ||
| headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, | ||
| body: JSON.stringify({ | ||
| client_id: clientId, | ||
| client_secret: clientSecret, | ||
| code, | ||
| redirect_uri: callbackUrl, | ||
| }), | ||
| }); | ||
| const tokenData = await tokenRes.json(); | ||
| const accessToken = tokenData?.access_token; | ||
| if (!accessToken) { | ||
| return loginRedirect('github_token_exchange_failed'); | ||
| } | ||
|
|
||
| // 3. Fetch the GitHub profile. | ||
| const ghHeaders = { | ||
| Authorization: `Bearer ${accessToken}`, | ||
| Accept: 'application/vnd.github+json', | ||
| 'User-Agent': 'gsecure', | ||
| }; | ||
| const userRes = await fetch(GITHUB_USER_URL, { headers: ghHeaders }); | ||
| if (!userRes.ok) { | ||
| return loginRedirect('github_profile_fetch_failed'); | ||
| } | ||
| const ghUser = await userRes.json(); | ||
| const githubId = ghUser?.id != null ? String(ghUser.id) : null; | ||
| const login = ghUser?.login; | ||
| if (!githubId || !login) { | ||
| return loginRedirect('github_profile_incomplete'); | ||
| } | ||
|
|
||
| // 4. Resolve a verified primary email (server-side), with a deterministic | ||
| // GitHub no-reply fallback so the required email field is always set. | ||
| let email = null; | ||
| const emailsRes = await fetch(GITHUB_EMAILS_URL, { headers: ghHeaders }); | ||
| if (emailsRes.ok) { | ||
| const emails = await emailsRes.json(); | ||
| if (Array.isArray(emails)) { | ||
| const primaryVerified = emails.find((e) => e.primary && e.verified); | ||
| const anyVerified = emails.find((e) => e.verified); | ||
| email = (primaryVerified || anyVerified || emails[0])?.email || null; | ||
| } | ||
| } | ||
| if (!email) { | ||
| email = `${githubId}+${login}@users.noreply.github.com`; | ||
| } | ||
| email = email.toLowerCase(); | ||
|
|
||
| await connectingtoDB(); | ||
|
|
||
| // 5. Account linking (prevents duplicate accounts): | ||
| // a) returning GitHub user -> matched by githubId | ||
| // b) existing local user, same email -> link githubId onto it | ||
| // c) otherwise -> create a new GitHub-authenticated account | ||
| let user = await User.findOne({ githubId }); | ||
|
|
||
| if (!user) { | ||
| const byEmail = await User.findOne({ email }); | ||
| if (byEmail) { | ||
| byEmail.githubId = githubId; | ||
| await byEmail.save(); | ||
| user = byEmail; | ||
|
coderabbitai[bot] marked this conversation as resolved.
Outdated
|
||
| } | ||
| } | ||
|
|
||
| if (!user) { | ||
| // Dedupe the chosen username against the unique index. | ||
| let username = login.toLowerCase(); | ||
| let attempt = 0; | ||
| while (await User.findOne({ username })) { | ||
| attempt += 1; | ||
| username = | ||
| attempt === 1 | ||
| ? `${login.toLowerCase()}-${githubId.slice(-4)}` | ||
| : `${login.toLowerCase()}-${Math.random().toString(36).slice(2, 8)}`; | ||
| } | ||
| user = await User.create({ | ||
| username, | ||
| email, | ||
| githubId, | ||
| authProvider: 'github', | ||
| }); | ||
| } | ||
|
|
||
| // 6. Issue the same session token + cookie the password login uses. | ||
| const { authToken } = await generateAccessToken(user._id); | ||
|
|
||
| const base = process.env.NEXT_PUBLIC_API_HOST || 'http://localhost:3000'; | ||
| const response = NextResponse.redirect(new URL('/vault', base)); | ||
|
|
||
| response.cookies.set('authToken', authToken, { | ||
| httpOnly: true, | ||
| secure: process.env.NODE_ENV === 'production', | ||
| sameSite: 'strict', | ||
| maxAge: 60 * 60 * 24 * 7, // 7 days | ||
| }); | ||
| // Clear the one-time CSRF state cookie. | ||
| response.cookies.set(STATE_COOKIE, '', { | ||
| httpOnly: true, | ||
| secure: process.env.NODE_ENV === 'production', | ||
| sameSite: 'lax', | ||
| maxAge: 0, | ||
| path: '/', | ||
| }); | ||
|
|
||
| return response; | ||
| } catch (error) { | ||
| console.error('GitHub OAuth callback error:', error); | ||
| return loginRedirect('github_oauth_failed'); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| import { NextResponse } from 'next/server'; | ||
|
|
||
| const GITHUB_AUTHORIZE_URL = 'https://github.com/login/oauth/authorize'; | ||
| const STATE_COOKIE = 'github_oauth_state'; | ||
|
|
||
| // GET /api/v1/auth/github | ||
| // Kicks off the GitHub OAuth flow: sets a short-lived CSRF "state" cookie and | ||
| // redirects the browser to GitHub's authorize screen. | ||
| export async function GET() { | ||
| const clientId = process.env.GITHUB_OAUTH_CLIENT_ID; | ||
| const callbackUrl = process.env.GITHUB_OAUTH_CALLBACK_URL; | ||
| const base = process.env.NEXT_PUBLIC_API_HOST || 'http://localhost:3000'; | ||
|
|
||
| if (!clientId || !callbackUrl) { | ||
| // Misconfigured server -> send the user back to login instead of erroring. | ||
| const url = new URL('/login', base); | ||
| url.searchParams.set('error', 'github_oauth_not_configured'); | ||
| return NextResponse.redirect(url); | ||
| } | ||
|
|
||
| // Random, unguessable state echoed back by GitHub and verified in the callback. | ||
| const state = crypto.randomUUID(); | ||
|
|
||
| const authorizeUrl = new URL(GITHUB_AUTHORIZE_URL); | ||
| authorizeUrl.searchParams.set('client_id', clientId); | ||
| authorizeUrl.searchParams.set('redirect_uri', callbackUrl); | ||
| authorizeUrl.searchParams.set('scope', 'read:user user:email'); | ||
| authorizeUrl.searchParams.set('state', state); | ||
| authorizeUrl.searchParams.set('allow_signup', 'true'); | ||
|
|
||
| const response = NextResponse.redirect(authorizeUrl); | ||
|
|
||
| // sameSite 'lax' (NOT 'strict') so this CSRF cookie survives GitHub's | ||
| // cross-site redirect back to the callback. The session cookie stays strict. | ||
| response.cookies.set(STATE_COOKIE, state, { | ||
| httpOnly: true, | ||
| secure: process.env.NODE_ENV === 'production', | ||
| sameSite: 'lax', | ||
| maxAge: 600, // 10 minutes | ||
| path: '/', | ||
| }); | ||
|
|
||
| return response; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.