passport.js在表单提交时注销用户

6fe3ivhb  于 2021-09-23  发布在  Java
关注(0)|答案(0)|浏览(305)

我正在使用passport.js作为一个简单应用程序的身份验证系统。用户输入用户名和密码以进入系统。用户登录后,在addtodb.ejs或editdb2.ejs页面上提交表单时,表单不会提交,用户将注销。有时候,表单很少会被提交,但不管怎样,用户最终都会被注销。当您花整整两分钟处理表单时,表单提交的注销会持续发生。如果少于两分钟,有时你会得到相同的行为,但在两分钟和超过分数时是一致的。
代码包括在下面。我尝试了许多关于stackoverflow的建议。
server.js:

const mongoose = require("mongoose");
const express = require("express");
const app = express();
const passport = require('passport')
const flash = require('express-flash')
const session = require('express-session')
const bcrypt = require('bcrypt')
var FRP = require('./models/FRP.js');
var suggestAnEdit = require('./models/suggestedEdit.js');

// //Import authRoute
// const authRoute = require('./routes/auth');

//Connect to the Database

***code obscured***

//Passport required

//Passport
LocalStrategy = require('passport-local').Strategy;

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

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

passport.use(new LocalStrategy(
  function (username, password, done) {
    User.findOne({
      email: username
    }, (err, user) => {
      if (err) return done(err)
      if (!user) return done(null, false, { message: 'User not found!' });
      bcrypt.compare(password, user.password, function(err, res) {
        if (err) return done(err)
        if (res) {
          return done(null, user);
        } else {
          return done(null, false, { message: 'Incorrect password!' });
        }
      })
    })
  }
));

function loggedIn(req, res, next) {
  if (req.isAuthenticated()) {
    next()
  } else {
    req.flash('error', 'You needed to be logged in to visit that page!');
    res.redirect('/login')
  }
}

app.set("view engine", "ejs");
app.set('views','./views/');
app.set('models','./models/');
app.use(express.static(__dirname + '/public'));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(flash())
app.use(session({
  secret: 'rainbowPup',
  resave: false,
  saveUninitialized: false,
  cookie: {
     maxAge: 3600000 //1 hour
  }
}));
app.use(passport.initialize());
app.use(passport.session());

app.disable('etag');

mongoose.set('useFindAndModify', false);

const Schema = mongoose.Schema;

const userSchema = new Schema({
  email: String,
  password: String
});

const User = mongoose.model('users', userSchema);

app.post('/register', async (req, res, next) => {
  const user = await User.findOne({
    email: req.body.email
  })

  if (user) {
      req.flash('error', 'Sorry, that name is taken. Maybe you need to <a href="/login">login</a>?');
      res.redirect('/register');
    } else if (req.body.email == "" || req.body.password == "") {
      req.flash('error', 'Please fill out all the fields.');
      res.redirect('/register');
    } else {
      bcrypt.genSalt(10, function (err, salt) {
        if (err) return next(err);
        bcrypt.hash(req.body.password, salt, function (err, hash) {
          if (err) return next(err);
          new User({
            email: req.body.email,
            password: hash
          }).save()
          req.flash('info', 'Account made, please log in...');
          res.redirect('/login');
        });
      });
    }
  });

  app.post('/login', passport.authenticate('local', { successRedirect: '/dashboard', failureRedirect: '/login', failureFlash: true }))

  //End passport

  app.get('/login', (req, res) => {
    res.render('login.ejs')
  })

  app.get('/register', (req, res) => {
    res.render('register.ejs')
  })

  app.get('/logout', (req, res) => {
    req.logOut()
    res.redirect('/login')
  })

  //Protected Routes

  app.get('/dashboard', loggedIn, (req, res) => {
    res.render('dashboard.ejs')
    // The user is logged in otherwise they would have been redirected
  })

//Handle routes

// //Route middle-ware for backend user registration
// app.use('/api/user', authRoute);

//Route for secure area to add to Database
app.get('/addToDB',  loggedIn, (req, res) => {
res.render('addToDB.ejs');
});

// Submit Data to the Database
  app.post('/DBadd', loggedIn, (req,res) => {
    FRP.create(req.body)
    .then(result => {
      req.flash('FRPStatusMsg', 'FRP Added To System Successfully');
      res.render('dashboard.ejs')
    })
      .catch(error => console.error(error))
  })

  //Route for secure area to editing FRPs in the Database
  app.get('/editDB', loggedIn, (req, res) => {
    FRP.find({},'Region Country NameOfFRP', function(err, FRPList) {
      if(err) {
        console.log("Error");
      } else {
        res.render("editDB.ejs", {FRPList:FRPList});
      }
    });
  });

//Edit data by id Route
app.get("/editFRP/:id/", loggedIn, function(req,res) {
  FRP.findById(req.params.id, function(err, editFRPByID) {
    if(err) {
      console.log(err);
    } else {
      res.render("editDB2.ejs", {editFRPByID:editFRPByID});
    }
  });
});

//Save freshly edited data by id to the database

app.post("/editFRP/:id", loggedIn, function(req, res){
   FRP.findByIdAndUpdate(req.params.id, req.body.FRP, function(err, updatedFRP){
       if(err){
           console.log(err);
           req.flash('FRPEditStatusMsgFail', 'An error has occured. Please try again.');
       }else{
           req.flash('FRPEditStatusMsg', 'FRP Successfully Edited!');
           res.render("editDB.ejs");
       }
   });
});

addtodb.ejs: <form action="/DBadd" method="POST">***form fields***</form> editdb2.ejs: <form action="/editFRP/<%=editFRPByID.id%>" id="#editFRPForm" method="POST">***form fields***</form>

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题