Answer the question
In order to leave comments, you need to log in
Why is the user unable to log in?
I have already checked everything, it finds the user, serializeUser works, and cookies are written, but req.isAuthtenticated() is always negative. Why? I have already done such authorization more than once, but I just can’t do authentication. Thanks in advance.
const express = require('express');
const bodyParser = require('body-parser');
const session = require('express-session');
const passport = require('passport');
const LocalStrategy = require('passport-local');
const Sequelize = require('sequelize');
const sequelize = new Sequelize(...);
const PORT = process.env.PORT || 3000;
const User = require('./models/user')(sequelize);
passport.use(new LocalStrategy((username, password, done) => {
User.findOne({
where: {username: username}
})
.then(({dataValues: user}) => {
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
User.validPassword(password, user.password)
.then(isMatch => {
if (isMatch) {
return done(null, user);
} else {
return done(null, false, { message: 'Incorrect password.' });
}
})
})
.catch(done);
}));
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findOne({
where: {id: id}
})
.then(({dataValues: user}) => {
done(null, user);
})
.catch(err => {
done(err, null);
});
});
let app = express();
app.use(express.static(path.join(__dirname, '/public')));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.set('view engine', 'pug');
app.set('views', path.join(__dirname, '/templates/pages'));
app.use(cookieParser());
// Session
app.use(session({
secret: 'my secret',
cookie: { maxAge: 14 * 24 * 60 * 60 * 1000 },
resave: true,
saveUninitialized: true
}));
// headers
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", req.headers.origin);
res.header('Access-Control-Allow-Credentials', 'true');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// Passport
app.use(passport.initialize());
app.use(passport.session());
// user
app.get('/login', (req, res) => {
res.set('Content-Type', 'text/html');
res.render('login.pug');
});
// login
app.post('/login', passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login',
badRequestMessage: 'Missing username or password.',
failureFlash: false
}));
// all
app.get('/*', (req, res, next) => {
if (!req.isAuthenticated()) {
res.redirect('/user');
} else {
next();
}
});
// Router
require('./routes/index')(app);
app.listen(PORT);
console.log(`Server work on port ${PORT}`);
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question