passport authentication always fails - node.js

I'm trying to setup a simple login page using express framework , mongodb and passport for authentication.
My authentication always goes to the failstate. Where am I wrong ?
my sever.js:
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
var cors = require('cors');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
//var router = express.Router();
var path = require('path');
var mongoose = require('mongoose');
var User = require('./model');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(
function(username, password, done) {
users.findOne({
username : 'username'
}, function(err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false);
}
if (user.password != password) {
return done(null, false);
}
return done(null, user);
});
}
));
app.post('/login',
passport.authenticate('local', { failureRedirect: '/error' }),
function(req, res) {
res.redirect('/success?username='+req.user.username);
});
//app.use("/",router);
//app.use(bodyParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
app.get('/success', (req, res) => res.send("Welcome "+req.query.username+"!!"));
app.get('/error', (req, res) => res.send("error logging in"));//ALWAYS LAND HERE
passport.serializeUser(function(user, cb) {
cb(null, user.id);
});
/*passport.deserializeUser(function(id, cb) {
User.findById(id, function(err, user) {
cb(err, user);
});
});
*/
//app engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
mongoose.connect('mongodb://localhost:27017/UserSchema');
/*
router.use(function (req,res,next) {
console.log("/" + req.method);
next();
});*/
app.get("/",function(req,res){
res.render('index');
});
app.post("/user",function (req, res) {
var u = new User();
//console.log(req.body);
u.email = req.body.email;
u.name = req.body.name;
u.password = req.body.password;
//p.photo = req.body.photo;
u.save(function (err) {
if (err) {
res.send(err);
}
res.render('login');
});
});
app.get("/login",function (req, res) {
res.render('login');
});
app.get("/all",function (req, res) {
User.find(function (err, products) {
if (err) {
res.send(err);
}
res.send(products);
});
});
/*
router.get("/about",function(req,res){
res.sendFile(path + "about.html");
});
router.get("/contact",function(req,res){
res.sendFile(path + "contact.html");
});
app.use("*",function(req,res){
res.sendFile(path + "404.html");
});
*/
app.listen(3000,function(){
console.log("Live at Port 3000");
});
sorry for the junk comments
here is my mongoose schema (model.js):
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
email: String,
name: String,
password: String,
//photo: String,
});
module.exports = mongoose.model('User', UserSchema);
my login.ejs :
<!DOCTYPE html>
<html>
<<title>Login</title>
<body>
<form action="/login", method="post">
Email:<br>
<input type="text" name="username">
<br>
Password:
<br>
<input type="text" name="password">
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
and my registration page which is able to register and insert in db:
<!DOCTYPE html>
<html>
<body>
<form action="/user", method="post">
Email:<br>
<input type="text" name="email">
<br>
Name:<br>
<input type="text" name="name" >
<br>
Password:
<br>
<input type="text" name="password">
<br><br>
<input type="submit" value="Submit">
</form>
<a href="/login"/><input type="submit" value="Login">
</body>
</html>

