I've a issue with PassportJS. It displays this message and I can't understand where I'm doing wrong:
{"message":"Unknown authentication strategy \"facebook\"","error":{}}
GET /auth/facebook 500 0.505 ms - 69
Credentials are hardcoded for simplicity and learning purpose. Passport and Passport-Facebook are installed.
auth/index.js
var passport = require('passport');
var FacebookStrategy = require('passport-facebook').Strategy;
var User = require('../modules/user');
module.exports = function(){
passport.use( new FacebookStrategy({
clientID: "secret",
clientSecret : "secret",
callbackURL : "secret"
},
function(accessToken, refreshToken, profile, done) {
User.findOne({ email: profile.emails[0].value }, function (err, user) {
if (err) { return done(err) }
if (!user) {
user = new User({
firstname: profile.name.givenName,
lastname: profile.name.familyName,
email: profile.emails[0].value,
providers: {
facebook: {
id: profile.id,
access_token: accessTOken,
display_name: displayName,
picture: "http://graph.facebook.com/"+profile.id+"/picture?type=square"
}
}
})
user.save(function (err) {
if (err) console.log(err)
return done(err, user)
})
}
else {
return done(err, user)
}
})
}
));
};
routes/auth.js
var express = require('express');
var router = express.Router();
var passport = require('passport');
router.get('/facebook', passport.authenticate('facebook'), function(res, res){});
router.get('/facebook/callback', passport.authenticate('facebook'), function(res, res){});
module.exports = router;
app.js
const express = require('express');
const path = require('path');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const passport = require('passport');
const auth = require('./routes/auth');
const app = express();
mongoose.connect('mongodb://localhost:auth/auth');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(passport.initialize());
app.use('/auth', auth);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.json({
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.json({
message: err.message,
error: {}
});
});
module.exports = app;
SOLUTION:
As suggested, I just add this line before app.use(passport.initialize());
app.js
require('./auth')(passport);
SOLUTION:
As suggested, I just add this line before app.use(passport.initialize());
app.js
require('./auth')(passport);
Related
many hours spent on reading books, passport.org and similar issues in stackoverflow. However, still had no clue why login failed using passport to authenticate with simple local strategy of username and password. passport.autheticate came back stating with info="missing credential" and user='false".
before stepping into passport.authenticate, confirmed that req.body had the right user info of username and password from Angular.
Besides, user registration using passport worked, however, using same username and password was not able to log in.
Below pls find code and thanks for any help in advance.
App.js (code associated with user registration and login)
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var logger = require('morgan');
var session = require('express-session');
var FileStore = require('session-file-store')(session);
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var authenticate = require('./lib-general/authenticate');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var User = require('./model/user');
var app = express();
const util = require('util');
var debug = require('debug')('http'),
http = require('http'),
name ='pIn3-server';
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use( bodyParser.urlencoded({ extended: true }) );
app.use(session({
name: 'session-id',
secret: config.secretKey,
saveUninitialized: false,
resave: false,
store: new FileStore()
}));
app.use(passport.initialize());
app.use(passport.session());
app.use('/', indexRouter);
app.use('/', usersRouter);
authenticate.js
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var User = require('../model/user');
var JwtStrategy = require('passport-jwt').Strategy;
var ExtractJwt = require('passport-jwt').ExtractJwt;
var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
var config = require('../config.js');
passport.use(new LocalStrategy(User.authenticate(),{passReqToCallback : true}));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
console.log("before getToken");
exports.getToken = function(user) {
return jwt.sign(user, config.secretKey,
{expiresIn: 3600});
};
var opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
console.log("after jwtFromRequest - extract JWT");
console.log(opts.jwtFromRequest);
opts.secretOrKey = config.secretKey;
console.log("after secretOrKey");
console.log(opts.secretOrKey);
exports.jwtPassport = passport.use(new JwtStrategy(opts,
(jwt_payload, done) => {
console.log("JWT payload: ", jwt_payload);
User.findOne({_id: jwt_payload._id}, (err, user) => {
if (err) {
return done(err, false);
}
else if (user) {
return done(null, user);
}
else {
return done(null, false);
}
});
}));
exports.verifyUser = passport.authenticate('jwt', {session: false});
Users.js (user router)
var express = require('express');
const bodyParser = require('body-parser');
var User = require('../model/user');
var passport = require('passport');
var authenticateMy = require('../lib-general/authenticate'); // use my to distinguish from passport authenticate
var LocalStrategy = require('passport-local').Strategy;
var cors = require('./cors');
var userRouter = express.Router();
userRouter.use(bodyParser.json());
const mongoose = require('mongoose');
const mongooseClient = require('mongoose'); /* this is important */
console.log("step into router users");
/*ensure if it from right port of whitelist in cors:3000, 3443, 4200 */
userRouter.options('*', cors.corsWithOptions, (req, res) => { res.sendStatus(200); } )
/* Get users listing. */
userRouter.get('/',cors.cors,function(req,res,next){
res.send('respond with a resource')
});
userRouter.post('/signup', cors.corsWithOptions,(req, res, next) => {
console.log('2.0.0.1 - at register',req.body);
let newUser = new User( {
_id: new mongoose.Types.ObjectId(),
username: req.body.username,
password: req.body.password,
firstName: req.body.firstName,
lastName: req.body.lastName,
role: req.body.role,
remember: req.body.remember }); // from book
User.register(newUser, req.body.password, (err, user) => {
if(err) {
console.log('2.0.0.2 - at register',err,user);
res.statusCode = 500;
res.setHeader('Content-Type', 'application/json');
res.json({err: err});
}
else {
console.log('2.0.1 - at register',req.body);
user.save((err, user) => {
if (err) {
res.statusCode = 500;
res.setHeader('Content-Type', 'application/json');
res.json({err: err});
return ;
}
passport.authenticate('local')(req, res, () => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json({success: true, status: 'Registration Successful!'});
});
});
}
});
});
userRouter.post('/login', cors.corsWithOptions, (req, res, next) => {
console.log('2.0.4 - at login',req.body);
passport.authenticate('local', (err, user , info) => {
console.log('2.0.5 - at login', user, info);
if (err)
return next(err);
if (!user) {
res.statusCode = 401;
res.setHeader('Content-Type', 'application/json');
res.json({success: false, status: 'Login Unsuccessful!', err: info});
}
req.logIn(user, (err) => {
if (err) {
console.log('2.0.6 - at req.login',user);
res.statusCode = 401;
res.setHeader('Content-Type', 'application/json');
res.json({success: false, status: 'Login Unsuccessful!', err: 'Could not log in user!'});
}
var token = authenticateMy.getToken({_id: req.user._id});
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json({success: true, status: 'Login Successful!', token: token});
});
}) (req, res, next);
});
userRouter.get('/logout', (req, res) => {
console.log('in userRouter logout code')
if (req.session) {
req.session.destroy();
res.clearCookie('session-id');
res.redirect('/');
}
else {
console.log('in userRouter log out ')
var err = new Error('You are not logged in!');
err.status = 403;
next(err);
}
});
I try to create an authentification api with Express, Passport, Jwt, passport local, and Mariadb.
I don't need User model, but would like to use sql call.
I follow some tutorials : tuto1 tuto2 tuto3
But I always get 404 error (POST request) with curl and postman.
I don't know where is the issue.
app.js
var express = require('express');
var logger = require('morgan');
var path = require('path');
var _ = require("lodash");
var favicon = require('serve-favicon');
var app = express();
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/routes')
var passport = require("passport");
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(passport.initialize());
app.use('/', routes);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.json({ error: err });
});
module.exports = app;
passport.js
var passport = require('passport');
var passportJWT = require("passport-jwt");
var ExtractJWT = passportJWT.ExtractJwt;
var LocalStrategy = require('passport-local').Strategy;
var JWTStrategy = passportJWT.Strategy;
var connection = require('./database');
var sodium = require('./sodium');
passport.use('local-signin', new LocalStrategy({
usernameField: 'username',
passwordField: 'password'
} , function (req, username, password, done){
if(!username || !password ) {
return done(null, false);
}
connection.query("select * from users where username = ?", [username],
function(err, rows){
console.log(err);
console.log(rows);
if (err)
return done(null, error);
if(!rows.length){
return done(null, false);
}
var dbpassword = rows[0].password;
if(sodium.password_check(dbpassword, password) == false){
return done(null, false);
}
return done(null, rows[0]);
});
})
);
passport.use(new JWTStrategy({
jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(),
secretOrKey : 'your_jwt_secret'
},
function (jwtPayload, cb) {
connection.query("select * from users where id = ?", [jwtPayload.id],
function(err, rows){
console.log(err);
console.log(rows);
if (err)
return done(null, error);
if(!rows.length){
return done(null, false);
}
var dbpassword = rows[0].password;
if(sodium.password_check(dbpassword, password) == false){
return done(null, false);
}
return done(null, rows[0]);
});
}
));
module.exports = passport ;
routes.js
var express = require('express');
var router = express.Router();
const jwt = require('jsonwebtoken');
const passport = require('passport');
router.post('/', function (req, res, next) {
passport.authenticate('local-signin', {session: false}, (err, user, info) => {
if (err || !user) {
return res.status(400).json({
message: 'Something is not right',
user : user
});
}
req.login(user, {session: false}, (err) => {
if (err) {
res.send(err);
}
const token = jwt.sign(user, 'my_secret');
return res.json({user, token});
});
})
(req, res);
});
module.exports = router ;
Thanks for help !
passport.use('local-signin',
passport.authenticate('local',
Could this inconsistency be an issue?
I try to implement a register on my web app, using Node JS and Passport.js for local authentication, but I have this error when I Post the request on Insomnia (Like Postman) :
Bad Request
I don't understand because I have follow a tutorial that I find on Google to do this.
Here is the route (auth.js):
const passport = require('passport');
const router = require('express').Router();
//const UserController = require('../controller/UserController');
router
// login
.post("/login", passport.authenticate("local", function(req, res, next) {
console.log(req);
}))
// logout
.get('/logout', (req, res, next) => {
req.session.destroy((err) => {
res.redirect('/login')
})
})
// signup
.post("/signup", passport.authenticate("local-register"), (req, res) => {
var userInfo = req.body;
})
module.exports = router;
Here is Passport.js file :
const bcrypt = require('bcrypt-nodejs');
const db = require("./queries");
const passport = require('passport');
const LocalStrategy = require("passport-local").Strategy
passport.use(new LocalStrategy(authenticate))
passport.use("local-register", new LocalStrategy({passReqToCallback: false}, register))
function authenticate(email, password, done) {
db.one('select * from users where email = $1', email)
.then((user) => {
if(!user || !bcrypt.compareSync(password, user.password)) {
return done(null, false, {message: "invalid user and password combination"});
}
done(null, user)
}, done);
}
function register(email, password, done) {
db.one('select * from users where email = $1', email)
.then((user) => {
if(user) {
return done(null, false, {message: "An user with this address have already been created."});
}
const newUser = {
email: email,
password: bcrypt.hashSync(password),
};
db.none('insert into users(email, password) values($1, $2)', [newUser.email, newUser.password])
.then((ids) => {
newUser.id = ids[0]
done(null, newUser)
})
})
}
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
db.one('select * from users where id = $1', id)
.then((user) => {
done(null, user)
}, done);
});
I'm using Postgresql as DB for this project, with pg-promise package.
And this is the app.js file :
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var session = require('express-session');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var passport = require('passport')
require('./passport');
var index = require('./routes/index');
var usersRoutes = require('./routes/users');
var authRoutes = require('./routes/auth');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(passport.initialize())
app.use(passport.session())
app.use('/', index);
app.use(usersRoutes);
app.use(authRoutes);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Doest anyone know why I have this response ? I try with a post method using email and password on Insomnia,
Thank you !
By default, LocalStrategy expects to find credentials in parameters named username and password. (passport-local on Github).
So you need to edit this line and set usernameField to email
passport.use("local-register", new LocalStrategy({passReqToCallback: false, usernameField: 'email'}, register))
In your passport.js file on line 4, ensure you end your line ;
const LocalStrategy = require('passport-local');
You can authenticate your details individually as well
passport.use(new LocalStrategy((email, password, done) => {
User.getUserByEmail(email, (err, email) => {
if(err) throw err;
if(!email){
return done(null, false, {message: 'Incorrect Username/Email'});
}
User.comparePassword(password, user.password, (err, isMatch)=>{
if(err) return done(err);
if(isMatch){
return done(null, email);
} else {
return done(null, false, {message: 'Invalid Password'});
}
});
})
}));
Try to stick to one way of writing your code, either ES6 or ES5. And when using ES6, I will advise you use 'use strict' to help you thoroughly check your codes for error.
I saw a couple of post with similar to mine but I still getting the same error
here is my user schema
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
var userSchema = mongoose.Schema({
local: {
email: String,
password: String,
},
});
userSchema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
userSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.local.password);
};
module.exports = mongoose.model('User', userSchema);
my routes
var express = require('express');
var passport = require('passport');
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/login', function(req, res, next) {
res.render('login.ejs', { message: req.flash('loginMessage') });
});
router.get('/signup', function(req, res) {
res.render('signup.ejs', { message: req.flash('loginMessage') });
});
router.get('/profile', isLoggedIn, function(req, res) {
res.render('profile.ejs', { user: req.user });
});
router.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
router.post('/signup', passport.authenticate('local-signup', {
successRedirect: '/profile',
failureRedirect: '/signup',
failureFlash: true,
}));
router.post('/login', passport.authenticate('local-login', {
successRedirect: '/profile',
failureRedirect: '/login',
failureFlash: true,
}));
module.exports = router;
function isLoggedIn(req, res, next) {
if (req.isAuthenticated())
return next();
res.redirect('/');
}
my app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongoose = require('mongoose');
var flash = require('connect-flash');
var session = require('express-session');
var routes = require('./routes/index');
var users = require('./routes/users');
var configDB = require('./config/database.js');
mongoose.connect(configDB.url);
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({ secret: 'shhsecret' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
require('./config/passport')(passport);
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
And here is my passport.js Im using local passport
var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/user');
module.exports = function(passport) {
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) {
process.nextTick(function() {
User.findOne({ 'local.email': email }, function(err, user) {
if (err)
return done(err);
if (user) {
return done(null, false, req.flash('signupMessage', 'That email is already in use.'));
} else {
var newUser = new User();
newUser.local.email = email;
newUser.local.password = newUser.generateHash(password);
newUser.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
}
});
});
}));
passport.use('local-login', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true,
},
function(req, email, password, done) {
User.findOne({ 'local.email': email }, function(err, user) {
if (err)
return done(err);
if (!user)
return done(null, false, req.flash('loginMessage', 'No user found.'));
if (!user.validPassword(password))
return done(null, false, req.flash('loginMessage', 'Wrong password.'));
return done(null, user);
});
}));
};
passport works it save the user to the database
expressauth 5 > db.users.find()
{ "_id" : ObjectId("586cc8b3ea780c071bbe2469"), "local" : { "password" : "$2a$08$vANw7GJIk8RUVEpJWnwSpOVQ77RuHCjbXiGoQVl.Fx/thhbMkEVWu", "email" : "david#david.com" }, "__v" : 0 }
expressauth 6 >
Cast to ObjectId failed for value “586cc8b3ea780c071bbe2469” at path “_id” for model “User”
I have built a couple apps that use passport oauth the exact same way that I have displayed above. So I dont know why Im getting this error.
Any suggestions?
I had the same problem with mongoose version > 4.7.2
Problem is about bson package.
I solved it with installing an older version of mongoose.
npm install mongoose#4.7.2
or you can change package.json to use exact version 4.7.2 "mongoose": "4.7.2"
You can update to newer versions after the problem is solved. You can track it on here.
The error exists in your serializeUser function in passport.
You need to use user._id instead of user.id.
since there is no field as id in your UserSchema, user.id will beundefined, and while deserializing the user, undefined is not typeOf ObjectId, thus it is throwing above error.
Try this:
passport.serializeUser(function(user, done) {
done(null, user._id);
});
Update:
Do this in your deserializeUser:
cast the upcoming id to ObjectId, just to be sure, and then use that ID to query the User.
var userId = mongoose.Schema.Types.ObjectId(id);
User.findById(userId , function(err, user) {
done(err, user);
});
Dont forget to include mongoose in the same file.
var mongoose=require('mongoose');
Hopefully this will help you.
This is due to latest version of mongoose, you have to use findOneAndRemove instead of FindByIdAndRemove.
That is cast objectId problem.
I am using passport local for authentication and the login credentials don't get authenticated. I just get redirected to the failureRedirect. I don't even get the flash error.
Here is my login route:
var express = require('express');
var router = express.Router();
var passport = require('passport');
var flash = require('connect-flash');
router.get('/', function(req, res, next) {
if(req.user){
return res.redirect('/profile');
}
var vm = {
title: 'Login',
error: req.flash('error')
};
res.render('login', { title: 'Place an order' });
});
router.post('/',
passport.authenticate('local', {
failureRedirect: '/login',
successRedirect: '/profile',
failureFlash: 'Invalid credentials'
}));
module.exports = router;
This is app.js:
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var passport = require('passport');
var expressSession = require('express-session');
var flash = require('connect-flash');
var config = require('./config');
var routes = require('./routes/index');
var signup = require('./routes/signup');
var login = require('./routes/login');
var profile = require('./routes/profile');
var restrict = require('./auth/restrict');
var passportConfig = require('./auth/passport-config');
passportConfig();
mongoose.connect(config.mongoUri);
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(expressSession({
secret: 'themsec',
saveUninitialized: false,
resave: false
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use('/', routes);
app.use('/signup', signup);
app.use('/login', login);
//app.use(restrict);
app.use('/profile', profile);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
Passport-config:
module.exports = function(){
var passport = require('passport');
var passportLocal = require('passport-local');
var userService = require('../services/user-service');
passport.use(new passportLocal.Strategy({username: 'email'},function(email, password, next){
userService.findUser(email, function(err, user){
if(err){
return next(err);
}
if(!user || user.password!= password){
return next(null, null);
}
next(null, user);
});
}));
passport.serializeUser(function(user, next){
next(null, user.email);
});
passport.deserializeUser(function(email, next){
userService.findUser(email, function(err, user){
next(err, user);
});
});
};
User services:
var User = require('../models/user').User;
exports.addUser = function(user, next){
var newUser = new User({
firstName: user.firstName,
lastName: user.lastName,
email:user.email.toLowerCase(),
password: user.password,
});
newUser.save(function(err){
if(err)
return next(err)
next(null);
});
};
exports.findUser = function(email, next){
User.findOne({email:email.toLowerCase()}, function(err, user){
next(err, user)
});
};
User model:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userService = require('../services/user-service');
var userSchema = new Schema({
firstName: {type: String, required: true},
lastName: String,
email: {type: String, required: true},
password: {type: String, required: true},
created: {type: Date, default: Date.now}
});
userSchema.path('email').validate(function(value, next){
userService.findUser(value, function(err, user){
if(err){
console.log(err);
return false;
}
next(!user)
});
}, 'That email is already in use');
var User = mongoose.model('User', userSchema);
module.exports = {
User:User
};
Someone please help me, I am turning mad with frustration. I am new to Node.
Edit: I have removed the code that would lead to an infinite loop if the user logged-in, however, I still cannot login.