Created
December 8, 2019 07:02
-
-
Save alant/f555f7419db2094af73e9725249ab52d to your computer and use it in GitHub Desktop.
This file contains 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
const loginWithGithub = async (req, res, next) => { | |
try { | |
// exchange "code" for a access token which never expire as of 201912 | |
const atoken_resp = await axios.post('https://github.com/login/oauth/access_token', | |
{ | |
client_id: process.env.GITHUB_CLIENT_ID, | |
client_secret: process.env.GITHUB_CLIENT_SECRET, | |
code: req.body.code | |
} | |
); | |
const parsed = queryString.parse(atoken_resp.data); | |
const access_token = parsed.access_token; | |
const user_resp = await axios.get('https://api.github.com/user', { | |
headers: { | |
'Authorization': "bearer " + access_token, | |
'User-Agent': 'smartshoppinglist' | |
} | |
}); | |
const email_resp = await axios.get('https://api.github.com/user/public_emails', { | |
headers: { | |
'Authorization': "bearer " + access_token, | |
'User-Agent': 'smartshoppinglist' | |
} | |
}); | |
req.email = email_resp.data[0].email; | |
let profile = { | |
email: email_resp.data[0].email, | |
id: user_resp.data.id, | |
name: user_resp.data.name, | |
avatar_url: user_resp.data.avatar_url | |
}; | |
await User.upsertGithubUser(profile); | |
} catch (err) { | |
console.log("====> github err: ", err); | |
res.status(500).send({ auth: false, message: 'Failed to auth through github.' }); | |
} | |
next(); | |
} | |
const issueJwt = function (req, res, next) { | |
let jwt_token = jwt.sign({ email: req.email }, | |
process.env.JWT_SECRET, | |
{ expiresIn: 30 * 24 * 60 * 60 }// expires in 30 days | |
); | |
res.json({ | |
token: jwt_token | |
}); | |
next(); | |
} | |
app.post('/login/github', loginWithGithub, issueJwt, (req, res) => {}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment