Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Why isAuthenticated() Function In JavaScript App Always Returns False in express-passport?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 86
    Answer it

    The req.isAuthenticated() function of api.js always returns false regardless whether the user is logged in or not. This particular function doesn't seem to work.
    I don't know what to do. I am stuck on this for a long time.

     

    I tried many solutions like adding cookies (which as far as I gathered from other forums is the reason why req.isAuthenticated() doesn't work), explicitly calling logIn (though passport.authenticate in authenticate.js calls it by default) and some other small remedies like changing the order of my middlewares but nothing is working.

    Any help is highly appreciated.

     

    I am testing my code on advanced rest client.

     

    app.js (main file):

    var http_errors = require('http-errors');
        var express = require('express');
        var path = require('path');
        var favicon = require('serve-favicon');
        var logger = require('morgan');
        var passport = require('passport');
        var session = require('express-session');
        var cookieParser = require('cookie-parser');
        var bodyParser = require('body-parser');
        
        var api = require('./routes/api');
        var authenticate = require('./routes/authenticate')(passport);
        
        var app = express();
        
        app.use(cookieParser('super duper secret'));
        app.use(session({
            secret: 'super duper secret',
            resave: true,
            saveUninitialized: true
        }));
        app.use(logger('dev'));
        app.use(bodyParser.json());
        app.use(bodyParser.urlencoded({ extended: false }));
        app.use(express.static(path.join(__dirname, 'public')));
        app.use(passport.initialize());
        app.use(passport.session());
        
        // view engine setup
        app.set('views', path.join(__dirname, 'views'));
        app.set('view engine', 'ejs');
        
        app.use('/api', api);
        app.use('/auth', authenticate);
        
        //Initialize passport
        var initPassport = require('./passport-init');
        initPassport(passport);
        
        module.exports = app;
    

    Routing files:-

    api.js:

    var express = require('express');
      var router = express.Router();
     
      router.use(function(req, res, next){
       
        if(req.method === "GET"){
          //continue to the next middleware or request handler
          return next();
        }
       
        if (!req.isAuthenticated()){
          //user not authenticated, redirect to login page
          return res.redirect('/#login');
        }
       
        //user authenticated continue to next middleware or handler
        return next();
      });
     
      //api for all posts
      router.route('/posts')
     
        //returns all posts
        .get(function(req, res){
       
          //temporary solution
          res.send({message: 'TODO return all posts'});
        })
     
        //posts all posts
        .post(function(req, res){
       
          //temporary solution
          res.send({message: 'TODO create a new post'});
        })
     
      module.exports = router;

    authenticate.js:

    var express = require('express');
      var router = express.Router();
     
      module.exports = function(passport){
     
       //sends successful login state back to angular
       router.get('/success', function(req, res){
        res.send({state: 'success', user: req.user ? req.user : null});
       })
     
       //sends failure login state back to angular
       router.get('/failure', function(req, res){
        res.send({state: 'failure', user: null, message: "Invalid username or password"});
       })
     
       //log in
       router.post('/login', passport.authenticate('login', {
        successRedirect: '/auth/success',
        failureRedirect: '/auth/failure'
       }))
     
       //sign up
       router.post('/signup', passport.authenticate('signup', {
        successRedirect: '/auth/success',
        failureRedirect: '/auth/failure'
       }))
     
       //log out
       router.get('/signout', function(req, res) {
        req.logout();
        res.redirect('/');
       });
     
       return router;
      }

    passport-init.js (file that exploits passport module):   

     var LocalStrategy  = require('passport-local').Strategy;
      var bCrypt = require('bcrypt-nodejs');
      //temporary data store
      var users = {};
      module.exports = function(passport){
     
       // Passport needs to be able to serialize and deserialize users to support persistent login sessions
       passport.serializeUser(function(user, done) {
         
          //tell passport which id to use for user
        console.log('serializing user:',user.username)
        return done(null, user.username);
       })
     
       passport.deserializeUser(function(username, done) {
          User.findById(username, function(err, user){
        return done(err,users[username]);
          })
       })
     
       passport.use('login', new LocalStrategy({
         passReqToCallback : true
        },
        function(req, username, password, done) {
     
            if(!users[username]){
              return done('user not found',false);
            }
         
            if(!isValidPassword (users[username],password)){
              return done('invalid password', false);
            }
         
            console.log('sucessfully logged in')
         return done(null, users[username]);
        }
       ))
     
       passport.use('signup', new LocalStrategy({
         passReqToCallback : true // allows us to pass back the entire request to the callback
        },
        function(req, username, password, done) {
         
            if(users[username]){
              return done('username already taken', false);
            }
           
            users[username] = {
          username: username,
          password: createHash(password)
         }
         
            console.log('sucessfully signed in')
            console.log(users[username])
         return done(null, users[username]);
        }
       ))
     
        var isValidPassword = function(user, password){
        return bCrypt.compareSync(password, user.password);
       }
       
       var createHash = function(password){
        return bCrypt.hashSync(password, bCrypt.genSaltSync(10), null);
       }
      };
    
    
    

     

 0 Answer(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: