supabase -如何防止未登录的用户看到我们的应用程序页面



我开始使用supabase作为firebase的替代品。我正在为我的vue webapp实现一个简单的身份验证系统,我对重定向有疑问。我已经使用了神奇的链接解决方案,让用户登录https://supabase.com/docs/guides/auth/auth-magic-link,但我不知道如何正确设置在我的本地主机在开发过程中登录后的重定向,我可以阻止用户看到一个视图,如果他们没有登录。

我已经实现了pinia和vue路由器,目前这是我在我的主页上让用户登录的代码

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

在模板中我有一个简单的电子邮件输入字段

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

在我的路由器中我有这个代码

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

如果用户没有登录,我如何正确设置vue路由器来防止导航,以及如何正确设置重定向的supabase ?

摘自: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

相关内容

  • 没有找到相关文章