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?
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 am trying to implement a simple user login and signup page for my application.
The signup page works and everything is getting stored in mongodb correctly. However, when I try to login it it does not seem to work. It is supposed to redirect to my root page but it will not do that. It always redirect back to /users/login
I've been going through a tutorial online so I do not understand why this isn't working. Here are the relevant files files.
user.js file
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const passport = require('passport');
let User = require('../models/user');
// Load register form
router.get('/register', function(req, res) {
res.render('register', {
title : 'Register',
errors : req.flash('success')
});
});
// Submit register form
router.post('/register', function(req, res) {
// Get the fields from the form
const firstname = req.body.firstname;
const lastname = req.body.lastname;
const email = req.body.email;
const pass = req.body.pass;
const pass2 = req.body.pass2;
// Verify body is not empty.
req.checkBody('firstname', 'First name is required').notEmpty();
req.checkBody('lastname', 'Last name is required').notEmpty();
req.checkBody('email', 'Email is required').notEmpty();
req.checkBody('email', 'Email is not valid').isEmail();
req.checkBody('pass', 'Password is required').notEmpty();
req.checkBody('pass2', 'Passwords do not match.').equals(req.body.pass);
// Check for errors
let errors = req.validationErrors();
if (errors) {
res.render('register', {
errors:errors
});
} else {
// Create new user object
let newUser = new User({
firstname:firstname,
lastname:lastname,
email:email,
pass:pass
});
// Hash the password for security.
bcrypt.genSalt(10, function(err, salt){
bcrypt.hash(newUser.pass, salt, function(err, hash) {
if (err) {
console.log(err);
}
newUser.pass = hash;
newUser.save(function(err) {
if (err) {
console.log(err);
return;
} else {
console.log("Successful creation.")
req.flash('success', 'Account creation successful!');
res.redirect('/users/login');
}
});
});
})
}
});
// Load login form
router.get('/login', function(req, res){
res.render('login');
});
// Submit login form
router.post('/login', function(req, res, next) {
passport.authenticate('local', {
successRedirect: '..',
failureRedirect: '/users/login',
failureFlash: true
})(req, res, next);
});
module.exports = router;
passport.js file
const LocalStrategy = require('passport-local').Strategy;
const passport = require('passport');
const User = require('../models/user');
const config = require('../config/database');
const bcrypt = require('bcryptjs');
// User Authentication
module.exports = function(passport){
console.log("Made it intro str");
passport.use(new LocalStrategy(function(email, pass, done){
// Match username
let query = {email:email};
User.findOne(query, function(error, user){
if (error){
console.log("error");
return done(error);
}
if (!user) {
console.log("No user found");
return done(null, false, {message: 'No user found.'});
}
bcrypt.compare(pass, user.pass, function(error, isMatch) {
if (error) {
console.log("error2");
return done(error);
}
if (isMatch) {
console.log("Matching password");
return done(null, user);
} else {
console.log("Wrong password");
return done(null, false, {message: 'Invalid password.'});
}
});
});
}));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
}
App.js
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const logger = require('morgan');
const session = require('express-session');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const expressValidator = require('express-validator');
const config = require('./config/database');
const flash = require('connect-flash');
const passport = require('passport');
/* Connect to Database */
mongoose.connect(config.database, { useNewUrlParser: true });
let db = mongoose.connection;
// Check connection.
db.once('open', function(){
console.log('Connected to MongoDB.');
})
// Check DB error.
db.on('error', function(error){
console.log(error);
});
/* Initialize app */
var app = express();
/* Bring in models for database */
let User = require('./models/user');
// Body Parser Middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Load the view engines
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// Set public folder
app.use(express.static(path.join(__dirname, 'public')));
app.use(expressValidator());
// Keep users session
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true,
cookie: { maxAge: 60000 }
}));
app.use(require('connect-flash')());
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
// Express Validator Middleware
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
};
}
}));
// Passport config
require('./config/passport')(passport);
app.use(passport.initialize());
app.use(passport.session());
// Load homepage
app.get('/', function(req, res) {
res.render('index', {
title: 'Index',
})
})
// Define routes
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/user');
app.use('/', indexRouter);
app.use('/users', usersRouter)
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// 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;
I believe the issue is in your passport.js file... By default, LocalStrategy expects to find credentials in parameters named username and password. You need to change that... something like so:
const localOptions = { usernameField: 'email', passwordField: 'pass' };
passport.use(new LocalStrategy(localOptions, function (email, pass, done) {
// Match username
let query = { email: email };
User.findOne(query, function (error, user) {
// etc etc...
});
}));
Link to the docs (at the bottom of the page...): http://www.passportjs.org/docs/username-password/
I'm a beginner in Angular 5 and I'm currently working on an app. So in login module, the passport local strategy is not working and passport.authenticate function is not working, and I can't seem to find the problem in my code.
Now I am not sure what is wrong because there is no error on the console and the return is null every time. That's why I'm copy pasting a lot of code.
Code is attached below.
Server.js file
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const http = require('http');
const cors = require('cors');
const app = express();
const cookieParser = require('cookie-parser');
const exphbs = require('express-handlebars');
const expressValidator = require('express-validator');
const flash = require('connect-flash');
const session = require('express-session');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
// API file for interacting with MongoDB
const api = require('./routes/api');
const auth = require('./routes/auth_companies');
require('./models/passport');
// Parsers/middlewares
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser());
app.use(flash());
// Angular DIST output folder
app.use(express.static(path.join(__dirname, 'dist')));
app.use(express.static('public'));
// API location
app.use('/api', api);
app.use('/auth', auth);
// 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 Vars
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();
});
// Send all other requests to the Angular app
//app.get('*', (req, res) => {
// res.sendFile(path.join(__dirname, 'dist/index.html'));
//});
// start the server
//app.listen(app.get('port'), () => {
// console.log('server on port 3000');
//});
//Set Port
const port = process.env.PORT || '3000';
app.set('port', port);
const server = http.createServer(app);
console.log(port);
server.listen(port, () => console.log(Running on localhost:${port}));
Passport.js file
const express = require('express');
const router = express.Router();
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const User = require ('./reg_company');
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(email, password, done) {
console.log('9900---------------------------------', email)
User.getUserByEmail(email, 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.use('local.signup' , new LocalStrategy ({
passReqToCallback : true ,
emailfield:'email',
passwordfield:'password'
}, function(req, email, password, done){
User.findOne({'email':email}, function(err, user){
if (err)
{
return done(err);
}
if (user)
{
return done (null, false);
}
const newCompany=new User();
newCompany.email = req.body.email;
newCompany.password = req.body.passport;
User.createUser(newCompany, function(err, user){
if(err) throw err;
console.log(user);
return done(null, user);
});
})
}) )
Mongo File
const mongoose = require('mongoose');
const uri='mongodb://localhost/tourhubdb';
mongoose.connect(uri);
const db=mongoose.connection;
const bcrypt = require('bcryptjs');
//tourist Schema
let company_reg_schema = mongoose.Schema({
email:{
type:String,
require:true
},
password:
{
type:String,
require:true
}
});
let User = module.exports = mongoose.model('companies',company_reg_schema);
module.exports.createUser = function(newUser, callback){
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(newUser.password, salt, function(err, hash) {
newUser.password = hash;
newUser.save(callback);
});
});
}
module.exports.getUserByEmail = function(email, callback){
var 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, function(err, isMatch) {
if(err) throw err;
callback(null, isMatch);
});
}
Routes file
const express = require("express");
const router = express.Router();
router.post('/login',function (req,res,next){
passport.authenticate('local-login', function (err ,user ,info){
})(req ,res ,next);
});
module.exports = router;
Just my two cents here...wherever you're returning done(null....) under
passport.use(), you could replace the null value with different errors for the different done() calls and see which one invokes and why.
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'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);