在 Node.js 中解釋 Passport?


Passport 是一個 Node 包或庫,我們可以將其安裝到任何 Node.js 專案中。Passport 提供了應用程式身份驗證的功能。此外,它還提供不同的加密策略來加密使用者資訊,例如密碼。

例如,如果 Facebook 或 Google 的員工能夠看到其使用者的密碼會怎樣?這違反了使用者隱私。因此,在這種情況下,我們可以使用 Passport,它會加密密碼並將其儲存在資料庫中。我們需要知道解密演算法和金鑰才能解密密碼。

此外,Passport 允許我們為使用者建立身份驗證會話。假設您每次關閉瀏覽器時都必須重新登入。這很耗時。不是嗎?因此,Passport 允許我們透過在瀏覽器中儲存 Cookie 來為特定時間建立會話。在開發人員設定的特定會話時間內,使用者每次訪問網頁時都不需要登入。

在這裡,我們將建立一個基本的身份驗證應用程式並學習如何在 Node.js 中使用 Passport。

建立應用程式的步驟

步驟 1 - 建立您想要開始新 Node.js 專案的資料夾。

步驟 2 - 輸入以下命令以啟動一個新的 Node 專案。它將在專案資料夾內建立一個名為 package.json 的檔案。

npm init -y

步驟 3 - 使用者必須為其 Node 專案安裝所需的外掛。開啟終端,轉到專案目錄,並輸入以下命令以安裝所有 NPM 包。

npm install express body-parser mongoose passport passport-local 
passport-local-mongoose express-session

在上面的命令中,express 是 Node.js 的 Web 框架。它允許使用者用更少的程式碼行建立 Node.js 應用程式伺服器。

body-parser 用於從使用者那裡獲取表單輸入資料。Mongoose 允許我們使用 MongoDB 資料庫。

Passport NPM 包用於在我們的應用程式中使用 Passport。Passport-local 包含大約 450 多種加密資料的策略。Passport-local-mongoose 將 MongoDB 與 Passport 和 express-session 結合使用,以使用 Passport 和 express 維持登入會話。

步驟 4 - 現在,讓我們建立一個表單來註冊使用者。在專案目錄中建立 register.html 檔案並貼上以下程式碼。

示例

<html>
<body>
   <h2>
      Enter email and password values, and press submit button for registration
   </h2>
   <!-- Make the post request on the /register route with email and password data -->
   <form action = "/register" method = "post">
      <input type = "email" name = "username" />
      <br />
      <input type = "password" name = "password" />
      <br />
      <button type = "submit" name = "button"> Submit </button>
   </form>
   </body>
</html>

在上面的程式碼中,我們建立了一個表單,使用 HTML 表單獲取使用者的電子郵件和密碼。我們為電子郵件和密碼建立了兩個不同的輸入欄位。此外,我們建立了提交按鈕,當用戶按下它時,應用程式將在“/register 路由上發出 POST 請求。

步驟 5 - 現在,讓我們為登入頁面建立程式碼。在專案目錄中建立 login.html 檔案並貼上以下程式碼。

示例

<html>
<body>
   <h2> Enter the credentials to log in to the app</h2>
   <!-- When the user presses the submit button, it makes a post request on the login route -->
   <form action = "/login" method = "post">
      <input type = "email" name = "username" />
      <br />
      <input type = "password" name = "password" />
      <br />
      <button type = "submit" name = "button"> Submit </button>
   </form>
   </body>
</html>

上面的程式碼與我們在 register.html 中編寫的程式碼幾乎相同,但不同之處在於,當用戶按下提交按鈕時,它會在“/login”路由上發出 POST 請求。

步驟 6 - 現在,我們將開始建立我們的伺服器。我們將匯入所需的模組並使用 Passport 初始化我們的應用程式。

// Importing the required and installed modules
var express = require("express");
var app = express();
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const session = require("express-session");
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");

// permitting the app to use body-parser without any error
app.use(bodyParser.urlencoded({ extended: true }));
app.use(
   session({
      secret: "This is the secret key to encrypt the password and user data.",
      resave: false,
      saveUninitialized: false,
   })
);

// initialize our app with passport and establish a session
app.use(passport.initialize());
app.use(passport.session());

我們在上面的程式碼中匯入了模組並使用 Passport 初始化了我們的應用程式。此外,我們還使用 Passport 建立了會話。

步驟 7 - 我們需要將 MongoDB 資料庫連線到我們的應用程式。

mongoose
.connect(
   "mongodb+srv://shubhamvora05:Stockdata@stockdata.lrlgm.mongodb.net/StockList?retryWrites=true&w=majority",
   { useNewUrlParser: true, useUnifiedTopology: true }
)
.then(() => {
   console.log("Connected to database successfully");
})
.catch((err) => {
   console.log("Error connecting to MongoDB database", err.message);
});

// creating the user schema containing the email_Adress and password field
const user = new mongoose.Schema({
   email_Address: String,
   password: String,
});

// code to use the Mongoose schema named user with passport
user.plugin(passportLocalMongoose);

// Creating the new model using the schema
const userModel = new mongoose.model("User", user);

// create the strategy to encrypt the data
passport.use(userModel.createStrategy());
passport.serializeUser(userModel.serializeUser());
passport.deserializeUser(userModel.deserializeUser());

