Пытаюсь сделать авторизацию, опираясь на этот
код
Но консоль выдает ошибку
Делаю практически все, как в коде по ссылке. Подскажите, в чем может быть проблема?
server.js
const express = require('express');
const path = require('path');
const flash = require('connect-flash');
const session = require('express-session');
const bodyParser = require('body-parser');
const passport = require('passport');
const mongoose = require('mongoose');
const ejs = require('ejs');
//initialize app
const app = express();
//Set Moment.js
app.locals.moment = require('moment');
//Load Routes
const mainRoutes = require('./routes/main');
//passport config
require('./config/passport')(passport);
// Connect to MongoDB
mongoose.connect('mongodb://name:password@localhost:27017/articles')
.then(() => console.log('Successfully connected'))
.catch(err => console.log(err));
//ejs middleware
app.engine('ejs', require('ejs').renderFile);
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// body parser middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//static folder middleware
app.use(express.static(path.join(__dirname, 'public')));
// session middleware
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true
}));
// passport middleware
app.use(passport.initialize());
app.use(passport.session());
//flash middleware
app.use(flash());
//global variables
app.use((req, res, next)=> {
res.locals.success_msg = req.flash('success_msg');
res.locals.err_msg = req.flash('err_msg');
res.locals.error = req.flash('error');
res.locals.user = req.user || null;
next();
});
//use Routes
app.use('/', mainRoutes);
const port = 8080;
app.listen(port, ()=>{
console.log(`App started at port ${port}`);
});
passport.js
const LocalStrategy = require('passport-local').Strategy;
const mongoose = require('mongoose');
const User = mongoose.model('user');
const bcrypt = require('bcryptjs');
module.exports = passport => {
passport.use(new LocalStrategy({
usernameField : 'login'
},
(login, password, done) => {
//match user
User.findOne({
login : login
})
.then(user => {
if(!user){
return done(null, false, {message : 'no user found'});
}
//match passwords
bcrypt.compare(password, user.password, (err, isMatch)=>{
if (err) throw err;
if (isMatch) {
return done(null, user);
} else {
return done(null, false, {message : 'password incorrect'});
}
})
})
.catch(err => console.log(err));
}
));
passport.serializeUser((user, done)=>{
done(null, user.id);
});
passport.deserializeUser(()=>{
User.findOne(id, (err, user)=>{
done(err, user);
});
});
};
Роуты
//login
router.get('/login', (req, res) => {
res.render('main/login.ejs');
});
// POST api/login
router.post('/login', (req, res, next) => {
passport.authenticate('local', {
successRedirect : '/admin',
failureRedirect : '/login',
failureFlash : true
})(req, res, next);
});
router.get('/admin', (req, res) => {
res.render('main/add-article.ejs')
});