.isAuthenticated () всегда ложно || паспорт местной стратегии - PullRequest
0 голосов
/ 03 августа 2020

Есть много сообщений, похожих на это, но я не нашел подходящего решения ни в одном из ответов на те сообщения, которые помогли мне с этим.

код

"use strict";

require('dotenv').config();

const auth     = require('./auth.js');

const express       = require('express');
const passport      = require('passport');
const bcrypt        = require('bcrypt');
const mongo         = require('mongodb');
const session       = require('express-session');
const cors          = require('cors');
const util          = require('util');

const app  = express();
const port = process.env.PORT || 8080;

app.use(cors());
app.use(express.json());
app.use(express.urlencoded({extended:true}));

app.use(session({
  secret: process.env.SESSION_SECRET,
  resave: true,
  saveUninitialized: true,
  cookie: {
    secure: false,
    maxAge: 1000 * 60 * 60 * 24 * 7
  }
}));

app.use(passport.initialize());
app.use(passport.session());

mongo.connect(process.env.DATABASE, {useNewUrlParser: true, useUnifiedTopology: true}, (err, db) => {
  if (err) {
    console.log('Database error: ' + err);
  } else {
    console.log('Database connection successful');

    auth(app, db);

    app.route('/test').get((req, res) => {
      res.send('The connection works!')
    });

    const ensureAuthenticated = (req, res, next) => {
      console.log('isAuth() is: ' + req.isAuthenticated());
      console.log('session store: ' + util.inspect(req.session, {showHidden: false, depth: null}));
      if (req.isAuthenticated()) return next();
      res.send('user not authenticated, begone! >:(');
    }

    app.route('/profile').get(
      ensureAuthenticated,
      (req, res) => {
        res.render({username: req.user.username});
      }
    );

    app.post('/login', 
      (request, response, next) => {
        console.log(request.session)
        passport.authenticate('local', 
        (err, user, info) => {
          if(!user){ response.send(info.message);}
          else{
            request.login(user, function(error) {
              if (error) return next(error);
              console.log("Request Login supossedly successful.");
              return response.send('Login successful');
            });
            //response.send('Login successful');
          }

        })(request, response, next);
      }
    );

    app.route('/register').post((req, res, next) => {
      const hash = bcrypt.hashSync(req.body.password, 13);
      db.db().collection('users').findOne({username: req.body.username}, (err, user) => {
        if (err) {
          next(err);
        } else if (user) {
          res.send('user already exists :(');
        } else {
          db.db().collection('users').insertOne({
            username: req.body.username,
            password: hash
          },
            (err, doc) => {
              if (err) {
                res.send('registration mongo error');
              } else {
                next(null, user);
              }
            }
          )
        }
      })
    },
      passport.authenticate('local', {failureMessage: 'passport authenticate failure'}),
      (req, res, next) => {
        console.log('registration successful');
        req.logIn(req.user, err => {
          if (err) next(err)
          return console.log("i'm trying: " + req.user);
        });
        res.send('registration successful!!! :D');
      }
    );

    app.listen(port, () => {console.log(`Listening on port: ${port}`)});
  }
});

авт. js

const passport      = require('passport');
const LocalStrategy = require('passport-local');
const ObjectID      = require('mongodb').ObjectID;
const bcrypt        = require('bcrypt');

module.exports = (app, db) => {
  passport.use(new LocalStrategy(
    (username, password, done) => {
      db.db().collection('users').findOne({username: username}, (err, user) => {
        console.log(`${username} attempted to log in`);
        if (err) return done(err);
        if (!user) return done(null, false);
        if (!bcrypt.compareSync(password, user.password)) return done(null, false);
        console.log('local strategy successful');
        return done(null, user);
      })
    }
  ));

  passport.serializeUser((user, done) => {
    console.log(user.username + " serialized");
    done(null, user._id);
  });

  passport.deserializeUser((id, done) => {
    db.db().collection('users').findOne(
      {_id: new ObjectID(id)},
      (err, doc) => {
        done(null, doc);
      }
    );
  });
}

Вопрос:

Все функции работают просто хорошо, я получаю все сообщения об успешном завершении, и даже регистрация сохраняет пользователя в базе данных, а логин успешно загружает его из базы данных. Единственная проблема, с которой я сталкиваюсь, заключается в том, что req.isAuthenticated() в функции ensureAuthenticated всегда возвращает false, и, как вы можете видеть, мне действительно действительно нужно, чтобы это было истиной, поэтому я могу отправить информацию клиенту для / профиль, и делать все остальное, что мне нужно с Паспортом. Что мне не хватает?

1 Ответ

0 голосов
/ 08 августа 2020

Решение: Мне нужно было добавить credentials: true в cors () и что-то похожее на заголовки http (withCredentials:true для ax ios) в клиенте. Я добавляю это, потому что знаю, что однажды у кого-то будет такая же проблема, и, вероятно, ему будет так же сложно найти этот ответ, как и мне.

Дополнительно: In На большинстве форумов, на которых я задавал этот вопрос, все ответы, которые я получил, были людьми, которые не верят, что этот код работает, и покровительствуют мне, говоря, что мне нужно заново выучить паспорт и реагировать (если я вообще получил ответ lmao).

...