我們首先在上面的程式碼中將我們的應用程式連線到 MongoDB 叢集。之後,我們建立了一個名為 user 的 MongoDB 模式來儲存使用者的身份驗證資料。接下來,我們將使用者模式與 passportLocalMongoose NPM 包外掛化。此外,我們在上面的程式碼中使用了序列化器和反序列化器。

步驟 8 - 我們需要處理來自主頁和登入路由的 GET 請求。

app.get("/", function (req, res) {
   if (req.isAuthenticated()) {
      res.send("Authenticated successfully");
   } else {
      res.sendFile(__dirname + "/register.html");
   }
});
app.get("/login", function (req, res) {
   if (req.isAuthenticated()) {
      res.send("Authenticated successfully");
   } else {
      res.sendFile(__dirname + "/login.html");
   }
});

在上面的程式碼中,isAuthenticated() 是一箇中間件函式,它檢查使用者是否已登入併發送布林值。

步驟 9 - 我們必須處理“/register”路由上的 POST 請求。

app.post("/register", function (req, res) {
   userModel.register(
      { username: req.body.username },
      req.body.password,
      function (err, user) {
         if (!err) {
            passport.authenticate("local")(req, res, function () {
               res.send("User registered successfully with email!");
            });
         }
      }
   );
});

在上面的程式碼中,我們使用 passport.authenticate() 方法加密密碼並將其儲存在資料庫中。

步驟 10 - 接下來,我們需要處理“/login”路由上的 POST 請求。

app.post("/login", function (req, res) {
   req.login(
      {
         username: req.body.username,
         password: req.body.password,
      },
      function (err) {
         if (!err) {
            passport.authenticate("local")(req, res, function () {
               userModel.find(
                  { email_Address: req.user.username },
                  (err) => {
                     if (!err) {
                        res.send("User login successful! Enjoy Now!");
                     }
                  }
               );
            });
         }
      }
   );
});

在上面的程式碼中,我們從使用者那裡獲取登入憑據。我們從資料庫中查詢使用者並使用 Passport 對其進行身份驗證。在沒有錯誤的情況下進行身份驗證後,我們傳送一條類似“使用者登入成功!”的訊息。

步驟 11 - 建立 server.js 檔案並貼上以下程式碼。

// Importing the required and installed modules
var express = require("express");
var app = express();
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const session = require("express-session");
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");

// give permission to the app to use body-parser without any error
app.use(bodyParser.urlencoded({ extended: true }));
app.use(
session({
   secret: "This is the secrect key to encrypt the password and user data.",
   resave: false,
   saveUninitialized: false,
   })
);

// initialize our app with passport and establish a session
app.use(passport.initialize());
app.use(passport.session());

// Connecting MongoDB cluster to our app using the mongoose NPM package
mongoose
.connect(
   "mongodb+srv://shubhamvora05:Stockdata@stockdata.lrlgm.mongodb.net/StockList?retryWrites=true&w=majority",
   { useNewUrlParser: true, useUnifiedTopology: true }
)
.then(() => {
   console.log("Connected to database successfully");
})
.catch((err) => {
   console.log("Error connecting to MongoDB database", err.message);
});

// creating the user schema containing the email_Adress and password field
const user = new mongoose.Schema({
   email_Address: String,
   password: String,
});

// code to use the Mongoose schema named user with passport
user.plugin(passportLocalMongoose);

// Creating the new model using the schema
const userModel = new mongoose.model("User", user);

// create the stratagy to encry the data
passport.use(userModel.createStrategy());
passport.serializeUser(userModel.serializeUser());
passport.deserializeUser(userModel.deserializeUser());

// handling the get request
// if user is authenticated then send response message "Authenticated successfullly"
// Othewise redirect user to register page.
app.get("/", function (req, res) {
   if (req.isAuthenticated()) {
      res.send("Authenticated successfully");
   } else {
      res.sendFile(__dirname + "/register.html");
   }
});

// Same like the register route,
// If user is authenticated then send response, othewise redirect to login route
app.get("/login", function (req, res) {
   if (req.isAuthenticated()) {
      res.send("Authenticated successfully");
   } else {
      res.sendFile(__dirname + "/login.html");
   }
});

/* Registering the user for the first time
handling the post request on /register route.*/
app.post("/register", function (req, res) {
   userModel.register(
      { username: req.body.username },
      req.body.password,
      function (err, user) {
         // registering using the passport
         if (!err) {
            passport.authenticate("local")(req, res, function () {
               res.send("User registered successfully with email!");
            });
         }
      }
   );
});

// Handling the post request on /login route
app.post("/login", function (req, res) {

   // requesting the login using passport
   req.login(
      {
         username: req.body.username,
         password: req.body.password,
      },
      function (err) {
         if (!err) {

            // authenticating using passport
            passport.authenticate("local")(req, res, function () {
               userModel.find(
                  { email_Address: req.user.username },
                  function (err, docs) {
                     if (!err) {
                        res.send("User login successful! Enjoy Now!");
                     }
                  }
               );
            });
         }
      }
   );
});

// Allowing the app to listen on port 3000
app.listen(3000, function () {
   console.log("server started successfully");
});

步驟 12 - 作為最後一步,我們需要執行我們的應用程式。要執行應用程式,請在終端中輸入以下命令。

node server.js

更新於:2022-12-29

2K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.