Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
northkode opened this issue Mar 8, 2020 · 5 comments
Open

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

northkode opened this issue Mar 8, 2020 · 5 comments

Comments

@northkode
Copy link

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?

@alshdavid
Copy link
Owner

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()

@northkode
Copy link
Author

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

@northkode
Copy link
Author

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

@alshdavid
Copy link
Owner

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
Copy link
Owner

Here's a sandbox with it using promises

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants