saus icon indicating copy to clipboard operation
saus copied to clipboard

Authorized routes

Open aleclarson opened this issue 3 years ago • 2 comments

⚠️ The example in this OP is outdated. See https://github.com/alloc/saus/issues/56#issuecomment-1143963756


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
}

aleclarson avatar Mar 30 '22 19:03 aleclarson

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' }]
})

aleclarson avatar Jun 01 '22 18:06 aleclarson

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.

aleclarson avatar Jun 01 '22 18:06 aleclarson