如何在我可以从我的网站上使用的node.js中进行身份验证?

时间:2012-05-30 08:53:11

标签: mysql node.js mongodb

我想要一个Node.js服务来验证我的网站用户。我怎么能这样做?

我想使用简单的密码方法实现Everyauth身份验证,而不是OpenID。

我尝试了https://github.com/jimpick/everyauth-example-password并且确实有效。

我想用数据库来存储。此脚本不使用数据库。我过去曾经使用过MySQL,所以我更喜欢它,但我也可以使用其他任何东西,例如MongoDB。

我只想在我的脚本中添加数据库。请帮忙。

1 个答案:

答案 0 :(得分:3)

您只需要修改.authenticate方法。由于连接到数据库是(或应该是)异步操作,因此您需要添加promise对象(请参阅everyauth documentation)。

假设您有一些ORM与用户数据相对应user对象usernamepassword属性(在我的示例中我将使用mongoose引擎),这就是它的外观:

.authenticate( function (login, password) {
    var promise = this.Promise(); /* setup promise object */

    /* asynchrnously connect to DB and retrieve the data for authentication */
    db.find({ username:login }, function(err, user) {
        if (err)
            return promise.fulfill([err]);
        if ((!user) || (user.password != password))
            return promise.fulfill(['Incorrect username or password!']);
        promise.fulfill(user);
    });

    return promise; /* return promise object */
})

我没有测试它,但根据文档它应该工作。请记住,错误应该保存在数组中。

顺便说一下:如果你只使用密码方法,那么你就不需要使用大炮对抗苍蝇。 :)编写自己的(不一定是完美的,但工作)认证机制非常简单,如果你不知道如何做到这一点,你应该学习它。它将在未来受益,因为在每个Web应用程序中,身份验证和安全性都非常重要。