W
W
Wasya UK2018-08-12 13:13:09
MySQL
Wasya UK, 2018-08-12 13:13:09

Why is the user not authorized during the first authorization?

A strange situation - the authorization seems to be working, but at the first authorization check, the user is considered not authorized.
How it all happens (I go to the login page):

// запуск сервера
Executing (default): CREATE TABLE IF NOT EXISTS `Sessions` 

// перешел на страницу логина
Executing (default): SHOW INDEX FROM `Sessions`
Executing (default): SELECT `sid`, 

// нажимаю кнопку логин
Executing (default): SELECT USER
USER IS CORRECT
USER: {...}  // serialize user
USER IS AUTHENTICATED
Executing (default): SELECT `sid`
Executing (default): SELECT `sid`
Executing (default): UPDATE `Sessions`

// срабатывает success redirect в Passport.js
CHECK AUTH FALSE
Executing (default): UPDATE `Sessions`
Executing (default): SELECT `sid`
USER ID: 18ea8856-af53-4386-a094-7a93989f86fb  // deserialize user
Executing (default): SELECT USER BY ID
Executing (default): UPDATE `Sessions`

And it redirects back to the login, but req.user is there, and if you then switch to another tab, then it is considered authorized and req.isAuthenticated == true, and if it logs in again, it normally redirects to the main one.
// ROUTER
app.get('/login', authRouter.login.get);
  app.post('/login', authRouter.login.post);
  app.get('/sign-up', authRouter.authorize.get);
  app.post('/sign-up', authRouter.authorize.post);

  // check auth
  app.get('/*', authRouter.checkAuth);

  app.get('/logout', authRouter.logout);
  app.get('/', frontpageRouter.get);

// CHECK USER
module.exports.checkAuth = (req, res, next) => {
  if (!req.isAuthenticated()) {
    console.log("CHECK AUTH FALSE");
    res.redirect('/login');
  } else {
    console.log("CHECK AUTH TRUE");
    next();
  }
}

// LOGIN
module.exports.login = {
  get: (req, res) => {
    res.set('Content-Type', 'text/html');
    res.render('sign_in.pug', {
      user: req.user
    });
  },
  post: passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login' })
}

Otherwise, I can throw a standard passport, but still what is wrong, the authorization is working, but at the first entry there are problems. I will be glad to all advice)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question