How to do authentication in node.js that I can use from my site?

I want Node.js to authenticate the user of my website. How can i do this?

I want to implement Everyauth authentication using a simple password method, not OpenID.

I tried https://github.com/jimpick/everyauth-example-password and it works.

I want to use a database for storage. This script does not use a database. I used MySQL in the past, so I prefer this, but I'm fine with something else like MongoDB.

I just want to add the database to my script. Please, help.

+3
source share
1 answer

You only need to change the .authenticate method. Since connecting to the database is (or should be) an asynchronous operation, you need to add a promise object (see everyauth documentation ).

Assuming you have an ORM with user data matching the user object with username and password attributes (in my example, I will use the mongoose engine), this is how it looks:

 .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 */ }) 

I have not tested it, but according to the documentation, it should work. Remember that errors must be stored in an array.

By the way: if you use only the password method, then you do not need to use a gun against a fly. :) Writing your own (not necessarily perfect, but working) authentication mechanism is very simple, and if you do not know how to do this, you should study it. This will be beneficial in the future, since authentication and security in general are very important in every web application.

+3
source

All Articles