question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Another~Another only missing credentials problem:D

See original GitHub issue

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'
}

Issue Analytics

  • State:open
  • Created 6 years ago
  • Comments:11

github_iconTop GitHub Comments

2reactions
sourav-besra-vst-au4commented, Aug 14, 2020

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

2reactions
ghostcommented, Jun 21, 2020

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,
    }
Read more comments on GitHub >

github_iconTop Results From Across the Web

What Does "Matching Credentials" Mean on Snapchat?
It appears that Snapchat has been locking individuals out of their accounts for *mostly* unknown reasons, which causes the "matching  ...
Read more >
Passport returning "missing credentials" error - Stack Overflow
I'm working on a password reset form so I'm only passing an email in my POST form. I'm getting a Missing credentials error...
Read more >
Credentials are missing - Forum - Foglight - Quest Community
Hi,. I'm testing the foglight enterprise and in optimization gives an error "Failed - Credentials are missing". I create a lockbox and then...
Read more >
Solved: Credentials are missing or not valid. inner except...
It seems that you are not providing the correct credentials. When creating the connection to SQL Server On-Premise, you will be asked to...
Read more >
How To FIX Snapchat "No Matching Credentials" Message!
GET SUPER CHEAP PHONES HERE: https://cheapphones.coGET AWESOME WALLPAPERS HERE: https://www.cheapphones.co/wallpapers/MY SECOND CHANNEL!
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found