问题
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