Cannot read property 'body' of null + passport.js - javascript

I'm trying to implement passport.js in a Node/Express/Sequelize app. I'm trying to stay as faithful as possible to both the official documentation and the Scotch.io tutorial, and currently have the following relevant code segments in my scaffolding:
app.js
const express = require('express');
const http = require('http');
const https = require('https');
const sequelize = require('sequelize');
const db = require('./config/sequelize');
const config = require('./config/config');
const passport = require('./config/passport');
const app = express();
const port = 3000;
app.use(passport.initialize());
app.use(passport.session());
app.set('view engine', 'ejs');
app.listen(port);
app.post('/signup', passport.authenticate('local', function(req, res, next, err){
if (err) { console.log(err); }
res.json(req.body);
}));
./config/passport.js
const db = require('./sequelize');
const passport = require('passport'),
LocalStrategy = require('passport-local').Strategy;
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(user, done) {
db.User.findById(id, function(err, user) {
done(err, user);
});
});
passport.use('local', new LocalStrategy({
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true
},
function(email, password, done){
process.nextTick(function() {
db.User.findOne({ email : 'local.email' }, function(err, user) {
if (err)
return done(err);
if (user) {
return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
}
else {
db.User.create({
username: 'local.email',
password: 'local.password'
});
}
});
});
}
));
module.exports = passport;
./views/signup.ejs
<!-- LOGIN FORM -->
<form action="/signup" method="post">
<div class="form-group">
<label>Email</label>
<input type="text" name="username">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password">
</div>
<button type="submit">Signup</button>
</form>
With this implementation in hand, I fire up the app, enter the email address and password to sign up on ./views/signup.ejs, and get the following error:
TypeError: Cannot read property 'body' of null
at C:\Users\Adam\Desktop\repos\chinese-democracy\app.js:45:15
at allFailed (C:\Users\Adam\Desktop\repos\chinese-democracy\node_modules\passport\lib\middleware\authenticate.js:94:18)
at attempt (C:\Users\Adam\Desktop\repos\chinese-democracy\node_modules\passport\lib\middleware\authenticate.js:167:28)
...
This indicates that req.body is being returned as null, and I have a suspicion it has to do with the manner in which the deserializeUser and serializeUser functions are defined in ./config/passport.js, but how can I get verbose error outputs to determine what the exact cause is? Also, I have done sanity CRUD checks with my Sequelize database so I omitted that file, but will provide it as an edit if any of you think that would be of use in resolving this issue.

Please try this in your app.js :
app.post('/signup', passport.authenticate('local'), function(req, res, next, err){
//^ close
// If this function gets called, authentication was successful.
res.redirect('/users/' + req.user.username);
});
If you need a custom callback:
app.post('/signup', function(req, res, next){
passport.authenticate('local', function(err, user, info) {
//Your code here
})(req, res, next);
});
Please refer to http://passportjs.org/docs/authenticate for more details.

Related

Passportjs Local authetication is not working properly

