jaredhanson / passport-local

Username and password authentication strategy for Passport and Node.js.
https://www.passportjs.org/packages/passport-local/?utm_source=github&utm_medium=referral&utm_campaign=passport-local&utm_content=about
MIT License
2.73k stars 498 forks source link

Another~Another only missing credentials problem:D #163

Open JonathanSum opened 6 years ago

JonathanSum commented 6 years ago

Is this part, which in the passport.js, wrong?

 router.post('/login', function(req, res, next) {
   passport.authenticate('local', {
     sucessRedirect: '/',
     failureRedirect: '/users/login',
     failureFlash: true
   })(req, res, next)
 })

passport.js

const LocalStrategy = require('passport-local').Strategy;
const User = require('../models/user')
const config = require('../config/database');
const bcrypt = require('bcryptjs')

module.exports = function(passport) {
  // Local Strategy
  passport.use(new LocalStrategy(function(username, password, done) {
    //Match Username
    let query = {
      username: username
    };
    User.findOne(query, function(err, user) {
      if (err) throw err;
      if (!user) {
        return done(null, false, {
          message: 'No User Found'
        })
      }

      //Match Password
      bcrypt.compare(password, user.password, function(err, isMatch) {
        if (err) throw err;
        if (isMatch) {
          return done(null, user);

        } else {
          return done(null, false, {
            message: 'Wrong password'
          })
        }
      });

      passport.serializeUser(function(user, done) {
        done(null, user.id);
      });

      passport.deserializeUser(function(id, done) {
        User.findById(id, function(err, user) {
          done(err, user);
        });
      });
    })

  }))
}

user.js

const express = require('express')
const router = express.Router();
const bcrypt = require('bcryptjs')
const passport = require('passport')

let User = require('../models/user')

// Register form
router.get('/register', (req, res) => {
  res.render('register');
});
//Login Redirect Page
// router.post('/register', function(req, res) {
//
//     }

//REGISTER Proccess
router.post('/register', function(req, res) {
  const name = req.body.name;
  const email = req.body.email;
  const username = req.body.username;
  const password = req.body.password;
  const password2 = req.body.password2;

  req.checkBody('name', 'Name is required').notEmpty();
  req.checkBody('email', 'Email is required').notEmpty();
  req.checkBody('email', 'Email is not valid').isEmail();
  req.checkBody('username', 'Username is required').notEmpty();
  req.checkBody('password', 'Password is required').notEmpty();
  req.checkBody('password2', 'Password do not match').equals(req.body.password);
  let errors = req.validationErrors();

  if (errors) {
    res.render('register', {
      errors: errors
    })
  } else {
    let newUser = new User({
      name: name,
      email: email,
      username: username,
      password: password
    })

    bcrypt.genSalt(10, function(err, salt) {
      bcrypt.hash(newUser.password, salt, function(err, hash) {
        if (err) {
          console.log(err);
        }
        newUser.password = hash;
        newUser.save(function(err) {
          if (err) {
            console.log(err);
            return;
          } else {
            req.flash('success', 'You are Now registered and can log in');
            res.redirect('/users/login');
          }
        })
      });
    })
  }
})

//Form of Login
router.get('/login', function(req, res) {
  res.render('login');
})

//Login Proccess
//router.post('/login',passport.authenticate('local', { successRedirect: '/',
//                                   failureRedirect: '/users/login',
//                                   failureFlash: true })
//);

 router.post('/login', function(req, res, next) {
   passport.authenticate('local', {
     sucessRedirect: '/',
     failureRedirect: '/users/login',
     failureFlash: true
   })(req, res, next)
 })
module.exports = router;

app.js


const express = require('express');
const path = require('path')
const mongoose = require('mongoose');
const bodyParser = require('body-parser')
const expressValidator = require('express-validator');
const flash = require('connect-flash')
const session = require('express-session')
const passport = require('passport');
const config = require('./config/database')

