Skip to content

Instantly share code, notes, and snippets.

@kiliman
Created January 8, 2022 16:07
Show Gist options
  • Save kiliman/2f3bbfa0c7e38da1232c79b4a079f241 to your computer and use it in GitHub Desktop.
Save kiliman/2f3bbfa0c7e38da1232c79b4a079f241 to your computer and use it in GitHub Desktop.
Remix Express handler that checks for auth cookie/token and return 401 if missing on non-anonymous routes
function handleRequest(req, res, next) {
let build = require('./build')
if (MODE !== 'production') {
purgeRequireCache()
}
if (requireAuthentication(req)) {
return unauthenticated(req, res)
}
return createRequestHandler({
build,
getLoadContext,
mode: MODE,
})(req, res, next)
}
const allowAnonymous = ['/login', '/logout', '/register']
function requireAuthentication(req) {
console.log('requireAuthentication', req.originalUrl)
const url = new URL(`${req.protocol}://${req.get('host')}${req.originalUrl}`)
const token = req.cookies.auth ?? req.get('x-token')
const isAnonymous = !token
return isAnonymous && !allowAnonymous.includes(url.pathname)
}
function unauthenticated(req, res) {
const url = new URL(`${req.protocol}://${req.get('host')}${req.originalUrl}`)
if (url.pathname.startsWith('/api')) {
return res.status(401).send('Unauthenticated')
}
const returnUrl = encodeURI(`${url.pathname}${url.search}`)
return res.redirect(`/login?returnUrl=${returnUrl}`)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment