Hi i'm working in node with passport and mongodb for login local session , and i got a synthax error but i can't figure out why?
it's kind of weird cause i think i got every thing in order
here here it's my code ...
var localStrategy = require('passport-local').Strategy;
var User = require('../app/models/users');
module.exports = function(passport){
//Serializing user
passport.serializeUser(function(user,done){
done(null, user.id);
});
passport.deserializeUser(function(id,done){
User.findById(id, fuction(err,user){ //here it's the error D:
done(err,user);
});
});
passport.use('local-signup', new localStrategy({
usernameField: 'username',
passField:'pass'
passReqToCallback: true
},
function(req,username, pass, done){
process.nextTick(function(){
User.findOne({'local.emial':email,},function(err,user){
if(err){
return done(err);
}
if(user){
retrun done(null,false,req.flash('signupMessage','Thath email its already taken '));
}else{
var newUser = new User();
newUser.local.username = username;
newUser.local.pass = pass;
newUser.save(function(err){
if(err){
throw err;
return done(null,newUser);
}
})
}
});
});
}
));
// end function
}
as always really thanks for your help
Correct fuction into function maybe?
Related
I am working on Node.js and email-verification with passport and mongoose.
Now I am testing the code and got an error, but I can't fix it.
Here is my problem and code posted below:
My app.js i have
var nev = require('email-verification')(mongoose);
require('./routes/db/email-verification')(nev);
require('./routes/db/passport')(passport,nev);
my email-verificaiton.js
var User = require('./ModelUser');
module.exports = function(nev){
nev.configure({
...
...
},function(err,options){
if(err)
return err;
console.log('test');
});
nev.generateTempUserModel(User,function(err,tempUserModel){
if(err){
return err;
}
console.log('checked');
});
};
my passport.js
module.exports = function (passport, nev) {
...
...
passport.use('local-signup', new LocalStrategy({
usernameField: 'email', //dummy string
passwordField: 'password', //dummy string
passReqToCallback: true
}, function (req, email, password, done) {
var newUser = new User();
newUser.email = email;
newUser.password = password;
nev.createTempUser(newUser, function( err, existingPersistentUser, newTempUser){
if(err) console.error(err);
if(existingPersistentUser){
console.log('E-mail already exists');
return done(null, false, req.flash('signupMessage', 'E-mail already exists'));
}
if(newTempUser){
var URL = newTempUser[nev.options.URLFieldName];
nev.sendVerificationEmail(email, URL, function(err, info){
if(err) console.error(err);
console.log('An email has been sent to you. Please check it to verify your account.');
return done(null);
})
} else{
console.log('You have already signed up. Please check your email to verify your account.');
return done(null);
}
})
I got an error TypeError: Cannot read property 'createTempUser' of undefined
I dont know why my 'nev' variable is undefined in my passport.js.
pls anyone can help me>? this is very hard.
In email-verificaiton.js, change it to look something more like this:
function verification(nev) {
nev.configure({
...
...
},function(err,options){
if(err)
return err;
console.log('test');
});
nev.generateTempUserModel(User,function(err,tempUserModel){
if(err){
return err;
}
console.log('checked');
});
};
module.exports = {verification}
And then inside app.js you can change
var nev = require('email-verification')(mongoose);
To become
var nev = require('email-verification').verification(mongoose);
First, i have this in my route, i need to use Passport to Authenticate the User Sign Up Process :
router.post('/user/signup', passport.authenticate('local.signup',{
successRedirect: '/user/profile',
failureRedirect: '/user/signup',
failureFlash: true
}));
I'm learning Node JS from Youtube Video, in the tutorial, there is a step to create Folder called "config", and inside the "config" folder, there is a file called "passport.js".
The problem is, there is "req" parameter inside one of the function in this "passport.js". When i try to run my program, there is an error that said, "req is not defined". this is the source code of "passport.js" :
var express = require('express');
var passport = require('passport');
var User = require('../models/user');
var 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){ //here is the problem
console.log('REQ :');
console.log(req);
console.log('password :');
console.log(email);
console.log('email :');
console.log(password);
console.log('done :');
console.log(done);
req.checkBody('email','Invalid Email').notEmpty().isEmail();
req.checkBody('password','Invalid password').notEmpty().isLength({min:4});
var errors = req.validationErrors();
if(errors){
var message = [];
errors.forEach(function(error){
message.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: 'Email is already in use.'});
}
var newUser = new User();
newUser.email = email;
newUser.password = newUser.encryptPassword(password);
newUser.save(function(err, result){
if(err){
return done(err);
}
return done(null, newUser);
});
});
}));
How to bring the req to fill the parameter in the passport.js ?
The parameter is called passReqToCallback, not passReqToCallBack (notice that the b needs to be lower-case).
I am building an API using the MEAN stack and am working on the login and signup functions.
And I want to respond with a json string as follows
{
success: 0,
message: ""
}
success:1 for successful login and 0 otherwise.
My authenticate.js is as follows
module.exports = function(passport){
//log in
router.post('/login', passport.authenticate('login', {
//success
//failure
}));
//sign up
router.post('/signup', passport.authenticate('signup', {
//success
//failure
}));
//log out
router.get('/signout', function(req, res) {
req.logout();
res.redirect('/');
});
return router;
}
My passport.init.js middleware is as follows
var mongoose = require('mongoose');
var User = mongoose.model('User');
var LocalStrategy = require('passport-local').Strategy;
var bCrypt = require('bcrypt-nodejs');
module.exports = function(passport){
// Passport needs to be able to serialize and deserialize users to support persistent login sessions
passport.serializeUser(function(user, done) {
console.log('serializing user:',user.username);
done(null, user._id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
console.log('deserializing user:',user.username);
done(err, user);
});
});
passport.use('login', new LocalStrategy({
passReqToCallback : true
},
function(req, username, password, done) {
// check in mongo if a user with username exists or not
User.findOne({ 'username' : username },
function(err, user) {
// In case of any error, return using the done method
if (err)
return done(err);
// Username does not exist, log the error and redirect back
if (!user){
console.log('User Not Found with username '+username);
return done(null, false);
}
// User exists but wrong password, log the error
if (!isValidPassword(user, password)){
console.log('Invalid Password');
return done(null, false); // redirect back to login page
}
// User and password both match, return user from done method
// which will be treated like success
return done(null, user);
}
);
}
));
passport.use('signup', new LocalStrategy({
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, username, password, done) {
// find a user in mongo with provided username
User.findOne({ 'username' : username }, function(err, user) {
// In case of any error, return using the done method
if (err){
console.log('Error in SignUp: '+err);
return done(err);
}
// already exists
if (user) {
console.log('User already exists with username: '+username);
return done(null, false);
} else {
// if there is no user, create the user
var newUser = new User();
// set the user's local credentials
newUser.username = username;
newUser.password = createHash(password);
// save the user
newUser.save(function(err) {
if (err){
console.log('Error in Saving user: '+err);
throw err;
}
console.log(newUser.username + ' Registration succesful');
return done(null, newUser);
});
}
});
})
);
var isValidPassword = function(user, password){
return bCrypt.compareSync(password, user.password);
};
// Generates hash using bCrypt
var createHash = function(password){
return bCrypt.hashSync(password, bCrypt.genSaltSync(10), null);
};
};
Please help me out in passing the JSON string accordingly
Using Express, all you have to do is to execute res.json inside any controller, passing it any JavaScript object. Express will automatically convert it to JSON and return it to the user.
return res.json({ success: 0, message: '' }
var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/user');
module.exports = function(passport){
passport.use('local-signup', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
},
function(req, email, password, done){
User.findOne({'local.username': email}).exec()
.then(function(user) {
console.log(user);
if(user){
return done(null, false, {message: 'Username already taken!'});
}
else{
var newUser = new User();
newUser.local.username = email;
newUser.local.password = password;
return newUser.save();
}
})
.then(function(user) {
console.log('DEBUG DEBUG DEBUG');
done(null, user);
})
.catch(function(err) {
done(err);
});
}
));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(userid, done) {
User.findById(userid).exec()
.then(function(user) {
done(user);
});
});
};
In my case the debug log always be printed, whether return newUser.save() is called or not.
Is it possible to make the debug log only be printed when return newUser.save() is called?
Btw I'm using passportJS for authentication things and for the promise I'm override mongoose default promise with global es6 promise.
You mean like this? Sorry if there are extra brackets or parenthesis. I edited in the text box. :(
User.findOne({'local.username': email}).exec()
.then(function(user) {
if(user){
return done(null, false, {message: 'Username already taken!'});
}
else{
var newUser = new User();
newUser.local.username = email;
newUser.local.password = password;
return newUser.save()
.then(function(){
console.log('DEBUG DEBUG DEBUG');
done(null, user);
})
}
})
.catch(function(err) {
done(err);
});
}
));
Just put your debug message in a function in newUser.save()
User.findOne({'local.username': email}).exec()
.then(function(user) {
console.log(user);
if(user){
return done(null, false, {message: 'Username already taken!'});
}
else{
var newUser = new User();
newUser.local.username = email;
newUser.local.password = password;
return newUser.save(function() {
console.log('SAVED!');
console.log('DEBUG DEBUG DEBUG');
});
}
})
.then(function(user) {
done(null, user);
})
My model looks like this, but when I try use verifyPassword, it says TypeError: user.verifyPassword is not a function
var passport = require('passport');
var BasicStrategy = require('passport-http').BasicStrategy;
var User = require('../models/user');
passport.use(new BasicStrategy(
function(username, password, callback) {
User.findOne({ username: username }, function (err, user) {
if (err) { return callback(err); }
// No user found with that username
if (!user) { return callback(null, false); }
// Make sure the password is correct
// Error comind at this point
user.verifyPassword(password, function(err, isMatch) {
if (err) { return callback(err); }
// Password did not match
if (!isMatch) { return callback(null, false); }
// Success scenario
return callback(null, user);
});
});
}
));
Try to use User.verifyPassword function
But for more correct answer show your User model
You should have in your User schema something like:
// I am use bctypt, but you need your comparer function
userSchema.methods.verifyPassword = function(password, callback) {
callback(err, bcrypt.compareSync(password, this.password));
};
I know i am late but you can do something like this,
passport.use(
'local',
new LocalStrategy(function(username, password, done) {
User.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);
});
})
);
Reference : https://github.com/sikandar114/node-auth-pass-local/blob/master/config/passport.js
Since the data is sent by post method, express is not able to parse data because body-parser middleware has been omitted from express due to some issues. Hence you must add it manually.Import body-parser:
npm install body-parser
Add these lines to your code.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(passport.initialize());
Also define these 2 functions.
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
Try using passport.use(new LocalStrategy(User.authenticate()));