alloc / saus

Vite SSR/SSG framework that aspires to be a layer for opinionated web frameworks to build upon
Other
38 stars 1 forks source link

Authorized routes #56

Open aleclarson opened 2 years ago

aleclarson commented 2 years ago

⚠️ 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 commented 2 years ago

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 commented 2 years ago

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.