/* Importing Different Modules */
const {globalVariables} = require('./config/configuration');
const express = require('express');
const mongoose = require('mongoose');
const path = require('path');
const hbs = require('express-handlebars')
const {mongoDbUrl,PORT} = require('./config/configuration');
const flash = require('connect-flash');
const session = require('express-session');
const methodOverride = require('method-override');
const {selectOption} = require('./config/customFunctions');
const fileUpload = require('express-fileupload');
const app = express();
// Configure mongoose to connect MongoDB
mongoose.connect(mongoDbUrl, { useNewUrlParser: true, useUnifiedTopology: true })
.then(response => {
console.log("MongoDB connect succes");
}).catch(err => {
console.log("Database connection failed");
})
/* Configure express */
app.use(express.json());
app.use(express.urlencoded({extended: true}));
app.use(express.static(path.join(__dirname, 'public')));
/* Flash and Session */
app.use(session({
secret: 'anysecret',
saveUninitialized: true,
resave: true
}));
app.use(flash());
app.use(globalVariables);
/* File upload middleware */
app.use(fileUpload());
/* Setup View Engine To Use Handlebars*/
app.engine('handlebars', hbs({defaultLayout: 'default', helpers: {select: selectOption}}));
app.set('view engine', 'handlebars');
/* Method Override Middleware */
app.use(methodOverride('newMethod'));
/* Routes */
const defaultRoutes = require('./routes/defaultRoutes');
const adminRoutes = require('./routes/adminRoutes');
app.use('/', defaultRoutes);
app.use('/admin', adminRoutes);
app.listen(PORT, () => {
console.log(`Server is running or port ${PORT}`);
});
const express = require('express');
const router = express.Router();
const defaultController = require('../controllers/defaultController');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcryptjs');
const User = require('../models/UserModel').User;
router.all('/*', (req, res, next) => {
req.app.locals.layout = 'default';
next();
})
router.route('/')
.get(defaultController.index);
//Defining of local strategy
passport.use(new LocalStrategy({
usernameField: 'email',
passReqToCallback: true
}, (req, email, password, done) => {
User.findOne({email: email}).then(user => {
if(!user){
//console.log(user);
return done(null,false, req.flash('error-message', 'User not found with this email'));
}
bcrypt.compare(password, user.password, (err, passwordMatched)=>{
if(err){
return err;
}
if(!passwordMatched){
return done(null,false, req.flash('error-message', 'Invalid username or password'));
}
return done(null, user, req.flash('success-message', 'Login successful'));
});
});
}));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
router.route('/login')
.get(defaultController.loginGet)
.post(passport.authenticate('local', {
successRedirect: '/admin',
failureRedirect: '/login',
failureFlash: true,
successFlash: true,
session: true
}),defaultController.loginPost);
router.route('/register')
.get(defaultController.registerGet)
.post(defaultController.registerPost);
module.exports = router;
const Post = require('../models/PostModel').Post;
const Category = require('../models/CategoryModel').Category;
const bcrypt = require('bcryptjs');
const User = require('../models/UserModel').User;
module.exports = {
index: async (req, res) => {
//res.send('Welcome to the CMS App'); // это была проверка роута
const posts = await Post.find().lean();
const categories = await Category.find().lean();
res.render('default/index', {posts: posts, categories: categories});
},
loginGet: (req, res) =>{
res.render('default/login', {message: req.flash('error')});
},
loginPost: (req, res) =>{
//res.send('Congratulation');
},
registerGet: (req, res) =>{
res.render('default/register');
},
registerPost: (req, res) =>{
let errors = [];
if(!req.body.firstName){
errors.push({message: 'First name is Mandatory'});
}
if(!req.body.lastName){
errors.push({message: 'Last name is Mandatory'});
}
if(!req.body.email){
errors.push({message: 'Email field is Mandatory'});
}
if(req.body.password !== req.body.passwordConfirm){
errors.push({message: 'Passwords do not match'});
}
if(errors.length > 0){
res.render('default/register', {
errors: errors,
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
});
}
else {
User.findOne({email: req.body.email}).then(user => {
if(user){
req.flash('error-message', 'Email already exist, try to login');
res.redirect('/login');
}
else {
const newUser = new User(req.body);
bcrypt.genSalt(10,(err, salt) => {
bcrypt.hash(newUser.password, salt, (err,hash) => {
newUser.password = hash;
newUser.save().then(user => {
req.flash('success-message', 'You are now registered');
res.redirect('/login');
});
});
});
}
})
}
//res.send('Successfuly registered');
}
};
return done(null, user, req.flash('success-message', 'Login successful'));