After implementing using passport-local not able to open profile page
I'm getting this below error
This page isn’t workinglocalhost redirected you too many times.
Try clearing your cookies.
ERR_TOO_MANY_REDIRECTS
passport-local-strategy.js
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const User = require('../models/user');
passport.use(new LocalStrategy({
usernameField: 'email'
},
function(email, password, done){
User.findOne({email: email}, function(err, user){
if(err){
console.log('Error in finding user --> Passport');
return done(err);
}
if(!user || user.password!=password){
console.log("Invalid username/password");
return done(null, false);
}
return done(null, user);
});
}
));
// serialize user function
passport.serializeUser(function(user, done){
done(null, user.id);
});
//deserialize the user fn
passport.deserializeUser(function(id, done){
User.findById(id, function(err, user){
if(err){
console.log("Error in finding user --> passport");
return done(err);
}
return done(null, user);
});
});
// check if user is authenticated
passport.checkAuthenticated = function(req, res, next){
if(req.isAuthenticated()){
return next();
}
// if the user is not signed in
return res.redirect('/users/sign-in');
}
passport.setAuthenticatedUser = function(req, res, next){
if(req.isAuthenticated()){
// req.user contains current signed in user data from the login page
res.locals.user = req.user;
}
next();
}
module.exports = passport;
users_controller.js
const User = require('../models/user')
module.exports.profile = function(req, res){
if(req.cookies.user_id){
User.findById(req.cookies.user_id, function(err, user){
if(user){
return res.render('profile',{
title:"Profile",
user:user
});
}
else{
return res.redirect('/users/sign-in')
}
})
}
else{
return res.redirect('/users/sign-in');
}
}
// render the sign up and in page
module.exports.signUp = function(req, res){
if(req.isAuthenticated()){
return res.redirect('/users/profile')
}
return res.render('user_sign_up', {
title: "Codeial | Sign Up"
})
}
module.exports.signIn = function(req, res){
if(req.isAuthenticated()){
return res.redirect('/users/profile')
}
return res.render('user_sign_in', {
title: "Codeial | Sign In"
})
}
// get the sign up data
module.exports.create = function(req, res){
if(req.body.password != req.body.confirm_password){
return res.redirect('back')
}
User.findOne({email:req.body.email}, function(err, user){
if(err){console.log('error in finding user in signing up'); return;}
if(!user){
User.create(req.body, function(err, user){
if(err){console.log('error in finding user in signing up'); return;}
return res.redirect('/users/sign-in')
})
}
else{
return res.redirect('back')
}
})
}
module.exports.createSession = function(req, res){
return res.redirect('/');
}
users.js
const express = require('express')
const router = express.Router();
const passport = require('passport');
const usersController = require('../controllers/users_controller');
router.get('/profile',passport.checkAuthenticated,usersController.profile)
router.get('/sign-up', usersController.signUp);
router.get('/sign-in', usersController.signIn);
// in above all codes after get('/sign-up') means when we type the keyword sign-up in the browser we need to render the folllowing page which is userController.signUp
// we are using users_controller.js file by importing
router.post('/create', usersController.create);
router.post('/create-session',passport.authenticate(
'local',
{failureRedirect: '/users/sign-in'},
),usersController.createSession);
// above line post create-session is forms action in user_sign_in.ejs file - when we submit the data of the form the post method is invoked
module.exports = router;
mongoose.js
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/codeial_development')
const db = mongoose.connection;
db.on('error', console.error.bind(console, "Error connecting to MongoDb"));
db.once('open', function(){
console.log('connected to the database :: MongoDB ')
})
module.exports = db;
index.js
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
const port = 8000;
const expressLayouts = require('express-ejs-layouts');
const db = require('./config/mongoose')
const session = require('express-session');
const passport = require('passport');
const passportLocal = require('./config/passport-local-strategy')
const MongoStore = require('connect-mongodb-session')(session)
app.use(express.urlencoded());
/* is a method inbuilt in express to recognize the incoming
Request Object as strings or arrays. This method is called as a
middleware in your application using the code*/
app.use(cookieParser());
app.use(express.static('./assets'));
app.use(expressLayouts);
// extact style and scripts from subpages into the layout
app.set('layout extractStyles', true)
app.set('layout extractScripts', true)
app.set('view engine', 'ejs');
app.set('views','./views')
app.use(session({
name: 'codeial',
secret:'blahsomeone',
saveUninitialized:false,
resave:false,
cookie:{
maxAge: (1000 * 60 * 100)
},
store: new MongoStore({
// mongooseConnection:db
mongoUrl: db._connectionString,
autoRemove: 'disabled'
}, function(err){
console.log(err || 'connect-mongo setup ok')
})
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(passport.setAuthenticatedUser);
// use express router
app.use('/', require('./routes'));
app.listen(port, function(err){
if(err){console.log(`Error running the server: ${err}`)};
console.log(`Server is running on port: ${port}`);
})
I'm not able to view profile page, its redirecting or getting this error
This page isn’t workinglocalhost redirected you too many times.
Try clearing your cookies.
ERR_TOO_MANY_REDIRECTS

Passport authentication works when login, but fails when register

I am learning passport.js and session, and am trying to add a local login feature to my website.
What I was trying to do is as follows:
Secret page: When users are authenticated, they can access to the secret page, otherwise they will be transfered to the login page.
Login page: If the username and password match, users are authenticated and are transfered to the secret page, otherwise they would be transfered back to the login page.
Register page: Users provide username and password, a new MongoDB document is created and stored in my database, meanwhile, the user is authenticated in this session and are transfered to the secret page.
My Problem:
Login page works fine: The authentication process in the login page works perfectly fine. When logined, a cookie is sent to the browser, the user is authenticated in this session and is successfully accessed to the secret page.
Register page data insert works fine: After register, the new password and username is successfully saved in the MongoDB database. User could login with this newly registered username.
Register page authentication failed: The register page, although using the same passport.authenticate() function, failed in the authentication process. I didn't get any error messages on my console, either.
I searched on Google and tried several methods of passport authentication, and they all worked very well on the 'login' POST Request, but failed on the 'register' POST Request.
I have read the documentation of passport-local and passport-local-mongoose. I have also tried this solution. But they all failed in the authentication process in the register page.
I use express-session, passport, passport-local-mongoose packages.
I'm wondering if my understanding of passport authentication is still lacking?
Thank you so much for your help and patience!
My Code:
EJS File - Register Page:
<!-- ... -->
<form action="/register" method="POST">
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" name="username">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" name="password">
</div>
<button type="submit" class="btn btn-dark">Register</button>
</form>
<!-- ... -->
JS File:
require('dotenv').config();
const express = require('express');
const app = express();
const port = 3000;
const ejs = require('ejs');
const session = require('express-session');
const passport = require('passport');
const passportLocalMongoose = require('passport-local-mongoose')
app.use(express.urlencoded({
extended: true
}));
app.use(express.static("public"));
app.set("view engine", "ejs");
//session and passport set up
app.use(session({
secret: process.env.SECRET,
resave: false,
saveUninitialized: true,
cookie: {
sameSite: 'lax'
},
}))
app.use(passport.initialize());
app.use(passport.session());
//user database set up ////////
const mongoose = require("mongoose");
main().catch(err => console.log(err));
async function main() {
await mongoose.connect('mongodb://localhost:27017/userDB');
}
const userSchema = new mongoose.Schema({
username: {
type: String,
unique: true
},
password: String
})
userSchema.plugin(passportLocalMongoose)
const User = mongoose.model("User", userSchema)
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
//user database set up end ///////
//GET Request
app.get("/", function(req, res) {
res.render("home");
})
app.get("/login", function(req, res) {
res.render("login");
})
app.get("/register", function(req, res) {
res.render("register");
})
//Secret Page ////////////////////////////////
app.get("/secrets", function(req, res) {
if (req.isAuthenticated()) {
res.render("secrets")
} else(
res.redirect("/login")
)
})
app.get('/logout', function(req, res) {
req.logout(function(err) {
if (err) {
console.log(err);
}
res.redirect('/');
});
});
//POST request
//Register POST Request ////////////////////////////////
app.post("/register", function(req, res) {
User.register(new User({
username: req.body.username
}), req.body.password,
function(err, user) {
if (err) {
console.log(err);
res.redirect('/register')
}
passport.authenticate('local'), function(req, res) {
res.redirect("/secrets");
}
}
)
})
app.post('/login', passport.authenticate('local', {
failureRedirect: '/login',
}), function(req, res) {
res.redirect("/secrets");
});
app.listen(port, function() {
console.log("start listening to port 3000")
})
I tried this answer by adding a parameter 'returnCode' to the call back of the passport authenticate function. Although the return code logged is 'undefined', the code successfully worked! I still don't know precisely why it worked simply by adding a parameter, but I think that's due to my lack of understanding of passport?
One thing I found very unhelpful is that the example page on the passport-local documentation is 404 not found. I wonder if there are any helpful examples I could find to study passport-local?
Here's my Code
app.post("/register", function(req, res) {
User.register(new User({
username: req.body.username
}), req.body.password,
function(err, user) {
if (err) {
console.log(err);
res.redirect('/register')
} else {
passport.authenticate('local', {})(req, res, function(returnCode) {
console.log(returnCode); //return: undefined
res.redirect('/secrets');
})
}
}
)
})

Passport.js signup appears to work but user credentials not inserted into database

Using Scotch.io and the official passport docs as reference, I'm implementing a Node/Express/Sequelize application where I have a basic signup form with fields for email and password:
./views/signup.ejs
<form action="/signup" method="post">
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" name="password">
</div>
<button type="submit" class="btn btn-warning btn-lg">Signup</button>
</form>
with the passport-local strategy defined as follows:
./config/passport.js
const db = require('./sequelize');
const passport = require('passport'),
LocalStrategy = require('passport-local').Strategy;
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(user, done) {
db.User.findById(id, function(err, user) {
done(err, user);
});
});
passport.use('local', new LocalStrategy({
emailField : 'email',
passwordField : 'password',
passReqToCallback : true
},
function(email, password, done){
process.nextTick(function() {
// find a user whose email is the same as the forms email
// we are checking to see if the user trying to login already exists
db.User.findOne({ email : email }, function(err, user) {
// if there are any errors, return the error
if (err)
return done(null, false, {message: err});
// check to see if theres already a user with that email
if (user) {
return done(null, false, {message: 'User already exists'});
}
else {
// if there is no user with that email
// create the user
db.User.create({
email: email,
password: password
});
return done(null, false, {message: 'User created'});
}
});
});
}
));
module.exports = passport;
and lastly the routes are taken care of in
app.js
const express = require('express');
const http = require('http');
const https = require('https');
const sequelize = require('sequelize');
const db = require('./config/sequelize');
const querystring = require('querystring');
const config = require('./config/config');
const passport = require('./config/passport');
const bodyParser = require( 'body-parser' );
const env = 'development';
const app = express();
const port = 3000;
app.use( bodyParser.urlencoded({ extended: true }) );
app.use(passport.initialize());
app.use(passport.session());
app.set('view engine', 'ejs');
app.listen(port);
app.post('/signup', function(req, res, next){
const user = req.body;
passport.authenticate('local', function(err, user, info){
if (err){
res.send({success: false, message: 'authentication failed'});
}
else{
console.log(info);
res.json({message: "success"});
}
})(req, res, next)
});
What I expect to happen if the local strategy works is for the res.json({message: "success"}) to appear on the browser and for the database to be updated per the specifications of ./config/passport.js. The {message: "success"} is appearing on the screen, but the database is not being updated, which leads me to believe that something is wrong with my implementation in ./config/passport.js. In app.js, the console.log(info) statement shows the following message on cmd:
Executing (default): SELECT `id`, `username`, `email`, `password`, `createdAt`,
`updatedAt` FROM `Users` AS `User` LIMIT 1;
which makes it look like the insertions might be going through but inspections of the db reveal otherwise. I have done previous sanity checks with CRUD updates to confirm that the basic implementation of Sequelize works, and will provide the schema of the table upon request. How else can I debug this situation?
Read about how to make queries in sequelize
http://docs.sequelizejs.com/en/latest/docs/querying/
you should use promises, like this:
db.User.findOne({ where: {email : email }})
.then(function(user){
//do smth;
})
.catch(function(error){
console.log(error);
});

Passport.js throwing "undefined is not a function" with LocalStrategy

I am implementing local authentication using Passport.js. I have already implemented Github Oauth, which is fine but for some reason the local strategy is failing with the above error. I cannot find any source of the issue so far. I have read other posts but the usual answer is that you should change the require statement to:
var LocalStrategy = require('passport-local').Strategy;
However, I have already done this. Any help would be much appreciated. Here are my files as it stands. I have omitted the github strategy code to focus on the problem strategy:
signin.html:
<div class="signin-bg">
<!-- <div class="modal fade" id="login-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;"> -->
<div class="modal-dialog">
<div class="loginmodal-container">
<h1>Login using Github</h1><br>
<i class="icon-github-sign"></i>
<h3>Or Use your Email</h3>
<form action="/signin" method="post">
<input type="text" name="username" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<input type="submit" name="login" class="login loginmodal-submit" value="Login">
</form>
<div class="login-help">
Register - Forgot Password
</div>
</div>
</div>
routes.js:
var User = require('./models/userModel');
var passport = require('passport');
var authStore = require('./config/authStore');
module.exports = function(app){
app.get('/signin', function(req, res, next){
res.render('signin', { message: req.flash('signinMessage') });
});
app.post('/signin', passport.authenticate('local', {
successRedirect: '/storyBoard',
failureRedirect: '/signin',
failureFlash: true
}));
app.get('/signup', function(req, res){
res.render('signup', { message: req.flash('signupMessage') });
});
app.post('/signup', passport.authenticate('local', {
successRedirect: '/signin',
failureRedirect: '/signup',
failureFlash: true
}));
function isLoggedIn(req, res, next) {
if(req.isAuthenticated()){
return next();
}
res.redirect('/#/signin');
}
};
passport.js
var User = require('../models/userModel.js');
var passport = require('passport');
var GithubStrategy = require('passport-github').Strategy;
var LocalStrategy = require('passport-local').Strategy;
var bcrypt = require('bcrypt');
module.exports = function(passport) {
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findUserByGithubId(id, function(err, user) {
user ? done(null, user) : done(err, null);
});
});
passport.use('local', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
},
function(req, email, password, done){
process.nextTick(function(){
User.findLocalUser(req.email, function(err, user){
if(err)
return done(err);
if(!user)
return done(null, false, req.flash('signinMessage', 'No user found'));
if(!User.generateHash(password)){
return done(null, false, req.flash('signinMessage', 'Invalid password'));
}
return done(null, user);
});
});
}
));
Well, i'm not sure what you are doing wrong exactly since you not paste all your code, but here is a express silly working sample with passport and connect flash, good luck.
var express = require('express');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var flash = require('connect-flash');
// You need session to use connect flash
var session = require('express-session');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use( session({
saveUninitialized : true,
secret : 'Some Secret' ,
resave : true,
}));
app.use( passport.initialize());
app.use( passport.session());
app.use(flash());
// Authentication
passport.use(
new LocalStrategy(
{},
function(username, password, done) {
// Fake user definition, just a sample.
var user = {name: 'fake', password: 'fake'};
// Here you can put your async authentication method from db
if(user.name === username && user.password === password) {
return done(null, {
username: username
});
}
else {
return done(null, false,{});
}
})
);
passport.serializeUser( function(user, done) {
return done(null, user);
});
passport.deserializeUser( function(user, done) {
return done(null, user);
});
app.get('/', function(req, res) {
var htmlToSend = '';
var error = req.flash('error')[0];
if(error)
htmlToSend += '<div style="background-color:red; width:30%;">' + error + '</div>';
htmlToSend += '<form action="/login" method="post"> \
<input name="username"/> \
<input type="password" name="password"/> \
<button> send \
</form>';
res.send(htmlToSend);
});
app.post('/login', passport.authenticate('local', {
failureRedirect: '/',
successFlash: 'Welcome!',
failureFlash: 'User/Password Invalid!'
}),
function(req, res) {
res.send('Loged In as '+ req.user.username);
});
app.listen(3000, function() {
console.log('started');
});

