Skip to content

Instantly share code, notes, and snippets.

@giusecapo
Created October 16, 2019 13:17
Show Gist options
  • Save giusecapo/53adbe17756c82c204c81126900f872e to your computer and use it in GitHub Desktop.
Save giusecapo/53adbe17756c82c204c81126900f872e to your computer and use it in GitHub Desktop.
Setup for CRUD project
// Import Libraries
var express = require('express');
var session = require('express-session')
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var passport = require('passport')
, LocalStrategy = require('passport-local').Strategy;
var cors = require('cors')
// ENV file with config
require('dotenv').config();
// - Mark: Models
var User = require('./models/user.model')
// - Mark: Routes for app
const apiRoutes = require('./routes/api');
const authRoutes = require('./routes/auth');
// This is an Express app
var app = express();
// - Mark: Mongoose configuration
mongoose.connect(process.env.MONGO_URI, {useNewUrlParser: true, useUnifiedTopology: true}); // connect to our database
// - Mark: API/json formatting config
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors())
// - Mark: AUTH - Session/Passport Configuration
app.use(session({
secret: process.env.SESSION_SECRET || "development",
maxAge: 24 * 60 * 60 * 1000, // 24 hours
resave: true,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
// Passport Local Configuration uses User model to search for user email/password
passport.use(new LocalStrategy({
usernameField: "email",
passwordField: "password"
},
(username, password, done) => {
User.findOne({ email: username }, function(err, user) {
if (user) {
done(null, user)
} else {
done(null, false, { message: 'Incorrect username or password'})
}
});
}
));
passport.serializeUser((user, done) => {
done(null, user.id)
})
passport.deserializeUser((id, done) => {
User.findOne({_id: id}, (err, user) => {
done(null, user)
})
})
// Middleware to check if request is from logged user
const authMiddleware = (req, res, next) => {
if (!req.isAuthenticated()) {
res.status(401).send('You are not authenticated')
} else {
return next()
}
}
// Routes
app.use('/api', apiRoutes);
app.use('/auth', authRoutes);
// Define port for the app
var port = process.env.PORT || 8080;
// Start the server
app.listen(port);
console.log('Magic happens on port ' + port);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment