alloc/saus

Authorized routes

Opened this issue · 2 comments

⚠️ The example in this OP is outdated. See #56 (comment)


Add an authorizeRoutes route hook, used like so:

// ./src/node/routes.ts
import { authorizeRoutes, Redirect } from 'saus'

// The route pattern is optional. If none is provided, all routes are authenticated.
authorizeRoutes('*', async (headers, url) => {
  if (verify(headers)) {
    return true
  }
  // Redirect the request, or return false to act like this route doesn't exist.
  return new Redirect('/login')
})

const verify = (headers) => {
  // TODO: verify a Cookie header or JWT token, etc
}

This can be implemented with an onRequest hook once it supports a route argument.

import { onRequest } from 'saus'

onRequest('/admin/*', async req => {
  return (await verifyAdmin(req))
    ? undefined
    : [307, { Location: '/login' }]
})

We could add a notAuthorized helper function:

import { onRequest, notAuthorized } from 'saus'

onRequest('/admin/*', async req => {
  return (await verifyAdmin(req))
    ? undefined
    : notAuthorized(req, '/login')
})

It would respond with 307 temporary redirect if Accept: text/html header exists.
Otherwise, it would respond with 403 forbidden.