From aef626eda08c70cd9befac371ba9bdd8dc8293ff Mon Sep 17 00:00:00 2001 From: Preston Lim Date: Mon, 10 May 2021 18:49:05 +0800 Subject: [PATCH] fix: whoami endpoint should return 200 --- middleware/auth.js | 16 +++++++++++++++- routes/auth.js | 23 ++++++++++++++--------- 2 files changed, 29 insertions(+), 10 deletions(-) diff --git a/middleware/auth.js b/middleware/auth.js index 8df6b82b9..19e5d7980 100644 --- a/middleware/auth.js +++ b/middleware/auth.js @@ -36,10 +36,24 @@ const verifyJwt = (req, res, next) => { return next('router') } +// Extracts access_token if any, else set access_token to null +const whoamiAuth = (req, res, next) => { + let access_token + try { + const { isomercms } = req.cookies + access_token = jwtUtils.verifyToken(isomercms).access_token + } catch (err) { + access_token = undefined + } finally { + req.accessToken = access_token + return next('router') + } +} + // Login and logout auth.get('/v1/auth', noVerify) auth.get('/v1/auth/logout', noVerify) -auth.get('/v1/auth/whoami', verifyJwt) +auth.get('/v1/auth/whoami', whoamiAuth) // Index auth.get('/v1', noVerify) diff --git a/routes/auth.js b/routes/auth.js index 2b2575570..83be80f38 100644 --- a/routes/auth.js +++ b/routes/auth.js @@ -84,15 +84,20 @@ async function whoami(req, res) { // Make a call to github const endpoint = 'https://api.github.com/user' - const resp = await axios.get(endpoint, { - headers: { - Authorization: `token ${accessToken}`, - "Content-Type": "application/json" - } - }) - - const { login: userId } = resp.data - res.status(200).json({ userId }) + let userId + try { + const resp = await axios.get(endpoint, { + headers: { + Authorization: `token ${accessToken}`, + "Content-Type": "application/json" + } + }) + userId = resp.data.login + } catch (err) { + userId = undefined + } finally { + res.status(200).json({ userId }) + } } router.get('/', attachReadRouteHandlerWrapper(githubAuth));