Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Getting unauthorized user upon logging in with correct credentials #109

Open
rahil051 opened this issue Oct 26, 2015 · 5 comments
Open

Getting unauthorized user upon logging in with correct credentials #109

rahil051 opened this issue Oct 26, 2015 · 5 comments

Comments

@rahil051
Copy link

I am getting unauthorized error even if I enter the correct user credentials for logging in. And even if I register a new user and then it tries to log in the user afterwards, it always fails with an 'unauthorized' message. And there is also something weird about it, that when the first time I registered a user and logged him it, it was successful, the very next day it fails to login.

I am using ExpressJS 4.13.1 with mongoose + passport + passport-local + passport-local-mongoose

here is my mongoose model

// models/db.user.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');

var options = { collection: 'user' };

var UserSchema = new Schema({
    username: String,
    password: String,
    name: { title: String, first: String, last: String },
    email: String,
    contact: String,
    locality: String,
    userVerifyEmail: Number,
    passwordResetToken: String,
    authKey: String,
    updatedAt: Date,
    status: { type: Boolean, default: false }
}, options);

UserSchema.plugin(passportLocalMongoose);

mongoose.model('User', UserSchema);

registering it in the app.js

// app.js
// rest of the modules here...
var mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;

// made a mongodb connection with mongoose here...
// Register Mongoose Model
require('./models/db.user');

var app = express();

// rest of the code here...
// require and register routes to app instance here

app.use(passport.initialize());
app.use(passport.session());

var User = mongoose.model('User');
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

in my routes/index.js

var express  = require('express');
var router   = express.Router();
var mongoose = require('mongoose');
var passport = require('passport');
var User = mongoose.model('User');

router.route('/register')
.get(function(req, res) {
    res.render('register', { title: 'User Registration' });
})
.post(function(req, res, next) {
    var user = {
        username: req.body.username,
        email: req.body.email,
        contact: req.body.contact,
        locality: req.body.locality,
        updatedAt: Date.now(),
        status: true,
        name: { first: req.body.firstname, last: req.body.lastname, title: req.body.title }
    };
    User.register(new User(user), req.body.password, function(err, user) {
        if (err) {
            return res.render("register", {info: "Sorry. That username already exists. Try again."});
        }
        passport.authenticate('local')(req, res, function () {
            req.session.save(function (err) {
                if (err) {
                    return next(err);
                }
                res.redirect('/');
            });
        });
    });
});

router.route('/login')
    .get(function(req, res) {
        res.render('login', { user : req.user, title: 'User Login' });
    })
    .post(passport.authenticate('local'), function(req, res, next) {
        req.session.save(function (err) {
            if (err) {
                return next(err);
            }
            res.redirect('/profile/' + req.user.username);
        });
    });

module.exports = router;

Now the first time I had written the code, the login and registration system seemed to be working just fine, until I started again on the very next day.
I am using Windows 8.1 x64

@jontonsoup
Copy link

This has been happening with me sporadically as well in production. I've also noticed when I pull my production database down onto my local machine this happens.

@rahil051
Copy link
Author

I resolved it months ago by just removing Passport Local Mongoose package and rewriting my own authentication strategy. And by the way using this package was imposing some boundaries into my app, for example there was only an option for logging in with username, but not email and etc.

@rahil051 rahil051 reopened this Feb 10, 2016
@jaideepdasviadynamics
Copy link

I am facing this issue, my dev database is remote. Locally when I try to log in the first time it fails. subsequent time it works. it works fine on production.

@elsowiny
Copy link

Having the same issue in reverse, I.e in production does not work.

I am facing this issue, my dev database is remote. Locally when I try to log in the first time it fails. subsequent time it works. it works fine on production.

@nathnaeltk
Copy link

Facing the same issue and couldn't figure out why the issue even exists.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants