Sunday, October 1, 2017

Node JS Passport - 400 Bad request for register

Leave a Comment

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 !

2 Answers

Answers 1

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)) 

Answers 2

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.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment