alshdavid / crayon-router

Simple framework agnostic UI router for SPAs
MIT License
327 stars 13 forks source link

Route called even when middleware use redirection #43

Closed snickers54 closed 5 years ago

snickers54 commented 5 years ago

Describe the bug Routes are still mounted even with a middleware that should prevent access to them (via a simple redirect). The redirection works well, but it shouldn't even access the component before the redirection is done.

To Reproduce Steps to reproduce the behavior:

  1. Create a simple protected route with a console.log inside. Let's say /user
  2. Use a custom middleware that simply redirect to another route. Let's say /
  3. Access /user, you will see your console.log inside your protected route display in console.

Expected behavior The route shouldn't mount or execute anything since there is a middleware and it purpose is to perform actions before accessing the actual path.

Desktop (please complete the following information):

Additional context main.js:

import App from './App';
import crayon, { group } from 'crayon';
import svelte from 'crayon-svelte';
import Editor from './components/editor/Editor';
import Login from './components/auth/Login';

const app = crayon.create();
app.use(svelte.router());
const auth = group('/auth', group => {
    group.path('/login', async (req, res) => {
        await res.mount(App, {req, nav: app, component: Login});
    });
});

const secured = group('/bot');
secured.use((_, res) => {
    const session = localStorage.getItem('session');
    if (!session) {
        res.redirect('/auth/login');
    }
});
secured.path('/editor', async (req, res) => {
    await res.mount(App, {req, nav: app, component: Editor});
});
app.use(secured);
app.use(auth);
app.load();

App.svelte:

<script>
    export let component;
    export let req;
    export let nav;
</script>

<div>
     <svelte:component this={component} nav={nav} req={req}/>
</div>

Editor.svelte:

<script>
console.log("should not display");
</script>

Login.svelte:

<div>login page</div>
aigr commented 5 years ago

+1

alshdavid commented 5 years ago

Thanks for noticing this, have put together this PR to address it.

I have included two test cases to cover your this behaviour.

Will be available from crayon version 4.1.6 Feel free to reopen this issue if the problem persists