Skip to content

Instantly share code, notes, and snippets.

@hovissimo
Last active September 21, 2022 22:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hovissimo/5c97d1938070d8f678eb20df78e09cdd to your computer and use it in GitHub Desktop.
Save hovissimo/5c97d1938070d8f678eb20df78e09cdd to your computer and use it in GitHub Desktop.
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
}
const loggedEndpoint = (handler) => async (req) => {
console.group(
`${new Date().toISOString()} ${req.method} ${req.path}`
)
const result = await handler(req)
console.groupEnd()
return result
}
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