如何在Vue + Firebase应用中实现邮箱验证及登录权限校验
Firebase邮箱验证功能实现方案
1. 注册模块修改(实现自动发验证邮件+跳转登录页)
原代码调用sendEmailVerification时未传入自定义配置,因此无法指定验证后的跳转地址,修改后的完整signup composable代码如下:
import { ref } from 'vue' import { projectAuth } from '../firebase/config' const error = ref(null) const isPending = ref(false) const signup = async (email, password, displayName) => { error.value = null isPending.value = true try { const res = await projectAuth.createUserWithEmailAndPassword(email, password) if (!res) { throw new Error('Could not complete signup') } await res.user.updateProfile({ displayName }) // 新增验证邮件跳转配置 const actionCodeSettings = { // 验证通过后跳转的目标地址 url: 'http://localhost:8080/login', handleCodeInApp: false } await res.user.sendEmailVerification(actionCodeSettings); error.value = null isPending.value = false return res } catch(err) { console.log(err.message) error.value = err.message isPending.value = false } } const useSignup = () => { return { error, signup, isPending } } export default useSignup
注意:本地测试前需要先进入Firebase控制台→Authentication→设置→授权域名,将localhost添加到授权列表中,否则验证链接会被Firebase拦截。
2. 登录模块修改(仅允许已验证邮箱的用户登录)
原登录逻辑仅校验账号密码正确性,未判断邮箱验证状态,新增emailVerified字段校验即可,修改后的完整login composable代码如下:
import { ref } from 'vue' import { projectAuth } from '../firebase/config' const error = ref(null) const isPending = ref(false) const login = async (email, password) => { error.value = null isPending.value = true try { const res = await projectAuth.signInWithEmailAndPassword(email, password) // 新增邮箱验证状态校验 if (!res.user.emailVerified) { // 未验证的用户直接登出,清除登录态 await projectAuth.signOut() throw new Error('请先前往邮箱完成验证后再登录') } error.value = null isPending.value = false return res } catch(err) { console.log(err.message) error.value = err.message === 'Incorrect login credentials' ? '登录账号或密码错误' : err.message isPending.value = false } } const useLogin = () => { return { error, login ,isPending} } export default useLogin
其他可选优化点
- 注册成功后给用户弹出提示,告知已发送验证邮件,引导用户去邮箱操作
- 生产环境上线时,将
actionCodeSettings中的url替换为线上环境的登录页地址 - 可新增重发验证邮件的功能,避免用户收不到邮件的情况
内容的提问来源于stack exchange,提问作者Bilal Hussain
相关产品推荐
相关产品推荐

