I'm new in Node.js and Express and I have a problem with access control with Passport.
I want to check with which role user is logged in.
My user schema:
let mongoose = require('mongoose');
let userSchema = new mongoose.Schema({
name:{
type: String,
required: true
},
email:{
type: String,
required: true
},
password:{
type: String,
required: true
},
username:{
type: String,
required: true
},
role:{
type: String,
default: 'user'
},
activated:{
type: Boolean,
default: false
}
});
let User = module.exports = mongoose.model('User', userSchema);
My passport.js file
const LocalStrategy = require('passport-local').Strategy;
const User = require('../models/user');
const dbConfig = require('../config/database');
const bcrypt = require('bcrypt');
module.exports = (passport) => {
//Local Strategy
passport.use(new LocalStrategy((email, password, done) => {
//Match email
let query = {email: email}
User.findOne(query, (err, user) => {
if(err){
console.log(err);
}
if(!user) {
return done(null, false, {message: 'No user found'});
}
//Match password
bcrypt.compare(password, user.password, (err, isMatch) => {
if(err){
console.log(err);
}
if(isMatch){
return done(null, user);
} else {
return done(null, false, {message: 'Wrong password'});
}
});
});
}));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
}
The small part of app.js file where I'm setting up global variable user
app.get('*', (req, res, next) => {
res.locals.user = req.user || null;
next();
});
Part of layout.pug file where I'm using global user variable
.navbar.collapse.navbar-collapse
ul.nav.navbar-nav
li
a(href='/') Home
if user
li
a(href='/articles/add') Add article
What I want to do is to check if user has an admin role. I tried to do that in different ways but with no success. I wanted to check the role in app.js, but I was getting errors:
if(req.user.role == 'admin'){
res.locals.admin = req.user;
}
Also I wanted to pass only the role in passport.js and it was working then but I need also other property of user.
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
How can I resolve my problem?
You should check if req.isAuthenticated() then checking the role. Cuz if req.user is null then you can't check the property 'admin' of null
if(req.isAuthenticated() && req.user.role == 'admin'){
res.locals.admin = req.user;
}
The req.isAuthenticated() function is provided by passport.js
Related
I am trying to get mongoose return data from local MongoDB instance. Eveything else is running fine. The form is giving data to passport. I have also inserted data into mongodb manually. The only error is in user.findOne. When I print user into console, instead of returning some data it returns null
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const User = require('../models/member');
// authentication using passport
passport.use(new LocalStrategy({
usernameField: 'user',
passwordField: 'password'
},
function (username, password, done) {
User.findOne({ user: username }, function (err, user) {
// console.log(user, username, password);
if (err) {
console.log(`Error in configuring passport-local \n ${err}`);
return done(err);
}
if (!user) {
console.log(`Invalid username or password!!`)
return done(null, false);
}
return done(null, user);
});
}
));
My schema:
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
user: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
dept: String,
yr: Number,
name: {
type: String
}
}, {
timestamps: true
});
module.exports = mongoose.model('member_list', userSchema, 'member_list');
Here's my full code: https://github.com/krush11/site
Let me know if you need any more info
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const User = require('../models/member');
// authentication using passport
passport.use(new LocalStrategy({
usernameField: 'user',
passwordField: 'password'
},
async function (username, password, done) {
await User.findOne({ user: username }, function (err, user) {
// console.log(user, username, password);
if (err) {
console.log(`Error in configuring passport-local \n ${err}`);
return done(err);
}
if (!user) {
console.log(`Invalid username or password!!`)
return done(null, false);
}
return done(null, user);
});
}
));
The function looks good but try making it asynchronous then await the query from the database. Take a look at the modification I made to your code. You might also want to refactor your code and use promises instead of callback and wrap everything inside of try{} catch{} block.
But making the function asynchronous and awaiting the query will fix the issue, this is because the findOne() method actually returns a query and might not have completed before you console it.
Let me know if you still have any issue.
I've seen this question asked already, sorry if it seems repetitive; but I've read through a lot of the answers and they haven't helped. I keep getting a "MISSING CREDENTIALS" error no matter what I do with the login form. I'm trying to implement a user login using email and password.
My Route File
const express = require('express');
const router = express.Router();
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const User = require('../models/user');
passport.use(new LocalStrategy((email, password, done) => {
User.getUserByEmail(email, (err, user) => {
if(err) throw err;
if(!user) {
return done(null, false, {message: 'this account does not exist'});
}
User.comparePassword(password, user.password, (err, isMatch) => {
if(err) throw err;
if(isMatch) {
return done(null, user);
}
else {
return done(null, false, {message: 'oops! wrong password! try again'});
}
});
});
}));
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.getUserById(id, (err, user) => {
done(err, user);
});
});
router.post('/', (req, res, next) => {
passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/toSignInPage',
failureFlash: true
})(req, res, next);
});
module.exports = router;
user.js file
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bcrypt = require('bcryptjs');
const UserSchema = new Schema({
email: {
type: String,
required: true,
trim: true
},
name: {
type: String,
required: true,
unique: true,
trim: true
},
password: {
type: String,
required: true,
trim: true
},
profilePhoto: {
originalemail: String,
imagePath: String
},
token: String
});
const User = module.exports = mongoose.model('User', UserSchema);
module.exports.registerUser = function(newUser, callback) {
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if(err) {
console.log(err);
}
newUser.password = hash;
newUser.save(callback);
});
});
};
module.exports.getUserByEmail = function(email, callback) {
const query = {
email: email
};
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, (err, isMatch) => {
if(err) throw err;
callback(null, isMatch);
});
};
I've initialized passport in my app.js file - session options and all that nice stuff.
also my html(handlebars)for the form
<form method="post" action="/signInPage">
<label for="mail"> Email </label>
<input type="email" id="mail" name="email" />
<label for="password"> Password</label>
<input type="password" id="password" name="password"/>
<button type="submit">Sign in</button>
<p class="corp"> Forgot password? </p>
</form>
Any help is appreciated on this. I've been stuck for a while debugging and I can't seem to figure out what I must have done wrong. please if I didn't properly format the question in an understandable format let me know.
Someone who I'm grateful to posted a link to the solution; but I can't find the comment, so I'll just add the solution.
Passport js logs user in with user name by default
passport.use(new LocalStrategy((username, password, done) => {
}));
so I was trying to use email
passport.use(new LocalStrategy((email, password, done) => {
}));
in order to log a user in with email, I had to do it this way
passport.use(new LocalStrategy((email, password, done) => {
{
usernameField : 'email',
passwordField : 'password'
}
}));
this will override the default use of username to email...
here's the link to the soultion:
https://github.com/scotch-io/easy-node-authentication/blob/master/config/passport.js#L58
I am trying to make a user account system in node and am using bcrypt for hashing passwords. My syntax seems to be correct, and there is no error thrown in the console, however still the passwords aren't getting encrypted when stored in the database(mongo db).
This is my user.js file in models:
var mongoose = require('mongoose');
var bcrypt = require('bcrypt');
mongoose.connect('mongodb://localhost/nodeauth');
var db = mongoose.connection;
// User
var UserSchema = mongoose.Schema({
username: {
type: String,
index: true
},
password: {
type: String,
required: true,
bcrypt: true
},
email: {
type: String
},
name: {
type: String
},
profileImage: {
type: String
}
});
var User = module.exports = mongoose.model('User', UserSchema);
module.exports.comparePassword = function(candidatePassword, hash, callback) {
bcrypt.compare(candidatePassword, hash, function(err, isMatch) {
if(err) return callback(err);
callback(null, isMatch);
});
}
module.exports.getUserById = function(id, callback) {
User.findById(id, callback);
}
module.exports.getUserByUsername = function(username, callback) {
var query = {username: username};
User.findOne(query, function(err, user) {
callback(err, user);
});
}
module.exports.createUser = function(newUser, callback) {
bcrypt.hash(newUser.password, 10, function(err, hash) {
if(err) throw err;
// Set hashed password
newUser.password = hash;
// Create user
newUser.save(callback);
});
}
And this is the relevant part of users.js file in routes which is used in the login section to check whether the username and password match(which is also not working):
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.getUserById(id, function(err, user) {
done(err, user);
});
});
passport.use(new LocalStrategy(function(username, password, done) {
User.getUserByUsername(username, function(err, user) {
if(err) throw err;
if(!user) {
console.log('Unknown 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 {
console.log('Invalid Password');
return done(null, false, {message: 'Invalid Password'});
}
});
});
}));
router.post('/login', passport.authenticate('local', {successRedirect: '/', failureRedirect:'/users/login', failureFlash:'Invalid username or password'}), function(req, res) {
console.log('Authentication Successful');
req.flash('success', 'You are logged in');
res.redirect('/');
});
module.exports = router;
I am not able to understand why the passwords aren't getting encrypted, and even then, why is comparePassword always returning a failure, thus making authentication fail every time as well.
Is there anything I am missing?
I am using Passport on my node.js app and I am currently using an Username to login.
On my user register page, I have allow the user to register their unique username and email.
I want a login page with "Sign in Using username/email:" ________
Where the script can detect if there is a "#" in the field and look up the email instead of username.
I have tried for a few hours with no avail.
here is my passport.js
var mongoose = require('mongoose')
var LocalStrategy = require('passport-local').Strategy
var User = mongoose.model('User');
module.exports = function(passport, config){
passport.serializeUser(function(user, done){
done(null, user.id);
})
passport.deserializeUser(function(id, done) {
User.findOne({ _id: id }, function (err, user) {
done(err, user);
});
});
passport.use(new LocalStrategy({
usernameField: 'username',
passwordField: 'password'
}, function(username, password, done) {
User.isValidUserPassword(username, password, done);
}));
}
EDIT: below is the user.js as requested
var mongoose = require('mongoose');
var hash = require('../util/hash.js');
UserSchema = mongoose.Schema({
username: String,
email: String,
salt: String,
hash: String
})
UserSchema.statics.signup = function(username, email, password, done){
var User = this;
hash(password, function(err, salt, hash){
if(err) throw err;
// if (err) return done(err);
User.create({
username : username,
email: email,
salt : salt,
hash : hash
}, function(err, user){
if(err) throw err;
// if (err) return done(err);
done(null, user);
});
});
}
UserSchema.statics.isValidUserPassword = function(username, password, done) {
this.findOne({username : username}, function(err, user){
// if(err) throw err;
if(err) return done(err);
if(!user) return done(null, false, { message : 'Incorrect username.' });
hash(password, user.salt, function(err, hash){
if(err) return done(err);
if(hash == user.hash) return done(null, user);
done(null, false, {
message : 'Incorrect password'
});
});
});
};
var User = mongoose.model("User", UserSchema);
module.exports = User;
Ok, you should have something like this in your Mongoose model:
UserSchema.statics.isValidUserPassword = function(username, password, done) {
var criteria = (username.indexOf('#') === -1) ? {username: username} : {email: username};
this.findOne(criteria, function(err, user){
// All the same...
});
};
its a mongoose thing rather than a passport thing, and if you can try out this, using bredikhin's answer ^_^ :
var criteria = {$or: [{username: username}, {email: username}, {mobile: username}, {anything: username}]};
The key is to find a user through a query from mongodb!!!
In this way, you can have whatever query you want to find a user.
For sign ins with username OR email, you could also use passport-local-mongoose's findByUsername option modify the queryParameters
// add passport functions
// schema.plugin(passportLocalMongoose);
schema.plugin(passportLocalMongoose, {
// allow sign in with username OR email
findByUsername: function(model, queryParameters) {
// start
// // queryParameters => { '$or' : [ { 'username' : 'searchString' } ] }
// iterate through queryParameters
for( let param of queryParameters.$or ){
// if there is a username
if( typeof param == "object" && param.hasOwnProperty("username") ){
// add it as an email parameter
queryParameters.$or.push( { email : param.username } );
}
}
// expected outcome
// queryParameters => { '$or' : [ { 'username' : 'searchString' }, { 'email' : 'searchString' } ] }
return model.findOne(queryParameters);
}
});
its very simple you have to redefine the passport strategy your self, just like in the code below,
serialize with username
passport.serializeUser(function(user, done) {
done(null, user.username);});
deserialize with username
passport.deserializeUser(function(username, done) {
User.findOne({username:username},function(err, user){
done(err,user);
}); });
Passport Strategy
//passport strategy
passport.use(new LocalStrategy(function(username, password, done) {
console.log(username.includes("#"));
User.findOne((username.includes("#"))?{email:username}:{username:username}, function(err, user) {
if (err) {return done(err); }
if (!user) {console.log("i am ERROR"); return done(null, false, { message: 'Incorrect username.' });}
if (user.password===password) {return done(null, user); }
return done(null, false);
});
}
));
NOTE: Here user.password===password means that the password in database is stored as plaintext.. And you have to insert password manually to database such as password : req.body.password also you have to apply encryption and decryption user self before adding or in comparing.
Or you just make a middle-ware to handle the situation like so:
const User = require("../models/user");
var middlewareObj = {};
middlewareObj.checkUsername = function (req, res, next) {
if (req.body.username.indexOf('#') !== -1) {
User.findOne({ email: req.body.username }, (err, foundUser) => {
if (err || !foundUser) {
req.flash('error', 'Please check your username or password');
return res.redirect('/login');
} else {
req.body.username = foundUser.username;
next();
}
});
} else {
next();
}
}
module.exports = middlewareObj;
And simply add it to the login route:
app.post('/login', middleware.checkUsername, function (req, res, next) {
//Login logic goes here
}
I need to write commonplace code to check a Current User Password value submitted via form to see if it matches the existing password in the database, and if so, update the password to a New Password value that was submitted via the same form.
Yet, I can't find any good examples of how to do this using Passport.js. Can anyone advise as to how I can do this in my Users controller down below, if there are any helper functions provided by passport that I should use for this, and how I do this with hashed and salted passwords?
Here is my code:
// Form Submitted
req.body = {
_id: '5294198b7b35ad2794000001',
email: 'testusera1#abc.net',
name: 'John Smith',
provider: 'local',
username: 'ab123',
current_password: 'currentpassword',
new_password: 'newpassword'
}
// Route
app.put('/users/me', users.update);
// Controller
var mongoose = require('mongoose'),
User = mongoose.model('User'),
_ = require('underscore'),
passport = require('passport'),
LocalStrategy = require('passport-local').Strategy;
exports.update = function(req, res) {
var user = req.user
user = _.extend(user, req.body);
user.save(function(err) {
if(err) { console.log(err) };
res.jsonp(user);
});
};
// Passport Config File
module.exports = function(passport) {
//Serialize sessions
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findOne({
_id: id
}, function(err, user) {
done(err, user);
});
});
//Use local strategy
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password'
},
function(email, password, done) {
User.findOne({
email: email
}, function(err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, {
message: 'Unknown user'
});
}
if (!user.authenticate(password)) {
return done(null, false, {
message: 'Invalid password'
});
}
return done(null, user);
});
}
));
};
hashed and salted password
full example on github
// Bcrypt middleware
userSchema.pre('save', function(next) {
var user = this;
if(!user.isModified('password')) return next();
bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
if(err) return next(err);
bcrypt.hash(user.password, salt, function(err, hash) {
if(err) return next(err);
user.password = hash;
next();
});
});
});
// Password verification
userSchema.methods.comparePassword = function(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
if(err) return cb(err);
cb(null, isMatch);
});
};