使用Node.JS将值从一个函数返回到另一个函数

时间:2015-05-06 03:07:04

标签: node.js mongoose passport.js

我正在使用MEAN堆栈登录界面。我已设法使用PassportJS使其工作。我现在的问题是我需要一种方法让我的客户端知道登录的人是管理员还是用户(用户角色)。这些信息可以从我的MongoDB获得。

我的API调用流程如下:

app.post('/login', passport.authenticate('local'), authRoutes.loginCheck);

首先,它运行passport.authenticate,它调用下面的函数

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.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的新手,所以我还不熟悉大部分术语。

我认为这些代码应该足够了,但如果我需要提供更多代码,请告诉我,我会这样做。在此先感谢!!

1 个答案:

答案 0 :(得分:2)

要将控制传递给下一个匹配路由,您需要使用在路由中作为第三个参数传递的<?php /** * Used to get the current viewed node (works when viewed in page mode). * @param array $node_types[optional] A filter on the type of node you want to see. * @return object The node or null if not successfull. */ function helper_get_current_node($node_types = array()) { // Store the current node id, to avoid doing the URL testing // on every call to this function. I didn't store the node itself // because I was afraid of data changes during page processing. // Normally node_load() already does some static caching and I think // it handles cache updates correctly. static $nid; if (!isset($nid)) { $arg = arg(); // Get URL splitted. // What type of URL is it? switch ($arg[0]) { // Viewing a node or a revision of a node : case 'node': // If the node id is missing, null or not numeric if (!isset($arg[1]) || is_null($arg[1]) || !is_numeric($arg[1])) { $nid = false; } // Look at the 3rd part of the URL ('edit', 'view', 'revisions', ...) if (isset($arg[2])) { switch ($arg[2]) { case 'view': break; case 'revisions': // If we are not viewing a revision if (!isset($arg[4]) || $arg[4] != 'view') { $nid = false; } break; default: // 'edit', 'delete', etc... $nid = false; } } // If $nid has not been set, it means we where viewing a node. if (!isset($nid)) { $nid = $arg[1]; } break; // Commenting a node : case 'comment': // If the URL just has /comment, or if the node id is missing or not numeric if (!isset($arg[1]) || !isset($arg[2]) || !is_numeric($arg[2])) { $nid = false; } // If $nid has not been set to false, it means we should be commenting a node. if (!isset($nid)) { $nid = $arg[2]; } break; // URL doesn't start with something relative to node viewing default: $nid = false; } } // end if $nid is not set. // Return null if we are not viewing a node. if (!$nid) return null; // Load the node. $viewedNode = node_load($nid); // return null, if node not loaded, if node isn't the desired type // or if the user isn't allowed to see this node. if (!$viewedNode || !node_access('view', $viewedNode) || (count($node_types) > 0 && array_search($viewedNode->type, $node_types) === false)) { return null; } return $viewedNode; } ?>

next