Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sapper - protected routes (route guard)

My question is very simple. How do you prevent, e.g. non authorized user, to enter specific routes in sapper?

user.svelte

<script>
    import { onMount } from 'svelte';

    onMount(() => {
      if(!authenticated)
        window.history.back()
      });
</script>

Is there any option to run some code before mounting to the DOM?

How do you solve this kind of problem?

Thank you.

like image 437
Raold Avatar asked Sep 29 '19 07:09

Raold


1 Answers

I can't say it's the right thing. It's what I do in my SPAs. If I want to protect all routes of my app. I create following in _layout.svelte top file.

<script context="module">

    import {ax} from './_parts/Helper.svelte'
    import {admin, adminName} from './store'
    import {goto} from '@sapper/app'

    export async function preload(page) {
        try {
            const {data} = await ax.get('/admin/is-logged-in')
            adminName.set(data)
            admin.set(true)
        } catch (e) {
            admin.set(false)
        }
    }
</script>

<script>
    import Login from './admin/login.svelte'
    import {loading} from './store.js'
</script>

<main>
{#if $admin}
     <slot></slot>
{:else}
     <Login />
{/if}
</main>

ax is nothing magic. It's just configured axios. '/admin/is-logged-in' is where you check session at backend.

like image 106
Yousuf Iqbal Hashim Avatar answered Sep 20 '22 10:09

Yousuf Iqbal Hashim