使用Node.js和Firebase进行电子邮件认证和验证
电子邮件验证是一种机制,以确保系统不会在其数据库中堆积虚假的电子邮件地址。在用户通过发给他/她的电子邮件地址的独特链接进行验证之前,一个账户一直是未验证的。
在此期间,系统会限制该账户使用应用程序的核心功能。
目标
在本文结束时,你将了解电子邮件验证的逻辑。我们将通过使用Node.js、Firebase和Express建立一个登录和注册系统的样本来逐步实现这个逻辑。
前提条件
为了有效地跟随我学习本篇文章。
- 你将需要在你的电脑上安装[Node.js]。
- 对Node.js有一个基本的了解。
- 一个合适的代码编辑器。我将使用[Visual Studio Code]。
项目设置
我们将像其他Node.js 项目一样设置该项目。执行下面的命令就可以开始了。
npm init -y
接下来,我们将安装所需的依赖项。我们需要
express作为我们的后台,body-parser来处理HTTP请求,ejs来渲染我们的HTML文件,以及nodemon来在我们开发应用程序时不断地更新变化。
执行下面的命令来安装这些依赖项。
npm install --save express, body-parser, ejs, nodemon
接下来,我们将为该项目创建所有的文件和目录。
项目的结构应该如下所示。
┣ node-modules
┣ static
┣ views
┃ ┣ login.html
┃ ┣ profile.html
┃ ┗ signup.html
┣ index.js
┣ package-lock.json
┣ package.json
建立服务器
index.js 文件是应用程序的入口点。它也将作为项目的服务器文件。
导入依赖项
为了引入依赖性,请将下面的片段添加到你的index.js 文件中。
//Express
const express = require('express');
//body-parser
const bodyParser = require('body-parser');
//ejs
const ejs = require('ejs');
//using express
const app = express();
//using bodyparser
app.use(bodyParser.json())
app.engine("html", require("ejs").renderFile);
app.use(express.static("static"));
创建应用程序的路由
我们为这个项目需要三个路由。
- 默认路由是
signup,用户在这里注册并自动登录他们的账户。
//sign up route
app.get("/signup", function (req, res) {
res.render("signup.html");
});
- 下一个路由是
login,它将用户带到登录页面。在登录页面,用户使用注册时提供的电子邮件和密码登录他们的账户。
//login route
app.get("/login", function (req, res) {
res.render("login.html");
});
- 最后一条路线是
profile,它把用户带到他的个人资料页面,在那里用户可以看到他的账户状态并要求一个验证链接。
//user profile route
app.get("/profile", function (req, res) {
res.render("profile.html");
});
用户界面
在views 文件夹中,创建三个HTML文件,分别命名为login.html,signup.html, 和profile.html 。
注册页面的用户界面
这里是用户使用电子邮件和密码创建一个账户的地方。

登录页面的用户界面
在这个页面上,用户输入注册时设置的电子邮件和密码。

档案页用户界面
在用户资料页面,用户可以申请账户验证,并查看其账户的验证状态。

将Firebase添加到应用程序中
在下一阶段,我们将接触到应用程序的核心功能。为了使用Firebase,我们需要获得Firebase的授权,以便知道谁在访问Firebase的功能。我们需要生成一个config 对象来与应用程序一起使用。
你最终的Firebaseconfig 对象应该是这样的。
var config = {
apiKey: "YOUR API KEY",
authDomain: "YOUR AUTH DOMAIN",
databaseURL: "YOUR DATABASE URL",
projectId: "YOUR PROJECT ID",
storageBucket: "STORAGE BUCKET",
messagingSenderId: "MESSAGE SENDER ID",
appId: "YOUR APPLICATION ID"
};
创建账户函数
这个函数调用Firebase auth来创建一个新的账户,并提供电子邮件和密码。在账户创建成功后,该函数会自动将用户登录到他们的账户中,并将他们重定向到个人资料页面。
// initialize firebase
firebase.initializeApp(config);
function createAccount(){
// obtain user email and user password from HTML
var userEmail = document.getElementById("email_field").value;
var userPass = document.getElementById("password_field").value;
firebase.auth().createUserWithEmailAndPassword(userEmail, userPass).catch((error) =>{
//error code
var errorCode = error.code
//error message
var errorMessage = error.message
}).then(() => {
//redirect the user to profile page
window.location.assign("/profile");
});
}
登录功能
登录函数接收用户的电子邮件和密码,然后调用Firebase来验证用户的身份。如果用户不存在或者密码错误,它将返回一个错误。在登录页面的script 标签中添加下面的片段。
// initialize firebase
firebase.initializeApp(config);
function login() {
// obtain user email and user password from HTML
var userEmail = document.getElementById("email_field").value;
var userPass = document.getElementById("password_field").value;
firebase.auth().signInWithEmailAndPassword(userEmail, userPass).catch(function(error) {
//error code
var errorCode = error.code
//errod message
var errorMessage = error.message
//show error message
window.alert("Error : " + errorMessage);
}).then(() => {
//redirect the user to profile page
window.location.assign("/profile");
});
}
发送电子邮件验证链接
这个函数负责从数据库中提取用户的电子邮件,并向创建账户时使用的电子邮件发送一个独特的链接。在验证之前,账户的验证状态为false ,意味着账户没有被验证。
//initialize firebase
firebase.initializeApp(config);
const user = firebase.auth().currentUser;
// send verification email
function sendVerificationEmail() {
// extracting the user from the firebase
var user = firebase.auth().currentUser;
user.sendEmailVerification().then(function() {
window.alert("Verification link sent to your email. Kinldy check to verify your account")
}).catch(function(error) {
// An error happened.
});
}
在该功能成功执行后,一个链接被发送到注册时提供的电子邮件,如下图所示。

点击该链接后,用户会被转到一个新的页面。
该页面显示验证过程的状态,如下图。

检查验证状态
一旦用户通过点击发给他们的电子邮件的链接成功地验证了一个账户,我们需要更新个人资料页面中的验证状态。
在用户资料页面中添加以下代码,以检查验证状态并呈现在资料页面上。
firebase.initializeApp(config);
firebase.auth().onAuthStateChanged(
function(user) {
if(user){
var emailVerified = user.emailVerified;
var email = user.email;
var data = '<h4> Hello, ' + email + '</h4>' +
'<h4>Account verified: ' + emailVerified + '</h1>';
document.getElementById("wrapper").innerHTML = data
if(emailVerified == true){
document.getElementById("verify").style.display = "none"
}
} else {
console.log("No user found")
}
}
);
当用户回到他们的账户时,账户的验证状态变为true ,verify 按钮也消失了。

启动服务器
在这个阶段,我们将通过在终端运行命令nodemon start 来测试我们的应用程序。
我们需要在index.js 文件中添加以下代码。
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Listening on http://localhost:${PORT}`);
});
总结
在本教程中,我们学习了如何使用Firebase进行电子邮件认证和验证。通过本教程,我们可以体会到这一功能在确保用户在访问给定系统的资源之前是多么有用。