Я хочу знать, почему req.isAuthenticated имеет значение false в пользовательской функции аутентификации.
Пробовал Поиск проблемы в гугле.Большинство решений были правильно настроены, когда вы должны вызывать parse cookie и passport.initialize () и passport.session ().Кроме того, наличие одного и того же паспорта для cookie-парсера и экспресс-сессии и перезапусков сервера.
// server.js //
if (process.env.NODE_ENV !== 'production') require('dotenv').config();
const express = require('express');
const app = express();
const path = require('path');
const PORT = process.env.PORT || 3001;
const db = require('./models');
const routes = require('./controller/controller');
//Authethication packages
const cookieParser = require('cookie-parser');
const session = require('express-session');
const passport = require('passport');
const sequelize = require('sequelize');
const SequelizeStore = require('connect-session-sequelize')(session.Store);
//serve up static assets production
if (process.env.NODE_ENV === 'production') {
app.use(express.static('client/build'));
/*app.get('*', (req, res) => {
res.sendFile(path.join((__dirname = './client/build/index.html')));*/
/*const index = path.join(__dirname, 'build', 'index.html');
res.sendFile(index);*/
//});
}
//build mode local
/*app.get('*', (req, res) => {
res.sendFile(path.join(__dirname + '/client/public/index.html'));
});*/
//session options
function extendedDefaultFields(defaults, session) {
return {
data: defaults.data,
expires: defaults.expires
};
}
//
const cookieExpirationDate = new Date();
const cookieExpirationDays = 365;
cookieExpirationDate.setDate(
cookieExpirationDate.getDate() + cookieExpirationDays
);
const sessionOptions = {
key: 'userId',
secret: /*process.env.SECRET*/ 'foo',
resave: false,
saveUninitialized: false,
cookie: {
expires: cookieExpirationDate, //1 month
secure: process.env.NODE_ENV === 'production' ? true : false,
httpOnly: process.env.NODE_ENV === 'production' ? true : false
},
store: new SequelizeStore({
db: db,
table: 'Session',
checkExpirationInterval: 20 * 23 * 60 * 1000,
expiration: 30 * 24 * 60 * 60 * 1000, //1 month
extendedDefaultFields: extendedDefaultFields
})
};
//cookieparse
const secret = 'foo';
app.use(cookieParser(secret));
//static file declaration
app.use(express.static(path.join(__dirname, 'client/build')));
//middleware to extract requests and exposing to req, without manually searching for them.
//extented keyword allow you to have nested objects sent
//dont need bodyparser package. Express has it included now after version 4.16.0
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
//express session. Options in object defined from line 29.
app.use(session(sessionOptions));
//passport
app.use(passport.initialize());
app.use(passport.session(sessionOptions));
app.use(routes);
//use routes when made and connect to mysql
db.sequelize.sync({ force: true }).then(() => {
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});
});`
///
//routes
const db = require('../models');
const bycrpt = require('bcrypt');
const passport = require('passport');
const express = require('express');
const router = express.Router();
const saltRounds = 10;
router.get('/api/users', (req, res, next) => {
db.User.findAll({})
.then(dbFindAll => {
return res.json(dbFindAll);
})
.catch(error => {
if (error) {
res.json(error);
}
});
});
router.post('/api/newuser', (req, res, next) => {
//strip tags afterwards.
const { first_name, last_name, email, password } = req.body;
//strip html tags and remove uneccessary white spaces
const stripTagsFunction = myString => {
return myString.replace(/(<([^>]+)>)/gi, '');
};
if (first_name && last_name && email && password) {
bycrpt.hash(password, saltRounds, function(err, hash) {
if (!err) {
db.User.create({
first_name: stripTagsFunction(first_name.split(' ').join('')),
last_name: stripTagsFunction(last_name.split(' ').join('')),
email: stripTagsFunction(email.split(' ').join('')),
password: hash
})
.then(created => {
const userId = created.id;
if (!created) {
return res.status(400).json({
success: false,
message: 'An error has occured. User has not been saved'
});
} else if (created && typeof userId !== 'undefined') {
req.login(userId, {}, error => {
// console.log('req.user: ', req);
console.log('hi: ', req.session.passport.user);
console.log('is authenticated: ', req.isAuthenticated());
if (!error) {
return res.json({
success: true,
data: created,
message: 'User successfully created'
});
} else {
return res.json({
success: false,
data: 'corrupted seralization',
message: 'User created Successfully, but not seralized'
});
}
});
}
})
.catch(error => {
if (error) {
return res.json({ success: false, errors: error });
}
});
} else {
res.json({ success: false, errors: err, message: 'Hash Failed' });
}
});
} else {
res
.status(400)
.json({ success: false, message: 'Error Missing Parameters' });
}
});
router.get('/test', authenticationMiddleware(), (req, res) => {
return res.send('hi');
});
passport.serializeUser(function(userId, done) {
console.log('from seralized userId: ', userId);
done(null, userId);
});
passport.deserializeUser(function(userId, done) {
db.User.findOne({ where: { id: userId } }).then(user => {
if (user) {
console.log('\n\n\n\nFound User\n\n\n\n');
done(null, user);
} else {
console.log('Unable to deseralize');
}
});
});
//authentication middleware
function authenticationMiddleware() {
return (req, res, next) => {
console.log(req.session);
console.log(req.cookies);
console.log('is authenticated middleware: ', req.isAuthenticated());
if (req.isAuthenticated()) {
return next();
} else {
return res
.json({
success: false,
data: 'unable to login',
message: 'unsuccessfull login process'
})
.status(404);
}
};
}
//passport
module.exports = router;
Результаты: console.log (req.session) в функции authenticationMiddleWare для отображения паспорта свойства.Однако это не так.Кроме того, req.cookie возвращается как пустой объект.Ожидается: req.session возвращается со свойством passport, как это происходит в req.login из моего маршрута регистрации.