Skip to content

Instantly share code, notes, and snippets.

/express.js
Created Dec 28, 2015

Embed
What would you like to do?
'use strict'
// Require modules
var express = require('express'),
morgan = require('morgan'),
compression = require('compression'),
mongoose = require('./mongoose'),
passport = require('passport'),
LocalStrategy = require('passport-local').Strategy,
cookieParser = require('cookie-parser'),
session = require('express-session'),
bodyParser = require('body-parser')
module.exports = function(){
var app = express()
if(process.env.NODE_ENV === 'production'){
app.use(compression())
} else if(process.env.NODE_ENV === 'development'){
app.use(morgan('dev'))
}
app.use(cookieParser('foo')) // Instatiate cookie-parser
app.use(bodyParser.urlencoded({'extended': true})) // Only parse urlencoded bodies
app.use(bodyParser.json()) // Only parse JSON
app.use(session({secret: 'foo',
saveUninitialized: true,
resave: true}))
app.use(passport.initialize()) // Intialize passport
app.use(passport.session()) // Initialize session for passport
// Set Static Server
app.use(express.static(__dirname + '/public'))
app.set('views', './public/views') // Set views directory
app.set('view engine', 'ejs') // Set template engine to EJS
// Require Passport Configuration
require('./passport')(passport)
// Require Routes Module
require('./server/routes.js')(app, passport)
return app;
}
<style>
form input {
display: block;
}
</style>
<form action="/login" method="POST">
<input type="text" name="username" placeholder="Username" required>
<input type="password" name="password" placeholder="Password" required>
<button type="submit">Login In</button>
</form>
var LocalStrategy = require('passport-local').Strategy,
User = require('mongoose').model('User')
module.exports = function(passport){
// Username and password extracted from cookie
passport.use('local-signup', new LocalStrategy(function(username, password, done){
User.findOne({username: username}, function(err, user){
if(err) { return done(err) }
if(user) { return done(null, false) }
else {
var newUser = new User()
newUser.username = username
newUser.password = newUser.generateHash(password)
newUser.downloads = []
newPassword = []
newUser.save(function(err){
if(err) { throw err }
return done(null, newUser)
})
}
})
}))
passport.use('local-login', new LocalStrategy(function(username, password, done){
User.findOne({username: username}, function(err, user){
if(err) { return done(err) }
if(!user) { return done(null, false) }
if(!user.validPassword(password)) { return done(null, false) }
console.log('this is the user', user)
console.log('done', done)
return done(null, user)
})
}))
passport.serializeUser(function(user, done){
done(null, user.id)
})
passport.deserializeUser(function(user, done){
User.findById(user._id, function(err, user){
done(err, user)
})
})
}
<style>
span {
display: block;
}
</style>
<h1>Profile Page</h1>
<span>Username:</span>
<span><%= user.username %></span>
<span>Email:</span>
<span><%= user.email %></span>
<span>Questions Posted:</span>
<span><%= user.questions %></span>
<span>Answers Posted:</span>
<span><%= user.answers %></span>
'use strict'
var User = require('mongoose').model('User')
// route middleware to ensure user is logged in
function isLoggedIn(req, res, next){
console.log('req', req)
console.log('req.isAuthenticated', req.isAuthenticated())
if(req.isAuthenticated()) {
console.log('in isLoggedIn')
return next()
}
res.redirect('/')
}
module.exports = function(app, passport){
console.log('passport', passport)
app.route('/')
.get(function(req, res){
res.render('index')
})
app.get('/signUp', function(req, res){
res.render('signup')
})
app.route('/user')
.get(function(req, res){
})
.post(passport.authenticate('local-signup', { successRedirect: '/',
failureRedirect: 'signup' }))
app.route('/login')
.get(function(req, res){
res.render('login')
})
.post(passport.authenticate('local-login', { successRedirect: '/',
failureRedirect: '/login'}), function(req, res){
console.log('req.user', req.user)
})
app.get('/profile', isLoggedIn, function(req, res){
// res.send('test')
console.log('################################################# in /profile function parameter')
res.render('profile', { user: req.user })
})
/*
app.route('/profile')
.get(function(req, res){
console.log('req.user', req.user)
if(!req.user){
res.render('profile', {user: "You're not logged in"})
}
if(req.user){
res.render('profile', {user: req.user})
}
})
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.