Last active
September 21, 2022 22:24
-
-
Save hovissimo/5c97d1938070d8f678eb20df78e09cdd 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
export const availableEndpoint = | |
(handler) => async (req) => { | |
let currentUser | |
try { | |
currentUser = await authorizeUser(req) | |
} catch (e) { | |
if (e instanceof UnauthorizedError) { | |
// pass! | |
} else { | |
throw e | |
} | |
} | |
// Make the currentUser available to the remaining handlers | |
req.currentUser = currentUser | |
// Make the currentUser available in the store (if the remaining handlers made one) | |
const result = await handler(req) | |
if (result.json) { | |
result.json.currentUser = currentUser | |
} | |
return result | |
} |
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
const loggedEndpoint = (handler) => async (req) => { | |
console.group( | |
`${new Date().toISOString()} ${req.method} ${req.path}` | |
) | |
const result = await handler(req) | |
console.groupEnd() | |
return result | |
} |
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
export const protectedEndpoint = | |
(handler) => async (req) => { | |
let currentUser | |
try { | |
currentUser = await authorizeUser(req) | |
} catch (e) { | |
if (e instanceof UnauthorizedError) { | |
console.log( | |
`protectedEndpoint prevented access to ${req.method} ${req.path}` | |
) | |
return { | |
json: null, | |
session: { ...req.session, returnTo: req.path }, | |
location: '/auth/login', | |
} | |
} else { | |
throw e | |
} | |
} | |
// Make the currentUser available to the remaining handlers | |
req.currentUser = currentUser | |
// Make the currentUser available in the store (if the remaining handlers made one) | |
const result = await handler(req) | |
if (result.json) { | |
result.json.currentUser = currentUser | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment