如何使用passportjs在nodejs中进行注册功能?

时间:2018-03-09 03:34:59

标签: node.js mongodb passport.js

我正在尝试在node.js中进行注册和登录应用。我使用passport.js进行身份验证。 我的主要问题是每当我提交包含有效表单数据的注册表单时,它会自动登录用户。其他功能正常工作。登录工作完美,但每当我提交注册表单时,它提交没有任何错误,并显示成功的消息。但主要的缺点是与singup一起它也记录了我不想要的用户。 这是我的代码

  

app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
const validator = require('express-validator');
const passport = require('passport');
const expressHbs = require('express-handlebars');
const flash = require('connect-flash');
const session = require('express-session');
const mongoose = require('mongoose');
const configDB = require('./config/database.js');


//db configuration
mongoose.connect(configDB.url, (err) => {
  if(err) {
    console.log('Error connecting to databse');
  } else {
    console.log('Connection Successful');
  }
});

require('./config/passport');


var index = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.engine('.hbs', expressHbs({defaultLayout: 'layout', extname: '.hbs'}));
app.set('view engine', '.hbs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(validator());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'node_modules')));

//required for passport
app.use(session({
  secret: 'mysecret',
  resave: false,
  saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());

app.use((req, res, next) => {
  res.locals.login = req.isAuthenticated();
  res.locals.session = req.session;
  next();
});

app.use('/users', users);
app.use('/', index);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

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

passport.js

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

passport.serializeUser((user, done) => {
    done(null, user.id);
});
passport.deserializeUser((id, done) => {
    User.findById(id, (err, user) => {
        done(err, user);
    });
});
passport.use('local-signup', new LocalStrategy({
    usernameField: 'email',
    passwordField: 'password',
    passReqToCallback: true
}, (req, email, password, done) => {
        var fullname = req.body.name;
        var address = req.body.address;
        req.checkBody('name', 'Name is Required').notEmpty();
        req.checkBody('email', 'Invalid email').notEmpty().isEmail();
        req.checkBody('password', 'Invalid password').notEmpty().isLength({ min: 4 });
        var errors = req.validationErrors();
        if (errors) {
            var messages = [];
            errors.forEach((error) => {
                messages.push(error.msg);
            });
            return done(null, false, req.flash('error', messages));
        }
        User.findOne({ 'email': email }, (err, user) => {
            if (err) {
                return done(err);
            }
            if (user) {
                return done(null, false, {message: 'That email is already taken.'});
            } else {
                var newUser = new User();
                newUser.fullname = fullname;
                newUser.email = email;
                newUser.password = newUser.encryptPassword(password);
                newUser.address = address;
                newUser.isAdmin = false;

                //saving the user
                newUser.save((err) => {
                    if (err) {
                        return done(err);
                    }
                    return done(null, newUser, req.flash('info', 'Signup Completed, pleases login to continue'));
                });
            }
        });
}));
passport.use('local-signin', new LocalStrategy({
    usernameField: 'email',
    passwordField: 'password',
    passReqToCallback: true
}, (req, email, password, done) =>{
        req.checkBody('email', 'Invalid email').notEmpty().isEmail();
        req.checkBody('password', 'Invalid password').notEmpty().isLength({ min: 4 });
        var errors = req.validationErrors();

        if (errors) {
            var messages = [];
            errors.forEach((error) => {
                messages.push(error.msg);
            });
            return done(null, false, req.flash('error', messages));
        }

        User.findOne({'email': email}, (err, user) => {
            if(err) {
                return done(err);
            }
            if(!user) {
                return done(null, false, {message: 'No User Found'});
            }
            if(!user.validPassword(password)) {
                return done(null, false, {message: "Wrong Password"});
            }
            return done(null, user);
        });
}));
  

user.js的

var express = require('express');
var router = express.Router();
const passport = require('passport');
const User = require('../models/user');

/* GET users listing. */
router.get('/admin/dashboard', isLoggedIn, isAdmin, (req, res) => {
    var user = req.user;
    User.find({}, (err, users) => {
      if(err) {
        throw err;
      } else {
        res.render('admin/dashboard', {
          successMsg: 'Hello' + ' ' + user.fullname,
          users: users
        });
      }
    });
});
//router.use('/', notLoggedIn, (req, res, next) => {
//  next();
//});

router.get('/login', (req, res) => {
  var messages = req.flash('error');
  var infoMsg = req.flash('info');
  res.render('users/login', { infoMsg: infoMsg, messages: messages, hasErrors: messages.length > 0 });
});
router.post('/login', passport.authenticate('local-signin', {// successRedirect: '/users/profile',
  failureRedirect: '/users/login',
  failureFlash: true
}), (req, res, next) => {
  user = req.user;
  role = user.isAdmin;
  if(role) {
    return res.redirect('/users/admin/dashboard');
  } else {
    return res.redirect('/users/profile');
  }
});

router.get('/signup', (req, res, next) => {
  var messages = req.flash('error');
  res.render('users/signup', { messages: messages, hasErrors: messages.length > 0 });
});
router.post('/signup', passport.authenticate('local-signup', {
  successRedirect: '/users/login',
  failureRedirect: '/users/signup',
  failureFlash: true
}));

router.get('/profile', isLoggedIn, (req, res) => {
  var user = req.user;
  var role = user.isAdmin;

  res.render('users/profile', {
    user: user,
    role: role,
    successMsg: 'Welcome' + ' ' + user.fullname 
  });
});

router.get('/logout', isLoggedIn, (req, res, next) => {
  req.logout();
  res.redirect('/users/login');
});

//route middleware to make sure a use is logged in
function isLoggedIn(req, res, next) {
  //if user is authenticated in the session, carry on
  if(req.isAuthenticated()) {
    return next();
  }

  res.redirect('/users/login');
}
function isAdmin(req, res, next) {
  var user = req.user;
  if(user.isAdmin == true) {
    return next();
  } 
  res.redirect('/users/profile');
}

function notLoggedIn(req, res, next) {
  if(!req.isAuthenticated()) {
    return next();
  }
  res.redirect('/');
}

module.exports = router;

1 个答案:

答案 0 :(得分:1)

您可以根据护照文档使用会话配置

spark-submit --class suhita.Sample --master local[*] target/DroolsMaven-1.0-SNAPSHOT.jar

或者您可以给护照呼叫回叫并阻止会话存储,这样就不会执行登录

.post(passport.authenticate('local-signup', {
    successRedirect: '/users/login',
    failureRedirect: '/users/signup',
    badRequestMessage: "You must fill in all of the form fields.",
    failureFlash: true, // allow flash,
    session: false // prevent auto-login
})