搜尋

首頁  >  問答  >  主體

保護Vue應用程式頁面免受未登入使用者的訪問

<p>我開始使用supabase作為firebase的替代品。我正在為我的vue webapp實作一個簡單的身份驗證系統,我對重定向有疑問。 我使用了魔術連結解決方案來讓使用者登入https://supabase.com/docs/guides/auth/auth-magic-link,但我不確定如何在開發過程中正確設定本地主機上的登入重新導向以及如何防止未登入使用者查看視圖。 </p> <p>我已經實現了pinia和vue router,在目前的主頁中,這是我用來讓用戶登入的程式碼:</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>在範本中,我有一個簡單的電子郵件輸入欄位:</p> <pre class="brush:html;toolbar:false;"><input type="email" class="form-control" placeholder="Email" v-model="userE"gt; <div class="d-grid gap-2"> <button class="btn btn-primary" @click.prevent="initMagicLinkAuth()">Login</button> </div> </pre> <p>在我的路由器中,我有以下程式碼:</p> <pre class="brush:js;toolbar:false;">import { createRouter, createWebHistory } 從 '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>如何正確設定vue router以防止未登入使用者導航,並如何正確設定supabase以進行重定向? </p>
P粉598140294P粉598140294451 天前610

全部回覆(1)我來回復

  • P粉904450959

    P粉9044509592023-09-02 00:28:37

    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
    

    回覆
    0
  • 取消回覆