Full-Stack Web Development with Vue.js and Node

(singke) #1
Building Authentication with passport.js Chapter 6

If username and password matches, the user object is saved in the session in the server


and can be access via req.user in every request.


Also, let's updated our vue files as well since we do not need the passport JWT strategy


now.


Update the contents in server.js with the following code:


const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors');
const morgan = require('morgan');
const fs = require('fs');
const session = require('express-session');
const config = require('./config/Config');
const passport = require('passport');
const serveStatic = require('serve-static');
const history = require('connect-history-api-fallback');

const app = express();
const router = express.Router();
app.use(morgan('combined'));
app.use(bodyParser.json());
app.use(cors());

app.use(session({
secret: config.SECRET,
resave: true,
saveUninitialized: true,
cookie: { httpOnly: false }
}))
app.use(passport.initialize());
app.use(passport.session());

//connect to mongodb
mongoose.connect(config.DB, function() {
console.log('Connection has been made');
})
.catch(err => {
console.error('App starting error:', err.stack);
process.exit(1);
});

// Include controllers
fs.readdirSync("controllers").forEach(function (file) {
if(file.substr(-3) == '.js') {
Free download pdf