PassportJS req.isAuthenticated()返回false

时间:2018-07-16 12:49:16

标签: javascript node.js express passport.js express-session

我正在使用ExpressJS和PassportJS。我对req.isAuthenticated()总是返回false有问题。我想知道很多,也用谷歌搜索,我也访问了关于stackoverflow的其他相同问题,但是我没有解决我的问题。我不知道问题出在哪里,这对NodeJS也是新的。

我真的需要你们的帮助。在这里,我要打印代码。

app.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var logger = require('morgan');
var expressMessages = require('express-messages');
// var expressValidator = require('express-validator');
var flash = require('connect-flash');
var passport = require('passport')
  , LocalStrategy = require('passport-local').Strategy;
var passportHttp = require('passport-http')
var session = require('express-session');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/vidoff')
var db = mongoose.connection;


// Router
var indexRouter = require('./routes/index');
var postRouter = require('./routes/post');
var usersRouter = require('./routes/users');
var userRegisteration = require('./routes/userRegisteration');
var userLogin = require('./routes/userLogin');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname, 'public')));


app.use(session({
  secret: 'secrettexthere',
  saveUninitialized: true,
  resave: true
}));
 
app.use(passport.initialize());
app.use(passport.session());

app.use(require('connect-flash')());
app.use(function (req, res, next) {
  res.locals.messages = require('express-messages')(req, res);
  next();
});

// validator
// app.use(expressValidator);

// routes Use
app.use('/', indexRouter)
app.use('/post', postRouter);
app.use('/users', usersRouter);
app.use('/user', userRegisteration);
app.use('/user', userLogin);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// 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;

Controller> Login.js

var User = require('../models/user')
var passport = require('passport')
, LocalStrategy = require('passport-local').Strategy;
var passportHttp = require('passport-http')

exports.loginPage = function(req, res, next) {
    res.render('login', {title: 'Login'})
}

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

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

exports.authenticateMiddleware = passport.authenticate('local', {failureRedirect: '/user/login', failureFlash: true})

exports.authenticateSuccess =  function (req, res) {
    console.log('authenticated user: ', req.user)
    res.redirect('/post')
}

passport.use(new LocalStrategy(
    function(username, password, done) {
      User.findByUserName(username, function(err, user) {
       if (!user) {
           console.log('User not find: ', user)
           return done(null, false, {message: 'User not found'})
       } else {
            User.comparePassword(password, user.password, function(err, isMatch) {
                if (err) throw err;
                if (!isMatch) {
                    console.log('Invalid Password')
                    return done(null, false, {message: "Invalid Password"})
                } else {
                    return done(null, user)
                }
            })
        }
      });
    }
  ));
  

这是我要验证的文件,无论用户是否登录

var express = require('express');
var router = express.Router();
var ensureAuthentication = require('../controller/ensureAuthentication')

/* GET post page (localhost:8000/post). */
router.get('/', ensureAuthentication.apply, function(req, res, next) {
  res.render('post', { title: 'VidOff - User Home' });
});

module.exports = router;

最后是我的身份验证控制器

exports.apply = function ensureAuthentication (req, res, next) {
    console.log(req.isAuthenticated())  
    if (req.isAuthenticated()) {
        console.log('Authenticated')
        return next();
    } else {
        res.redirect('/user/login')
    }
}

0 个答案:

没有答案