js 驗證護照
In my last article (Passport local strategy section 1 | Node.js), we started the implementation of the passport-local authentication strategy. We also looked at the various requirements to get started with the login form. In this article, we will continue with setting up passport and MongoDB database.
在我的上一篇文章( Passport本地策略第1節| Node.js )中,我們開始了護照本地身份驗證策略的實現。 我們還研究了登錄表單入門的各種要求。 在本文中,我們將繼續設置passport和MongoDB數據庫 。
These codes are just to help you get started. So you can edit them.!
這些代碼僅是為了幫助您入門。 因此您可以編輯它們。
護照設置 (Passport setup)
In the app.js file, add the following code at the bottom
在app.js文件中,在底部添加以下代碼
/* PASSPORT SETUP */
const passport = require('passport');
app.use(passport.initialize());
app.use(passport.session());
app.get('/success', (req, res) => res.send("Welcome "+req.query.username+"!!"));
app.get('/error', (req, res) => res.send("error logging in"));
passport.serializeUser(function(user, cb) {
cb(null, user.id);
});
passport.deserializeUser(function(id, cb) {
User.findById(id, function(err, user) {
cb(err, user);
});
});
The code above requires the passport module and creates 2 additional routes which handles successful login and when there's an error.
上面的代碼需要通行證模塊,并創建2條附加路由來處理成功登錄和出現錯誤時的情況。
貓鼬的設置 (Mongoose setup )
Before setting up mongoose, first of all, create a database with name MyDatabase with collection userInfo and add some few records as shown below:
在設置貓鼬之前,首先,創建一個名稱為MyDatabase且具有集合userInfo的數據庫,并添加一些記錄,如下所示:
Mongoose is what helps our node application to connect with our MongoDB database. It makes use of schema and models.
Mongoose是幫助我們的節點應用程序連接到MongoDB數據庫的工具。 它利用模式和模型。
Schema helps us define our data structure and is later used to create our model as you'll see later in the code.
Schema幫助我們定義數據結構,以后將用于創建我們的模型,如稍后在代碼中所見。
First of all install mongoose by running the following command in a terminal:
首先,通過在終端中運行以下命令來安裝貓鼬:

In the app.js file, add the following code at the bottom
在app.js文件中,在底部添加以下代碼
/* MONGOOSE SETUP */
// schema
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/MyDatabase', { useNewUrlParser: true } );
const Schema = mongoose.Schema;
const UserDetail = new Schema({
username: String,
password: String
});
// model
const UserDetails = mongoose.model('userInfo', UserDetail, 'userInfo');
That's all for this second section. In the last section, we are going to set up our passport-local authentication strategy since we are working on a form and finally test our work.
這是第二部分的全部內容。 在上一節中,由于我們正在處理表單并最終測試我們的工作,因此我們將建立我們的護照本地身份驗證策略。
Thanks for coding with me! See you @ the next article. Feel free to drop a comment or question.
感謝您與我編碼! 下次見。 隨意發表評論或問題。
翻譯自: https://www.includehelp.com/node-js/passport-local-strategy-section-2-node-js.aspx
js 驗證護照