Protect Vue application pages from access by non-logged-in users
P粉598140294
2023-09-01 11:46:55
<p>I started using supabase as an alternative to firebase. I'm implementing a simple authentication system for my vue webapp and I have a problem with redirects.
I used the magic link solution to log users in to https://supabase.com/docs/guides/auth/auth-magic-link but I'm not sure how to properly set up the login redirect on localhost during development as well How to prevent non-logged-in users from viewing a view. </p>
<p>I have implemented pinia and vue router. In the current homepage, this is the code I use to let users log in: </p>
<pre class="brush:js;toolbar:false;">import { supabase } from '../supabase/supabase'
export default {
name: 'HomeView',
data() {
return {
userEmail: null
}
},
created() {
},
mounted() {
//this.initGoogleAuth()
},
methods: {
initMagicLinkAuth() {
supabase.auth.signInWithOtp({
email: this.userEmail,
options: {
emailRedirectTo: '/about'
}
})
}
}
}
</pre>
<p>In the template I have a simple email input field: </p>
<pre class="brush:html;toolbar:false;"><input type="email" class="form-control" placeholder="Email" v-model="userEmail">
<div class="d-grid gap-2">
<button class="btn btn-primary" @click.prevent="initMagicLinkAuth()">Login</button>
</div>
</pre>
<p>In my router I have the following code: </p>
<pre class="brush:js;toolbar:false;">import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'home',
component:HomeView
},
{
path: '/about',
name: 'about',
component: () => import('../views/AboutView.vue')
}
]
})
export default router
</pre>
<p>How to correctly set up vue router to prevent non-logged in users from navigating, and how to correctly set up supabase for redirection? </p>
Taken from: https://blog.logrocket.com/ultimate-guide-authentication-vue-js-supabase/