Answer the question
In order to leave comments, you need to log in
Why doesn't passport.js use passport.use?
When authenticating a user through passport, it immediately issues a failureRedirect (line 61), bypassing the middleware (line 36), i.e. does not use LocalStrategy.
const consolidate = require('consolidate');
const bodyParser = require('body-parser');
const path = require('path');
const mongoose = require('mongoose');
const session = require('cookie-session');
const passport = require('passport');
const express = require('express');
const app = express();
const Task = require('./models/task');
mongoose.connect('mongodb://127.0.0.1', {
useNewUrlParser: true,
useUnifiedTopology: true,
}, (err) => {
err ? console.error(err) : console.log('[+] База подключена!');
/* Settings */
app.engine('hbs', consolidate.handlebars);
app.set('view engine', 'hbs');
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(path.join(__dirname, 'static')));
/* Authorisation */
app.use(session({ keys: ['*1hF5l07%[email protected]'] }));
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.use(passport.initialize({}));
app.use(passport.session({}));
const LocalStrategy = require('passport-local').Strategy;
passport.use('local', new LocalStrategy({}, (username, password, done) => {
console.log('params: ', username, password);
if (username !== 'admin') {
console.log('invalid username');
return done(null, { name: 'Vasya', id: 1});
}
if (password !== 'admin') {
console.log('invalid password');
return done(null, { name: 'Vasya', id: 1});
}
console.log('done!');
return done(null, { name: 'Vasya', id: 1});
}));
/* Session */
passport.serializeUser((user, done) => done(null, user.id));
passport.deserializeUser((id, done) => {
done(null, { name: 'Vasya', id})
});
/* Authentication */
const auth = passport.authenticate('local', {
successRedirect: '/main',
failureRedirect: '/login?message=err',
});
app.get('/login', (req, res) => {
if (req.query.message === 'err') {
res.render('login', { message: 'Неверный логин или пароль!' });
} else {
res.render('login', { message: '' });
}
});
app.post('/login', auth);
const mustBeAuth = (req, res, next) => { // Is user authenticated
console.log('isAuth', req.isAuthenticated());
if (req.isAuthenticated()) { next(); }
else { res.redirect('/login'); } // Else redirect to login page
}
app.all('/main', mustBeAuth);
app.all('/main/*', mustBeAuth);
app.get('/', (req, res) => {
res.redirect('/main');
});
app.get('/main', (req, res) => {
res.send('ok');
});
/* Start the server! */
app.listen(8888, (err) => {
err ? console.error(err) : console.log('[+] Сервер поднят!');
});
});
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