passportjs local strategy not getting called

I am using express and passport to build a rest api backend and it seems that my localStrategy is not getting called on request.
The entry point of my application looks like the following:
app.js
var fs = require('fs');
var express = require('express');
var mongoose = require('mongoose');
var passport = require('passport');
var config = require('./config/config');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.urlencoded({extended:true}));
app.use(passport.initialize());
//connect to mongodb
mongoose.connect(config.db, options);
//load models (shorten forEach)
...
require(__dirname + '/models/' + file)(mongoose);
//load passport config
require('./config/passport')(mongoose, passport);
//load routes
require('./config/routes')(app, passport);
//start server
var server = app.listen(3000, ....
routes.js
...
app.post('/auth', function(req, res){
console.log("reached auth endpoint");
console.log(req.body);
passport.authenticate('local', { session: false}, function(err, user, info){
console.log("Test:"+user);
if(err) {
console.log("Error1");
return next(err)}
if(!user){
console.log("Error2");
return res.json(401, {error: 'Auth Error!'});
}
console.log("Error3");
var token = jwt.encode({ username: user.email }, "hanswurst");
res.json({token: token});
}),
function(req, res){
console.log("passport user", req.user);
};
});
passport.js
...
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
},
function(email, password, done){
console.log("TEST");
User.findOne({'email': email}, function(err, user){
if(err){
console.log("Unknown error");
return done(err);
}
if(!user){
console.log("No User found");
return done(null, false);
}
if(!user.validPassword(password)){
console.log("Password was incorrect");
return done(null, false);
}
console.log("User was found");
return done(null, user);
});
}
));
The only result i get on form request is
reached auth endpoint
{ email: 'test#mail.com', password: 'secret' }
POST /auth - - ms - -
For me the request body looks fine and it should enter my LocalStrategy. I am bit helpless as i am not getting any other console output from this point.
First off, you have some basic javascript syntax errors in routes.js. This part right here (lots of code removed for clarity) is broken:
passport.authenticate(/*...*/), function(req, res) {/*..*/};
It might have been that you just added some console.log calls in the wrong place. To clear up the confusion, passport.authenticate() does not perform the authentication right away, what it does is return a middleware for you. You would use it like this for example :
var middleware = passport.authenticate(...);
app.post('/auth', middleware);
So to fix your problem, try invoking the middleware returned by authenticate right away, like this:
app.post('/auth', function(req, res, next) {
console.log("reached auth endpoint");
console.log(req.body);
passport.authenticate('local', {
session: false
}, function(err, user, info) {
console.log("Test:" + user);
if (err) {
console.log("Error1");
return next(err);
}
if (!user) {
console.log("Error2");
return res.json(401, {
error: 'Auth Error!'
});
}
console.log("Error3");
var token = jwt.encode({
username: user.email
}, "hanswurst");
res.json({
token: token
});
})(req, res, next);
});
Also, I have to tell you that require caches modules. To make config/passport.js aware of mongoose and passport, you should not feed them as parameters like this:
require('./config/passport')(mongoose, passport);
Simply require them again inside config/passport.js like so:
// (in config/passport.js)
// Both of these vars point to the same thing you require'd in app.js
var mongoose = require('mongoose');
var passport = require('passport');
[Edit] I Found the problem. Because Express is no longer supporting subpackages like body-parser etc, you need to set those separately. All would be well had I done that in the first place, but I only activated:
app.use(bodyParser.urlencoded({extended:true}));
You also need to set
app.use(bodyParser.json());
To get it to work properly. Stupid oversight but still, got me stumped for 3 days.
I Have the same problem, but nothing seems to work for me though.
I'll drop the code from the top down in execution order
jade template
.navbar-right(ng-controller="mvNavBarLoginCtrl")
form.navbar-form
.form-group
input.form-control(placeholder='Email', ng-model='username')
.form-group
input.form-control(type='password', placeholder='password', ng-model='password')
button.btn.btn-primary(ng-click="signIn(username,password)") Sign In
Next step Login controller
angular.module('app').controller('mvNavBarLoginCtrl',function($scope, $http){
$scope.signIn = function (username, password){
console.log('un = ' + username); // Prints fine in the console
console.log('pw = ' + password); // Prints fine in the console
$http.post('/login', {username: username, password: password}).then(function(response){
if(response.data.success){
console.log('Logged in!!');
}
else{
console.log('Failed to log in!!');
}
});
}
});
Next step Route handler
app.post('/login', function(req, res, next){
console.log(req.username); // Already empty
console.log(req.password); // Already empty
console.log(req.body); // Already empty
// Because of the use of AngularJS we can not call passport directly,
// missing req and res will break the code
var auth = passport.authenticate('local', function(err, user){
console.log(user); // prints undefined
if(err){return next(err);}
if(!user){res.send({success:false});}
req.logIn(user, function(err){
if(err){return next(err);}
res.send({success: true, user: user});
});
});
// call the auth function to start authenticate
auth(req, res, next);
});
Next step passport authentication handler
var User = mongoose.model('User');
passport.use(new LocalStrategy({
username: 'username',
password: 'password'
},
function(username, password, done){
console.log("called"); // never printed
// find user based in mongoose schema see 'var User'
User.findOne({userName:username}).exec(function (err,user){
console.log(user) // never printed
if(err){return done(err);}
if(user){
return done(null, user);
}
else{
return done(null, false);
}
});
}
));
passport.serializeUser(function(user, done){
if(user) {
done(null, user._id);
}
});
passport.deserializeUser(function(id, done){
user.findOne({_id:id}).exec(function(err, user){
if(user) {
done(null, user);
}
else{
done(null, false);
}
});
});
There are no errors not in the console and not as node output. I am stumped and read about 5 or so other thread with similar issues, nothing worked.
If somebody could give me the golden tip, I would be eternally gratefull.

Categories

Resources