Sapper - protected routes (route guard)

早过忘川 提交于 2019-12-24 21:40:10

问题


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.


回答1:


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.




回答2:


I think that I had basically the same problem. I posted question (with solution) here on SO and solved it the same day with help from this issue from Sapper GitHub with my own "auth redirecting middleware".



来源:https://stackoverflow.com/questions/58153372/sapper-protected-routes-route-guard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!