实现身份验证是您在大多数项目中都会做的事情,但由于您实际执行此操作的频率,您可能仍然不记得如何执行此操作。
以下是有关使用 nuxt v3 实施 supabase auth 的快速方法。在此示例中,我们将使用 otp,但它适用于所有情况。
您首先要访问 supabase 的网站来开始您的项目。
在 supabase 中创建项目并在 nuxt 上启动项目后,我们希望通过执行以下操作来安装 supabase nuxt 包:
npx nuxi@最新模块添加supabase
然后我们将创建 .env 文件并添加以下环境变量:
supabase_url=supabase_key=
登录后复制
您可以在项目的 supabase 仪表板上的“设置 -> api”下找到这些
之后,我们就可以设置我们的项目了。到目前为止我已经制作了 2 个非常基本的文件:
auth.ts(我使用了 pinia 商店,但随意使用常规文件)
import { definestore } from "pinia";export const useauthstore = definestore("auth", () => { const supabase = usesupabaseclient(); const sendotp = async (email: string) => { const { error } = await supabase.auth.signinwithotp({ email, }); if (error) { throw error; } return true; }; const verifyotp = async (email: string, otp: string) => { const { error } = await supabase.auth.verifyotp({ type: "email", token: otp, email, }); if (error) { throw error; } return true; }; return { sendotp, verifyotp, };});
登录后复制loginform.vue
import { ref, computed } from "vue";import { useauthstore } from "~/stores/auth";const authstore = useauthstore();const email = ref("");const otpcode = ref("");const mode = ref("email");const buttonlabel = computed(() => { return mode.value === "email" ? "send one-time password" : "verify code";});const handlesubmit = async () => { if (mode.value === "email") { try { await authstore.sendotp(email.value); mode.value = "code"; } catch (error) { console.log("error sending otp: ", error); } } else { try { await authstore.verifyotp(email.value, otpcode.value); } catch (error) { console.log("error verifying otp: ", error); } }};welcome
enter the 6-digit code sent to {{ email }}
登录后复制
请注意,我也使用 nuxtui,以防出现任何错误。
因为默认情况下,signinwithotp 函数会发送一个魔术链接,因此您必须更改 supabase 仪表板上的电子邮件模板才能发送令牌:
这可以在身份验证 -> 电子邮件模板 -> 更改确认注册和 magic link 模板下找到以使用 {{ .token }}
差不多就这些了,您已经拥有工作授权了!
如果你想添加注销,你还可以在之前的文件中添加一个方法,如下所示:
const signout = async () => { const { error } = await supabase.auth.signout(); if (error) { throw error; } return true;};
登录后复制
但是,如果您想保护某些路由,我们也可以添加中间件。
在根目录上创建一个名为 middleware 的文件夹(名称是 key)和一个名为 auth.ts 的文件。
然后您可以添加如下内容:
export default definenuxtroutemiddleware((to) => { const user = usesupabaseuser(); const protectedroutes = ["/app"]; if (!user.value && protectedroutes.includes(to.path)) { return navigateto("/auth"); } if (user.value && to.path === "/auth") { return navigateto("/"); }});
登录后复制
这基本上可以保护您的 /app 路由免受服务器的影响,因此,如果您尝试在未登录的情况下访问 /app,您将被重定向到 /auth。
同样,如果您在已登录的情况下尝试访问 /auth,您将被重定向到主页 /。
现在,要使用它,您可以将其放置在任何组件的 标签内,如下所示:
definePageMeta({ middleware: "auth", // this is the name of the file, minus the extension});
登录后复制
就是这样,就这么简单!
以上就是使用 Nuxt v3 设置 Supabase Auth的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2664283.html