Reputation: 119
I'm trying to do small app using Node.js+Express+MongoDb.Created login Page. Now I want post data from loginpage and validate username and email according to database. I wonder how to do this. My Login-page View(Jade):
extends layout
body
block content
.container
form.form-signin(action="/login", method="post")
h2.form-signin-heading Please sign in
input.input-block-level(type="text", name="username", placeholder="username")
input.input-block-level(type="text", name="text", placeholder="user mail")
label.checkbox.
<input type="checkbox" value="remember-me" /> Remember me
button.btn.btn-large.btn-primary(type="submit") Sign in
router.post('/login', function(req, res, next) {
var uname=req.body.username;
var email=req.body.email;
var db = req.db;
var collection = db.get('userlist');
if(check with database uname and email present or not)
{
//if true
res.render('index', { title: 'Express' });
}
else
{
//render loginpage with error msg
res.render('login', { title: 'Express' });
}
});
Please help.
Upvotes: 0
Views: 1572
Reputation: 668
There are a lot of methods to reach the goal. I can recommend you the following.
Here are links below
Code examples:
//User Schema
/*
* Generate Hash to save password
*/
userSchema.methods.generateHash = function (password) {
// some service to encrypt and check passwords
return encryptService.encrypt(password);
};
/*
* Check if password is valid
*/
userSchema.methods.validPassword = function (password) {
var user = this;
var checkPasswordParams = {
password: password,
hash: user['authentication']['hash']
};
// some service to encrypt and check passwords
return encryptService.compare(checkPasswordParams);
};
//encrypt service
//here are examples from bcrypt page
bcrypt.hash("bacon", null, null, function(err, hash) {
// Store hash in your password DB.
});
bcrypt.compare("bacon", hash, function(err, res) {
});
bcrypt.compare("veggies", hash, function(err, res) {
});
//Example Of Passport Local Strategy (Username + Password)
var passport = require('passport')
, LocalStrategy = require('passport-local').Strategy;
passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({ username: username }, function(err, user) {
if (err) { return done(err); }
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
if (!user.validPassword(password)) {
return done(null, false, { message: 'Incorrect password.' });
}
return done(null, user);
});
}
));
Here you can find good example of Token Authentication:
https://scotch.io/tutorials/authenticate-a-node-js-api-with-json-web-tokens
I recommend using this npm module to create and check tokens:
npm install jwt
Upvotes: 1