Protect Vue application pages from access by non-logged-in users
P粉598140294
P粉598140294 2023-09-01 11:46:55
0
1
548

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.

I have implemented pinia and vue router. In the current homepage, this is the code I use to let users log in:

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' } }) } } } 

In the template I have a simple email input field:

 

In my router I have the following code:

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 

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粉598140294
P粉598140294

reply all (1)
P粉904450959

Taken from:https://blog.logrocket.com/ultimate-guide-authentication-vue-js-supabase/

// router/index.js import { createRouter, createWebHistory } from 'vue-router'; function loadPage(view) { return () => import( /* webpackChunkName: "view-[request]" */ `@/views/${view}.vue` ); } const routes = [ { path: '/', name: 'Dashboard', component: loadPage("Dashboard"), meta: { requiresAuth: true, } }, { path: '/sign-up', name: 'SignUp', component: loadPage("SignUp") }, { path: '/sign-in', name: 'SignIn', component: loadPage("SignIn") }, ] const router = createRouter({ history: createWebHistory(process.env.BASE_URL), routes }) router.beforeEach((to, from, next) => { // get current user info const currentUser = supabase.auth.user(); const requiresAuth = to.matched.some (record => record.meta.requiresAuth); if(requiresAuth && !currentUser) next('sign-in'); else if(!requiresAuth && currentUser) next("/"); else next(); }) export default router
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!