2
我正在使用MEAN堆棧的登錄界面上工作。我設法使用PassportJS來運行它。我現在的問題是我需要一種方法讓我的客戶端知道登錄的用戶是管理員還是用戶(用戶角色)。這些信息可以從我的MongoDB獲得。使用Node.JS從一個函數返回值到另一個函數
我的API調用的流程如下:
app.post('/login', passport.authenticate('local'), authRoutes.loginCheck);
首先,它運行在那裏調用下面
function verifyCredentials(username, password, done) // username & password from what user provide when logging in
{
console.log('VC');
User.findOne({username: username}, function(err, user) //query Mongo
{
console.log(user); // User role is available here, in JSON format
if(user === null) // if no username in database, do this
{
console.log('Username does not exist in database');
}
else
{
user.comparePassword(password, function(err, match) // function written to compare hashed password in Mongo & password provided by user
{
if(match)
{
done(null, {id: username, name: username});
return user; // this is not the correct syntax, but the idea is, I want to send over the user details here, so I can access the role later
}
else
{
done(null, null);
}
});
}
});
}
的功能verifyFunction被調用此語法passport.authenticate。
passport.use(new LocalStrategy(verifyCredentials));
成功調用該函數後,服務器執行第二部分,它是loginCheck。
module.exports.loginCheck = function(req, res)
{
console.log('Calling loginCheck route');
// I generate some sort of jwt token here
// payload, body, blah blah blah ...
console.log(req.body);
res.json({
authenticated: req.isAuthenticated(), //built-in authentication function, returns true or false
token: token // sends over token
role: user.role // want to send over something like this
}); // sends all these to client side as JSON
}
因爲這兩個功能在不同的文件,我還不清楚,如果我有需要的東西或者只是簡單地傳遞一個額外的參數給loginCheck功能。我嘗試過後者,但沒有奏效。
我可以想到的一種方法是在loginCheck函數中執行另一個Mongo查詢,但那會有點多餘。
即使一個特定的關鍵字對我來說,谷歌一定會有很大的幫助,因爲我不知道我應該尋找什麼。原因是因爲我是NodeJS的新手,因此我不熟悉大部分術語。
我認爲這些代碼應該足夠,但如果我需要提供更多,請告訴我,我會這樣做。提前致謝 !!
我應該在哪裏放置語法通過對用戶的價值,這樣的loginCheck功能會能夠訪問它?還是因爲下一個關鍵字而已經可以訪問? – ChickenWing24
如果在路由中指定了2個函數,並且在第一個函數中調用'next'時沒有錯誤,則會將控件移動到下一個函數。 'verifyCredentials'函數的地方和誰調用這個函數? –
'passport.use(new LocalStrategy(verifyCredentials));' 上面的路由使用了verifyCredentials功能。 – ChickenWing24