Здравствуйте.
При проверке авторизованного пользователя с помощью req.user или req.isAuthenticated() я всегда получаю false.
При этом при выполнении входа, я попадаю в колбэк и судя по тексту из доки passport это должно значить, что пользователь успешно залогинен. Часть ниже я скопировал из доки в свой код.
router.post('/login', passport.authenticate('local'), function(req, res) {
// If this function gets called, authentication was successful.
// `req.user` contains the authenticated user.
// Сообщение в консоль выводится успешно
console.log('User logged in');
});
Однако проверки авторизации возвращает false.
Кроме того я заметил, что при логине не вызывается serializeUser/deserializeUser
Ниже части кода относящиеся к авторизации.
Passport
const LocalStrategy = require('passport-local').Strategy;
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
// Load User Model
const User = require('../models/user.model');
module.exports = function(passport) {
passport.use(
new LocalStrategy({ usernameField: 'email' }, (email, password, done) => {
User.findOne({ email: email })
.then(user => {
if (!user) {
return done(null, false, { message: 'That email is not register' });
}
// Match password
bcrypt.compare(password, user.password, (err, isMatch) => {
if (err) {
throw err;
}
if (isMatch) {
return done(null, user, { message: 'Login success' });
} else {
return done(null, false, { message: 'Password incorrect' });
}
});
})
.catch(err => console.log(err));
})
);
passport.serializeUser((user, done) => {
done(null, user._id);
});
passport.deserializeUser((id, one) => {
User.findById(id, (err, user) => {
done(err, user);
});
});
};
User
const router = require('express').Router();
const bcrypt = require('bcryptjs');
let User = require('../models/user.model');
const passport = require('passport');
router.route('/').get((req, res) => {
User.find()
.then(users => res.json(users))
.catch(err => res.status(400).json('Error: ' + err));
});
//Register Handler
router.post('/register', (req, res) => {
const { name, email, password } = req.body;
User.findOne({ email: email }).then(user => {
if (user) {
//User exists
res.status(400).json(`Email ${email} is already registered`);
}
});
const newUser = new User({
name,
email,
password
});
//Hash password
bcrypt.genSalt(10, (err, salt) =>
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
//Set password to hashed
newUser.password = hash;
//Save user
newUser
.save()
.then(() => res.json('User added'))
.catch(err => res.status(400).json(`Error: ${err}`));
})
);
});
// Login Handle
router.post('/login', passport.authenticate('local'), function(req, res) {
// If this function gets called, authentication was successful.
// `req.user` contains the authenticated user.
console.log('User logged in');
});
//delete after check
router.post('/isloggedin/', (req, res) => {
if (req.user) {
res.send('Is logged in');
} else {
res.send('Is not logged in');
}
});
//Logout Handle
router.post('/logout', (req, res) => {
req.logout();
res.send('User logged out');
});
module.exports = router;
Server
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const passport = require('passport');
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
//Passport config
require('./config/passport')(passport);
app.use(cors());
app.use(express.json());
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true });
const connection = mongoose.connection;
connection.once('open', () => {
console.log('MongoDB database connection established successfully');
});
const exercisesRouter = require('./routes/items');
const usersRouter = require('./routes/users');
//Express Session
app.use(
session({
secret: 'secret',
store: new MongoStore({ mongooseConnection: connection }),
resave: true,
saveUninitialized: true
})
);
// Passport middleware
app.use(passport.initialize());
app.use(passport.session());
app.use('/items', exercisesRouter);
app.use('/users', usersRouter);
app.listen(port, () => {
console.log(`Server is running on port: ${port}`);
});