You imported your MongoDB User model as:
var User = require('./model');
However, you are calling the .findOne() method on "users"
passport.use(new LocalStrategy(
function(username, password, done) {
users.findOne({
username : 'username'
}, function(err, user) {
Should it not be User.findOne()
If that doesn't resolve the issue then you should elaborate more on what you mean by "my application always go to the failstate".

Related

How can I enter three field in my database, with passport, passport-local-mongoose, and express-session

I am stuck with this code. I want to insert three fields in my database using User.register(), but my passport.authenticate() is giving me bad request and redirect me to register page again and again, but my data got inserted into the database.
Here is my app.js:
require('dotenv').config()
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const _ = require("lodash");
const session = require("express-session");
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");
const app = express();
app.set("view engine", 'ejs');
app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({
secret: process.env.SECRET,
resave: false,
saveUninitialized: false,
}));
app.use(passport.initialize());
app.use(passport.session());
mongoose.set("strictQuery", true);
mongoose.connect("mongodb://127.0.0.1:27017/My1stProjectDb", (err) => {
if (err) {
console.log(err);
} else {
console.log("Success !!!");
}
});
const userSchema = new mongoose.Schema({
name: String,
email: String,
Password: String
});
userSchema.plugin(passportLocalMongoose);
const User = new mongoose.model("User", userSchema);
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.get("/", function (req, res) {
res.render("home");
});
app.get("/sell", function (req, res) {
res.render("sell");
});
app.get("/categories", function (req, res) {
res.render("categories");
});
app.get("/register", function (req, res) {
res.render("register");
});
app.get("/login", function (req, res) {
res.render("register")
})
app.get("/secrets", function (req, res) {
if (req.isAuthenticated()) {
res.render("secrets")
} else {
res.render("register")
}
});
app.get("/logout", function (req, res) {
req.logout((err) => {
if (err) {
console.log(err);
} else {
res.redirect("/");
}
});
});
app.post("/register", function (req, res) {
const registerUser = new User({ email: req.body.useremail, username: req.body.username });
User.register(registerUser, req.body.userpassword, function (err, user) {
if (err) {
console.log(err);
} else{
passport.authenticate("local",{ failureRedirect: '/register' })(req, res, function () {
res.redirect("/secrets");
});
}
});
});
app.listen(3000, function () {
console.log("Server started at port 3000");
});
Here is registration page
<form action="/register" method="POST">
<div class="form sign-up">
<h2>Create your Account</h2>
<label>
<span>Name</span>
<input type="text" name="username" />
</label>
<label>
<span>Email</span>
<input type="email" name="useremail" />
</label>
<label>
<span>Password</span>
<input type="password" name="userpassword"/>
</label>
<button type="submit" class="submit">Sign Up</button>
</div>
</form>
I want to make my code compatible for three fields entry in userSchema into database and successfully redirect it to secrets page with authentication.

How to Authenticate signup and login frontend form with Passport JS at backend

Getting my signup and login form to connect to my local MongoDB is not working. I am using a Passport for authentication. At first, it threw up "no username was given error". I fixed that by defining usernameField. Now, when I fill in details on the frontend form, it is not sending to the MongoDB database on clicking submit. The values are just there.
Here is My Server.js
const express = require("express"),
connect = require("./config/db"),
passport = require("passport"),
bodyParser = require("body-parser"),
User = require("./model/trialModel");
LocalStrategy = require("passport-local").Strategy,
routes = require('./route/userRoute')
const path = require('path')
connect()
const app = express();
app.engine('html', require('ejs').renderFile)
app.set("view engine", "html");
app.set('views', path.join(__dirname, 'views'))
app.use(bodyParser.urlencoded({ extended: true }));
app.use(require("express-session")({
secret: "Rusty is a dog",
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
// passport.use(User.createStrategy());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
//=====================
// ROUTES
//=====================
// Showing home page
app.get("/", function (req, res) {
res.render("home");
});
// Showing secret page
app.get("/secrete", isLoggedIn, function (req, res) {
res.render("secrete");
});
// Showing register form
app.get("/register", function (req, res) {
res.render("register");
});
//Showing registration success page
app.get("/success", function (req, res) {
res.render("success");
});
// // Handling user signup
// app.post("/register", function (req, res) {
// var username = req.body.username
// var password = req.body.password
// var fullname = req.body.fullname
// var email = req.body.email
// User.findByUsername(username, function(err, user) {
// if (err) {
// console.log(err)
// } else if (user){
// res.send('username already exist!')
// } else{
// User.register(new User({ username: username, fullname: fullname, email: email}), password,
// function (err, user) {
// if (err) {
// console.log(err);
// return res.render("register");
// } else{
// res.redirect('/success')
// }
// passport.authenticate("local")(
// req, res, function () {
// res.render("secrete");
// });
// });
// }
// })
// });
//Showing login form
app.get("/login", function (req, res) {
res.render("login");
});
// //Handling user login
// app.post("/login", passport.authenticate("local", {
// successRedirect: "/secrete",
// failureRedirect: "/login"
// }), function (req, res) {
// });
// //Handling user logout
// app.get("/logout", function (req, res) {
// req.logout(function(err){
// if (err){
// return next(err)
// }
// res.redirect("/");
// });
// });
function isLoggedIn(req, res, next) {
if (req.isAuthenticated()) return next();
res.redirect("/login");
}
app.use('/', routes)
var port = process.env.PORT || 4000;
app.listen(port, function () {
console.log("Server Has Started!");
});
Here is my controller.js
const User = require('../model/trialModel')
passport = require("passport")
//sign up
exports.signUp = (req, res) => {
var username = req.body.username
var password = req.body.password
var fullname = req.body.fullname
var email = req.body.email
User.findByUsername(username, function(err, user) {
if (err) {
console.log(err)
} else if (user){
res.send('username already exist!')
} else{
User.register(new User({ username: username, fullname: fullname, email: email}), password,
function (err, user) {
if (err) {
console.log(err);
return res.render("register");
} else{
passport.authenticate("local")(
req, res, function () {
res.send('User registered successfully')
})}
});
}
})
};
//login
exports.login = passport.authenticate("local", {
successRedirect: "/secrete",
failureRedirect: "/login"
}), function (req, res) {
}
//logout
exports.logout = (req, res) => {
req.logout(function(err){
if (err){
return next(err)
}
res.redirect("/");
});
}
Here is my Schema Model:
const {Schema, model} = require('mongoose')
const passportLocalMongoose = require('passport-local-mongoose');
const newSchema = new Schema({
username: {
type: String,
require : true
},
fullname: {type: String,
require: true
},
email: {
type: String,
require: true
}
},
{timestamps: true})
newSchema.plugin(passportLocalMongoose,{
usernameField: 'fullname'
});
const todoModel = model('trial', newSchema);
module.exports = todoModel
Here is my HTML for Signup:
<h1> Sign up form </h1>
<h1>Auth-wiki</h1>
<h2>Create your free account</h2>
<form action="" id="register">
<div class="input-details">
<label for="">Full name</label> <br />
<input type="text" name="fullname" placeholder="Enter full name" id="" />
<br />
<label for="">Username</label> <br />
<input type="text" name="username" placeholder="Enter username" id="" />
<br />
<label for=""> Email</label> <br />
<input
type="email"
name="email"
placeholder="Enter username or email"
id="email"
/>
<h5 id="email-msg"></h5>
<br />
<label for="">Password</label> <br />
<input
type="password"
name="password"
placeholder="Enter Password"
id="Password"
/>
<h5 id="pass-msg"></h5>
</div>
<div class="check">
<input type="checkbox" id="checkbox" />
<label for="">Remember Password</label>
</div>
<button id="creat-account" type="submit">Create account</button>
</form>
<h1>This is home page</h1>
<li>Sign up!!</li>
<li>Login</li>
<li>Logout</li>
Here is my codes to consume the API from the Frontend:
const registerForm = document.getElementById('register')
function registerUser(event) {
event.preventDefault();
let fullname = event.target.fullname.value
let username = event.target.username.value
let password = event.target.password.value
//validation
if (!username || !password || !fullname) {
alert('All fields must be entered')
return;
}
let userObj = {
fullname,
username,
password
}
console.log(userObj)
fetchAPI(userObj,'register', 'POST').then((data) =>{
if (data) {
alert('user created successfully! Click ok to sign in')
// window.location.href = "../"
}
})
}
const API = 'http://localhost:4000';
async function fetchAPI(data, endpointurl, method) {
try {
//response from form
const response = await fetch(`${API}/${endpointurl}`, {
method: 'POST',
headers: {
"content-type": "application/json"
},
body:JSON.stringify(data) //convert the plain data to json so server is able to read it
})
const result = await response.json()
console.log(result)
} catch (error) {
}
}
registerForm.addEventListener('submit', registerUser)

NodeJS csrf protection gives ForbiddenError invalid csrf token only on one POST request form

I have been unsuccessfully trying to find a solution on Google for the past several hours for the following issue:
I have csurf set up and working well. It works for POST requests related to signing up/in users. I am trying to create a form in the user profile, that updates the user's data, but when I hit submit, I get ForbiddenError: invalid csrf token.
On further testing, the csrt token is created on the profile page, but for some reason, it is invalid.
(I have only recently picked up programming, I'm willing to provide additional information if I have missed something.)
Tools used:
Node.js v10.16.3
Express v4.17.1
ejs v2.7.1
csurf v1.10.0
Express session v1.16.2
Passport v^0.4.0
cookie-parser 1.4.4
body-parser v1.19.0
My app.js
let express = require("express"),
app = express(),
bodyParser = require("body-parser"),
cookieParser = require('cookie-parser'),
session = require("express-session"),
mongoose = require("mongoose"),
passport = require("passport"),
flash = require('connect-flash'),
validator = require('express-validator'),
LocalStrategy = require("passport-local"),
csrf = require('csurf'),
csrfProtection = csrf({ cookie: true }),
MongoStore = require('connect-mongo')(session);
let indexRoutes = require('./routes/index');
let userRoutes = require('./routes/user');
let User = require("./models/user");
// APP CONFIGURATION
mongoose.connect("mongodb://localhost:27017/azax", { useNewUrlParser: true, useUnifiedTopology: true, }).then(() => {
console.log("Connected to MongoDB");
}).catch((error) => {
console.log("Something is wrong...");
});
require('./config/passport');
// View engine setup
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
// Initial setup
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(validator());
// Session setup
app.use(cookieParser());
app.use(session({
secret: 'somesecretforbytox',
resave: false,
saveUninitialized: false
}));
app.use(flash());
// Initialize passport
app.use(passport.initialize());
app.use(passport.session());
app.use(csrf());
// CSRF
app.use(function (req, res, next) {
var token = req.csrfToken();
res.cookie('XSRF-TOKEN', token);
res.locals.csrfToken = token;
next();
});
app.use(function (req, res, next) {
res.locals.currentUser = req.user;
res.locals.session = req.session;
next();
});
// ======================
// Connect to route files
// ======================
app.use('/user', userRoutes);
app.use(indexRoutes);
app.listen(3033, function () {
console.log("Listening at port 3033...");
});
My passport.js:
let passport = require('passport');
let User = require('../models/user');
let LocalStrategy = require('passport-local').Strategy;
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (id, done) {
User.findById(id, function (err, user) {
done(err, user);
});
});
passport.use('local-signup', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
}, function (req, email, password, done) {
req.checkBody('username', 'Invalid username').notEmpty();
req.checkBody('email', 'Invalid email').notEmpty().isEmail();
req.checkBody('password', 'Invalid password').notEmpty().isLength({ min: 4 });
let errors = req.validationErrors();
if (errors) {
let messages = [];
errors.forEach(function (error) {
messages.push(error.msg);
});
return done(null, false, req.flash('error', messages));
}
User.findOne({ 'email': email }, function (err, user) {
if (err) {
return done(err);
}
if (user) {
return done(null, false, { message: 'Вече има акаунт с този имейл.' })
}
let username = req.body.username;
let newUser = new User();
newUser.username = username;
newUser.email = email;
newUser.password = newUser.encryptPassword(password);
newUser.country = 'България';
newUser.save(function (err, result) {
if (err) {
return done(err);
}
return done(null, newUser);
});
});
}));
passport.use('local-signin', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
}, function (req, email, password, done) {
// req.checkBody('username', 'Invalid username').notEmpty();
req.checkBody('email', 'Invalid email').notEmpty();
req.checkBody('password', 'Invalid password').notEmpty();
let errors = req.validationErrors();
if (errors) {
let messages = [];
errors.forEach(function (error) {
messages.push(error.msg);
});
return done(null, false, req.flash('error', messages));
}
User.findOne({ 'email': email }, function (err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, { message: 'Акаунтът не е намерен.' });
}
if (!user.validPassword(password)) {
return done(null, false, { message: 'Грешна парола.' });
}
return done(null, user);
});
}));
HTML...:
<form action="/user/profile" method="POST" class="form-validate form-horizontal" enctype="multipart/form-data">
<fieldset>
<legend>Edit address</legend>
<!-- email -->
<div class="control-group">
<div class="control-label">
<label id="jform_email1-lbl" for="jform_email" class="hasPopover required" title="" data-content="Enter new email address." data-original-title="Email Address">
Email<span class="star"> *</span></label>
</div>
<div class="controls">
<input type="email" name="email" class="validate-email required" id="jform_email" value="<%= (typeof currentUser.email != 'undefined' ? currentUser.email : '') %>" size="30" autocomplete="email" required aria-required="true">
</div>
</div>
<!-- name -->
<div class="control-group">
<div class="control-label">
<label id="jform_fname-lbl" for="jform_fname" class="hasPopover required" title="" data-content="Enter new name." data-original-title="Name">
Name<span class="star"> *</span></label>
</div>
<div class="controls">
<input type="text" name="firstName" id="jform_fname" value="<%= (typeof currentUser.firstName != 'undefined' ? currentUser.firstName : '') %>" class="required" size="30" required aria-required="true">
</div>
</div>
</fieldset>
<div class="form-actions">
<input type="hidden" name="_csrf" value="<%= csrfToken %>">
<button type="submit" class="btn btn-primary validate">
<span>Save</span>
</button>
<a class="btn" href="/" title="Cancel">Cancel</a>
</div>
</form>
user.js:
let express = require('express'),
router = express.Router(),
csrf = require('csurf'),
csrfProtection = csrf(),
passport = require('passport');
router.use(csrfProtection);
let User = require("../models/user");
// user profile
router.get("/profile", isLoggedIn, csrfProtection, function (req, res) {
res.render("user/profile", { csrfToken: req.csrfToken(), currentUser: req.user });
});
router.post('/profile', (req, res) => {
updateRecord(req, res);
res.redirect('/profile');
});
// update user data
function updateRecord(req, res) {
User.findOne({ _id: req.user.id }, (err, doc) => {
doc.name = req.body.name;
doc.save(function (err, doc) {
});
});
}
router.get("/profile/edit", isLoggedIn, csrfProtection, function (req, res) {
res.render("user/edit", { csrfToken: req.csrfToken(), currentUser: req.user });
});
// sign up form works with csrf
// signup form
router.get("/signup", csrfProtection, function (req, res) {
let messages = req.flash('error');
res.render("user/signup", { csrfToken: req.csrfToken(), messages: messages, hasErrors: messages.length > 0 });
});
// ... more routes
module.exports = router;
// middleware
function isLoggedIn(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/user/login');
}
What worked for me was adding the below hidden field to every form:
<input type="hidden" name="_csrf" value="<%= csrfToken %>">
and sending the token to every get request to the template page displaying the form.
{csrfToken: req.csrfToken()}
like
router.get('/user/login',function(req,res){
res.render('pages/login', {csrfToken: req.csrfToken()});
})
this fixed the error in whole app.

Nodejs - Registering/Loggin a user in error = "Cannot read property '_id' of undefined"

I'm creating authentication in NodeJs. When I try to log in a user/register a user I get the error.
Cannot read property '_id' of undefined
The method findById is only used in one get route. This is the secret get route, so only a user who is of a particular user type can access this page
I'm using passportjs also. It sends data to the databases.
This is my registration and login code
var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
mongoose = require("mongoose"),
passport = require("passport"),
User = require("./models/user"),
localStrategy = require("passport-local"),
passportLocalMongoose = require("passport-local-mongoose"),
User = require("./models/user");
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost/ww", {useMongoClient: true});
app.use(bodyParser.urlencoded({extended:true}));
app.set("view engine", "ejs");
/*=========================
Setting up PassportJS
==========================*/
app.use(passport.initialize());
app.use(passport.session());
app.use(require("express-session")({
secret: "King Nidge",
resave: false,
saveUninitialized: false
}));
passport.use(new localStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser()); //Put it back in session
passport.deserializeUser(User.deserializeUser()); //Reading session, taking in data and decoding.
/*=========================
Routes
==========================*/
app.get("/", function(req, res){
res.render("landing");
});
app.get("/secret", function(req, res){
User.findById(req.user._id, function(err, user){
if(err){
console.log(err);
}
else {
if(user.role === "Landlord"){
res.render("secret");
}
else {
res.redirect("/");
}}
});
});
/*=========================
Authentication Routes
==========================*/
//Register
app.get("/register", function(req, res){
res.render("register");
});
app.post("/register", function(req, res){
User.register(new User({username: req.body.username, email: req.body.email, role: req.body.role}), req.body.password, function(err, user){
if(err){
console.log(err);
return res.render('register');
} else {
passport.authenticate("local")(req, res, function(){
res.redirect("/secret");
});
}
});
});
//Login
app.get("/login", function(req, res) {
res.render("login");
});
app.post("/login", passport.authenticate("local", {
successRedirect: "/secret",
failureRedirect: "/login"
}) ,function(req, res){
});
This is my schema for the users.
var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");
var UserSchema = new mongoose.Schema({
username: String,
password: String,
email: String,
role: String
});
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", UserSchema);
This is my registration form
<h1>Sign Up Form</h1>
<form action="/register" method="POST">
<input type="text" name="username" placeholder="username">
<input type="password" name="password" placeholder="password">
<input type="email" name="email" placeholder="email">
<input type="radio" name="role" value="Administrator">
<input type="radio" name="role" value="User">
<button>Submit</button>
</form>
Any tips to overcome this error?
Please check this.
Express-session should be declared before passport initialization and the declaration of passport.session usage.
app.use(require("express-session")({
secret: "King Nidge",
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());

LocalStrategy of passportjs is not being called

I'm trying to build a login system using passportJS. For some reason, LocalStrategy is not being called from passport.authenticate(). No idea why. Database is mongodb. I have a collection for users in db. Can anyone help me regarding this issue? Thanks. Here is the code:
app.js
var express = require('express');
var bodyParser = require("body-parser");
var mysql = require('mysql');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongo = require('mongodb');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/WelcomeLimoUsa');
var db = mongoose.connection;
var routes = require('./routes/index');
var users = require('./routes/users');
// Init App
var app = express();
// BodyParser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// Set Static Folder
app.use(express.static(__dirname + '/'));
// Express Session
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
// Passport init
app.use(passport.initialize());
app.use(passport.session());
// Express Validator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
// Connect Flash
app.use(flash());
// Global Variables
app.use(function (req, res, next) {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
res.locals.user = req.user || null;
next();
});
app.use('/admin', routes);
app.use('/users', users);
login.html
<form action="/users/admin" method="post" class="well form-horizontal">
<p>
<strong>Admin User Name: </strong>
<input type="text" name="username" size="25" class="form-control" placeholder="User Name">
<p>
<p>
<strong align="center">Admin Password: </strong>
<input align="center" type="password" size="15" name="password" class="form-control" placeholder="password">
<p>
<p>
<input align="center" type="submit" value="Log In" class="btn btn-success" style="font-weight:600">
<input align="center" type="reset" value="Clear" class="btn btn-default" style="font-weight:600">
</form>
users.js
var express = require('express');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/user');
var router = express.Router();
// Login
router.get('/admin', function(req, res){
res.render('./login.html');
});
router.get('/error', function(req, res){
res.sendfile("./loginerror.html");
});
passport.use(new LocalStrategy(
function(username, password, done) {
User.getUserByUsername(username, function(err, user){
if(err) throw err;
if(!user){
return done(null, false, {message: 'Unknown User'});
}
User.comparePassword(password, user.password, function(err, isMatch){
if(err) throw err;
if(isMatch){
return done(null, user);
} else {
return done(null, false, {message: 'Invalid password'});
}
});
});
}));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.getUserById(id, function(err, user) {
done(err, user);
});
});
router.post('/admin', passport.authenticate('local', { successRedirect: '/admin',
failureRedirect: '/users/error',
failureFlash: true }), function(req,res){
var user_name = req.body.userid;
var password=req.body.password;
console.log("User name = " + user_name + ", password is "+ password);
res.redirect('/admin');
});
module.exports = router;
user.js
var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');
// User Schema
var UserSchema = mongoose.Schema({
username: {
type: String,
index:true
},
password: {
type: String
}
});
var User = module.exports = mongoose.model('User', UserSchema);
module.exports.getUserByUsername = function(username, callback){
var query = {username: username};
User.findOne(query, callback);
}
module.exports.getUserById = function(id, callback){
User.findById(id, callback);
}
module.exports.comparePassword = function(candidatePassword, hash, callback){
bcrypt.compare(candidatePassword, hash, function(err, isMatch) {
if(err) throw err;
callback(null, isMatch);
});
}

Resources