//init libraries
mongoose.Promise = global.Promise;
var promise = mongoose.connect((config.database), {
  useMongoClient: true,
});
let db = mongoose.connection;
// mongoose.Promise = global.Promise;
// mongoose.connect('mongodb://10.7.0.3:27107/data/db');

//Check connection
db.once('open', function() {
  console.log('Connected to MongoDB')
})

//Check for DB errors
db.on('error', function(err) {
  console.log(err)
})

//init app
const app = express();

//Bring in Models
let Article = require('./models/article')

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
  extended: false
}))

// parse application/json
app.use(bodyParser.json())

//Set Public Folder
app.use(express.static(path.join(__dirname, 'public')))

//Express Session MiddleWare
app.use(session({
  secret: 'keyboard cat',
  resave: true,
  saveUninitialized: true,
  cookie: {}
}))

//EXpress Message Middleware
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 View Engine
// let Article = require('../models/article')
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// Home Route
app.get('/', function(req, res) {
  Article.find({}, function(err, articles) {
    if (err) {
      console.log(err);
    } else {
      res.render('index', {
        title: "Blog",
        articles: articles
      })
    }
  })
})

//Route Files
let articles = require('./routes/articles');
// let users = require('.routes/users');
let users = require('./routes/users');
app.use('/users', users)
app.use('/articles', articles)

// Start Server
app.listen(3000, function(req, res) {
  console.log("it is on 3000 now")

})

One more thing, this database.js file is in the config folder what des the variable secret for? People say it can be anything. database.js

module.exports = {
  database: 'mongodb://localhost:27017/nodekb',
  secret: 'anything'
}
MauriceMorrey commented 4 years ago

Were you ever able to fix this?

ghost commented 4 years ago

Another one banging the head against the wall...

JonathanSum commented 4 years ago

Good Question! @MauriceMorrey @Croma1994 I remember I fix it. But if you look at the date, do you still remember how to fix it if it is you? But don't worry! The solution must be in my GitHub repo because I usually upload almost everything I do. So the solution so far is to find the same piece of code in my Github, and you will see a fixed solution.

So far I don't want to spend too much time finding it on my repo, but if we have too many people have this issue, I may find it, test it, and debug it.

So far I don't want to spend too much time on Web things but in Deep Learning.

Satou_456 copy

ghost commented 4 years ago

So far, in my case was just passing this into the local strategy because I had custom named fields...

    {
      usernameField: "name",
      passwordField: "password",
      passReqToCallback: true,
    }
JonathanSum commented 4 years ago

@Croma1994 does it work? If it works, it is great.

ghost commented 4 years ago

@JonathanSum Yep! I had a misconception, thought that the local strategy function searched automatically for the req.body payloads no matter what name attribute they had, but you have to pass that object specifying the name and passing the req to the callback in order to use flash messages.

sourav-besra-vst-au4 commented 4 years ago

Didn't work for me, i have been banging my head for 3 days? Any fix guys?

JonathanSum commented 4 years ago

Yeah. Another one has the same issue. Welcome on board. image

jefflaub12 commented 4 years ago

Also same issue Missing credentials

passport.use('local.signup', new LocalStrategy({ usernameField: 'email', passwordField: 'passwd', passReqToCallback: true }, function(req, username, password, done) { req.check('email', 'Invalid Email').notEmpty().isEmail(); req.check('password', 'Your password must be at least 5 characters').notEmpty().isLength({min:5}); var errors = validationErrors();

Which I followed from http://www.passportjs.org/docs/username-password/

MauriceMorrey commented 4 years ago

I don't quite remember the fix but it had something to do with passing parameters named differently; in the documentation link @jefflaub12 shared, it says;

"By default, LocalStrategy expects to find credentials in parameters named username and password. If your site prefers to name these fields differently, options are available to change the defaults."

I know it says you have the option to change defaults but if I remember correctly, using the defaults fixed the issue for me.

Good luck.

jefflaub12 commented 4 years ago

That did it used the defaults instead of attempting to rename the variable for usernameField. Thanks