开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第32天,点击查看活动详情
前言
Supabase 是一个自称的 "开源 Firebase 替代品"。我对与 Supbase 合作已经有一段时间了,我想我将尝试使用他们的认证 API 来为 Vue.js 3 应用程序进行认证设置。
首先,你为什么要使用 Supabase Auth?最重要的是,如果你使用 Supabase 作为你的数据存储,Supabase Auth 是你可以管理对这些数据的访问的唯一方法。其次,虽然 Supabase Auth 也有许多不同的功能。
- 没有中间件的用户权限(通过 Postgres 的行级安全)。
- 神奇的电子邮件链接
- 社交提供者的登录
- 以及所有其他你期望的封装在一个简单的 JavaScript SDK 中的 Auth 功能
综上所述,值得一提的是,Supabase Auth 不是一个独立的认证提供商,它只是为了与其他 Supabase 服务(数据、存储等)一起使用。 好了,让我们开始在我们的 Vue.js 3 应用程序中实施 Supabase Auth。
安装 Supabase
我假设你已经有了一个用 Vue Router 设置的 Vue.js 3 应用程序,如果没有,你可以下载这个模板代码来进行操作。我还假设你已经有了一个 Supabase 账户和项目设置。如果没有,你可以前往 supabase.io,它将引导你完成第一步。
然后,为了与 Supabase auth 以及它的任何其他服务合作,我们需要安装 Supabase JavaScript SDK。
npm install @supabase/supabase-js
设置 Supabase
安装完 Supabase 后,我们需要经过几个步骤来设置它。我将创建一个名为 UseSupabase.js 的组合,用来组织这个设置。
// UseSupabase.js
import { createClient } from "@supabase/supabase-js";
// these can come from an environment variable if desired
// not required however as they are 100% exposed on the client side anyway
// and that's ok, Supabase expects this (security is provided by Row Level Security)
const supabaseUrl = "";
const supabaseKey = "";
// setup client
const supabase = createClient(supabaseUrl, supabaseKey);
// expose supabase client
export default function useSupabase() {
return { supabase };
}
supabaseUrl 和 supabaseKey 可以在 Supabase 仪表板上的 Settings > API。
当你在 Supabase 界面时,你也可以到 Autentication > Settings ,设置你的网站网址,以便 Supabase 知道如何正确地重定向确认邮件等。它的默认值是 localhost:3000,但你可以根据需要进行修改。
创建一个 AuthUser 组合
设置好 Supabase SDK 后,我们现在可以开始使用它了。首先,我将创建一个 AuthUser 组合,以抽象出与 AuthUser 的一些交互,并存留所有我们需要填写的方法。这在我们将来想脱离 Supabase 时很有帮助,并帮助我们把所有的 AuthUser 功能集中到一个地方。
import { ref } from "vue";
// user is set outside of the useAuthUser function
// so that it will act as global state and always refer to a single user
const user = ref(null);
export default function useAuthUser() {
/**
* Login with email and password
*/
const login = async ({ email, password }) => {};
/**
* Login with google, github, etc
*/
const loginWithSocialProvider = (provider) => {};
/**
* Logout
*/
const logout = async () => {};
/**
* Check if the user is logged in or not
*/
const isLoggedIn = () => {};
/**
* Register
*/
const register = async ({ email, password, ...meta }) => {};
/**
* Update user email, password, or meta data
*/
const update = async (data) => {};
/**
* Send user an email to reset their password
* (ie. support "Forgot Password?")
*/
const sendPasswordRestEmail = async (email) => {};
return {
user,
login,
loginWithSocialProvider,
isLoggedIn,
logout,
register,
update,
sendPasswordRestEmail,
maybeHandleEmailConfirmation,
};
}