pico-router icon indicating copy to clipboard operation
pico-router copied to clipboard

Is there an example or setup for using a route guard?

Open northkode opened this issue 4 years ago • 5 comments

Is route guard middle ware doable?

is there docs for how to write a middleware controller to all me to preload route data or check for auth etc?

northkode avatar Mar 08 '20 01:03 northkode

Due to the large variation of authentication methods, it's difficult to provide a generalised solution. For example you could write an entire middleware dedicated to the OAuth2 OpenID Connect flow, which would act as a guard.

As a simple example which doesn't use a framework, it would look something like this:

import crayon from 'crayon'

const router = crayon.create()
const password = 'foobar'
let isAuth = false

router.use(ctx => {
   if (isAuth === false) {
      ctx.redirect('/login')
   }
})

router.path('/', ctx => {
   document.body.innerHTML = 'Hello!'
})

router.path('/login', ctx => {
   const result = prompt('whats your password?')
   if (result === password) {
      isAuth = true
      ctx.redirect('/')
   }
   document.body.innerHTML = 'Incorrect Password'
})

router.load()

alshdavid avatar Mar 08 '20 03:03 alshdavid

Thanks for this. This was helpful. Even this simple example in the docs is valuable. 👍

northkode avatar Mar 08 '20 05:03 northkode

Does this library support promise returns in the path routers so I can resolve server data before route loads?

northkode avatar Mar 08 '20 06:03 northkode

Yes, if you return a promise in a middleware/handler, the router will wait for the promise to resolve before moving onto the next handler in the chain

alshdavid avatar Mar 08 '20 07:03 alshdavid

Here's a sandbox with it using promises

https://codesandbox.io/s/keen-carson-hmrgh

alshdavid avatar Mar 08 '20 12:03 alshdavid