Created
April 4, 2025 11:26
-
-
Save markgarrigan/6e639dbb97daedc556f33e160bb1d8fc to your computer and use it in GitHub Desktop.
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
app.get('/auth/github', (req, res) => { | |
const redirectUri = req.query.redirect_uri || '/'; | |
req.session.redirectUri = redirectUri; | |
const params = new URLSearchParams({ | |
client_id: process.env.GITHUB_CLIENT_ID, | |
redirect_uri: 'http://localhost:3000/auth/github/callback', | |
scope: 'read:user user:email', | |
allow_signup: 'true', | |
}); | |
const authUrl = `https://github.com/login/oauth/authorize?${params.toString()}`; | |
res.redirect(authUrl); | |
}); | |
app.get('/auth/github/callback', async (req, res) => { | |
const code = req.query.code; | |
if (!code) return res.status(400).send('Missing code from GitHub'); | |
const payload = { | |
client_id: process.env.GITHUB_CLIENT_ID, | |
client_secret: process.env.GITHUB_CLIENT_SECRET, | |
code, | |
redirect_uri: 'http://localhost:3000/auth/github/callback', | |
}; | |
const tokenRes = await axios.post( | |
'https://github.com/login/oauth/access_token', | |
toFormData(payload), | |
{ headers: { Accept: 'application/json' } } // Important for GitHub | |
); | |
const accessToken = tokenRes.data.access_token; | |
// Fetch user profile from GitHub | |
const userRes = await axios.get('https://api.github.com/user', { | |
headers: { | |
Authorization: `Bearer ${accessToken}`, | |
Accept: 'application/vnd.github+json' | |
} | |
}); | |
// Optional: fetch primary verified email | |
const emailRes = await axios.get('https://api.github.com/user/emails', { | |
headers: { | |
Authorization: `Bearer ${accessToken}`, | |
Accept: 'application/vnd.github+json' | |
} | |
}); | |
const primaryEmail = emailRes.data.find(e => e.primary && e.verified)?.email; | |
req.session.tokens = { | |
github: { | |
accessToken, | |
}, | |
}; | |
req.session.user = { | |
provider: 'github', | |
id: userRes.data.id, | |
username: userRes.data.login, | |
avatar_url: userRes.data.avatar_url, | |
email: primaryEmail, | |
}; | |
const redirectTo = req.session.redirectUri || '/'; | |
delete req.session.redirectUri; | |
req.session.save(() => res.redirect(redirectTo)); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment