带节点的简单用户登录验证模块

时间:2014-03-02 02:34:00

标签: javascript mysql node.js node-mysql

我正在编写我的第一个(非教程)节点应用程序,我正在编写一个函数,该函数应该将用户名和密码作为参数,并根据我的数据库的用户表查询它们以返回true或者是假的。数据库已设置,应用程序已成功连接到该数据库。

但是,我没有使用过SQL,也没有使用过节点,而且我不确定如何继续使用这个函数(以及简短的周围脚本)。这是:

console.log('validator module initialized');
var login = require("./db_connect");

function validate(username, password){

connection.connect();
console.log('Connection with the officeball MySQL database openned...');

connection.query(' //SQL query ', function(err, rows, fields) {
    //code to execute

});

connection.end();
console.log('...Connection with the officeball MySQL database closed.');


    if(){ //not exactly sure how this should be set up
        return true;
    }
    else{ //not exactly sure how this should be set up
        return false;
    }
}

exports.validate = validate;

这是使用node-mysql。我正在寻找一个如何设置查询和验证的基本示例。

1 个答案:

答案 0 :(得分:1)

我认为你会想要将你的应用重新考虑为更像节点的方式(即认识到许多/大多数事情是异步发生的,所以你通常不会从这样的函数“返回”,而是做来自它的回调。不确定你打算从node-mysql获得什么,但我可能只是使用普通的mysql模块。以下代码仍然很可能不完全是你想要的,但希望能让你正确地思考它

请注意,下面使用'return'实际上并不返回结果(回调本身不应该返回任何内容,因此它就像返回undefined一样。返回语句在那里,所以你退出函数,这节省了很多繁琐的if / else阻止。

希望这会有所帮助,但我建议在github上查看各种节点项目,以便更好地了解节点写入的异步性质。

function validate(username, password, callback){
    var connection = mysql.createConnection({ user:'foo',
                            password: 'bar',
                            database: 'test',
                            host:'127.0.0.1'});

    connection.connect(function (err){
        if (err) return callback(new Error('Failed to connect'), null);
        // if no error, you can do things now.

        connection.query('select username,password from usertable where username=?',
                username,
                function(err,rows,fields) {
                    //  we are done with the connection at this point), so can close it
                    connection.end();

                    // here is where you process results
                    if (err)
                        return callback(new Error ('Error while performing query'), null);
                    if (rows.length !== 1)
                        return callback(new Error ('Failed to find exactly one user'), null);

                    // test the password you provided against the one in the DB.
                    // note this is terrible practice - you should not store in the
                    // passwords in the clear, obviously. You should store a hash,
                    // but this is trying to get you on the right general path

                    if (rows[0].password === password) {
                        // you would probably want a more useful callback result than 
                        // just returning the username, but again - an example
                        return callback(null, rows[0].username);
                    } else {
                        return callback(new Error ('Bad Password'), null);
                    }

                });


    });
};