Last active
August 27, 2023 05:33
-
-
Save gabrielstuff/5733546 to your computer and use it in GitHub Desktop.
express + passport + session / req.session
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Module dependencies. | |
*/ | |
var express = require('express'), | |
mongoStore = require('connect-mongo')(express), | |
flash = require('connect-flash'), | |
viewHelpers = require('./middlewares/view'), | |
fs = require('fs'), | |
upload = require('jquery-file-upload-middleware'); | |
module.exports = function(app, config, passport) { | |
app.set('showStackError', true) | |
// should be placed before express.static | |
app.use(express.compress({ | |
filter: function(req, res) { | |
console.log(res.getHeader('Content-Type')); | |
return /json|text|javascript|css/.test(res.getHeader('Content-Type')); | |
}, | |
level: 9 | |
})) | |
app.use(express.static(config.root + '/public')) | |
// don't use logger for test env | |
if (process.env.NODE_ENV !== 'test') { | |
//app.use(express.logger('dev')) | |
var access_logfile = fs.createWriteStream('./access.log', { | |
flags: 'a' | |
}); | |
app.use(express.logger({ | |
stream: access_logfile | |
})); | |
} | |
// set views path, template engine and default layout | |
app.set('views', config.root + '/app/views') | |
app.set('view engine', 'jade') | |
upload.configure({ | |
//uploadDir: __dirname + '/public/uploads', | |
uploadDir: config.uploadPath, | |
//uploadUrl: '/uploads', | |
uploadUrl: config.uploadUrl, | |
imageTypes: /\.(mov|mp4|avi|m4v|gif|jpe?g|png)$/i, | |
imageVersions: { | |
thumbnail: { | |
width: 80, | |
height: 80 | |
} | |
}, | |
accessControl: { | |
allowOrigin: '*', | |
allowMethods: 'OPTIONS, HEAD, GET, POST, PUT' | |
}, | |
hostname:(require('os').hostname()).toLowerCase() | |
}); | |
app.configure(function() { | |
// dynamic helpers | |
app.use(viewHelpers(config)) | |
var secret = 'xxxxxxx'; | |
// cookieParser should be above session | |
app.use(express.cookieParser(secret)) | |
// bodyParser should be above methodOverride | |
app.use(config.uploadUrl, upload.fileHandler()); | |
upload.on('begin', function(fileInfo) { | |
console.log("fileInfo 0: ",fileInfo); | |
}); | |
upload.on('abort', function(fileInfo) { | |
console.log("fileInfo 1: ",fileInfo); | |
}); | |
upload.on('end', function(fileInfo) { | |
app.emit('file-uploaded', fileInfo); | |
}); | |
upload.on('delete', function(fileInfo) { | |
console.log("fileInfo 3: ", fileInfo); | |
}); | |
upload.on('error', function(e) { | |
console.log("fileUpload 4: ", e.message); | |
}); | |
app.use(express.bodyParser()) | |
app.use(express.methodOverride()) | |
// express/mongo session storage | |
app.use(express.session({ | |
secret: secret, | |
store: new mongoStore({ | |
url: config.db, | |
collection: 'sessions' | |
}) | |
})) | |
// connect flash for flash messages | |
app.use(flash()) | |
// use passport session | |
app.use(passport.initialize()) | |
app.use(passport.session()) | |
app.use(express.favicon()) | |
// routes should be at the last | |
app.use(app.router) | |
// assume "not found" in the error msgs | |
// is a 404. this is somewhat silly, but | |
// valid, you can do whatever you like, set | |
// properties, use instanceof etc. | |
app.use(function(err, req, res, next) { | |
// treat as 404 | |
if (~err.message.indexOf('not found')) return next() | |
// log it | |
console.error(err.stack) | |
// error page | |
res.status(500).render('500', { | |
error: err.stack | |
}) | |
}) | |
// assume 404 since no middleware responded | |
app.use(function(req, res, next) { | |
res.status(404).render('404', { | |
error: '', | |
url: req.originalUrl | |
}) | |
}) | |
}) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var mongoose = require('mongoose') | |
, LocalStrategy = require('passport-local').Strategy | |
, TwitterStrategy = require('passport-twitter').Strategy | |
, FacebookStrategy = require('passport-facebook').Strategy | |
, GitHubStrategy = require('passport-github').Strategy | |
, GoogleStrategy = require('passport-google-oauth').Strategy | |
, User = mongoose.model('User') | |
module.exports = function (passport, config) { | |
// require('./initializer') | |
// serialize sessions | |
passport.serializeUser(function(user, done) { | |
done(null, user.id) | |
}) | |
passport.deserializeUser(function(id, done) { | |
User.findOne({ _id: id }, function (err, user) { | |
done(err, user) | |
}) | |
}) | |
// use local strategy | |
passport.use(new LocalStrategy({ | |
usernameField: 'email', | |
passwordField: 'password' | |
}, | |
function(email, password, done) { | |
User.findOne({ email: email }, function (err, user) { | |
if (err) { return done(err) } | |
if (!user) { | |
return done(null, false, { message: 'Unknown user' }) | |
} | |
if (!user.authenticate(password)) { | |
return done(null, false, { message: 'Invalid password' }) | |
} | |
return done(null, user) | |
}) | |
} | |
)) | |
// use twitter strategy | |
passport.use(new TwitterStrategy({ | |
consumerKey: config.twitter.clientID | |
, consumerSecret: config.twitter.clientSecret | |
, callbackURL: config.twitter.callbackURL | |
}, | |
function(token, tokenSecret, profile, done) { | |
User.findOne({ 'twitter.id': profile.id }, function (err, user) { | |
if (err) { return done(err) } | |
if (!user) { | |
user = new User({ | |
name: profile.displayName | |
, username: profile.username | |
, provider: 'twitter' | |
, twitter: profile._json | |
}) | |
user.save(function (err) { | |
if (err) console.log(err) | |
return done(err, user) | |
}) | |
} | |
else { | |
return done(err, user) | |
} | |
}) | |
} | |
)) | |
// use facebook strategy | |
passport.use(new FacebookStrategy({ | |
clientID: config.facebook.clientID | |
, clientSecret: config.facebook.clientSecret | |
, callbackURL: config.facebook.callbackURL | |
}, | |
function(accessToken, refreshToken, profile, done) { | |
User.findOne({ 'facebook.id': profile.id }, function (err, user) { | |
if (err) { return done(err) } | |
if (!user) { | |
user = new User({ | |
name: profile.displayName | |
, email: profile.emails[0].value | |
, username: profile.username | |
, provider: 'facebook' | |
, facebook: profile._json | |
}) | |
user.save(function (err) { | |
if (err) console.log(err) | |
return done(err, user) | |
}) | |
} | |
else { | |
return done(err, user) | |
} | |
}) | |
} | |
)) | |
// use github strategy | |
passport.use(new GitHubStrategy({ | |
clientID: config.github.clientID, | |
clientSecret: config.github.clientSecret, | |
callbackURL: config.github.callbackURL | |
}, | |
function(accessToken, refreshToken, profile, done) { | |
User.findOne({ 'github.id': profile.id }, function (err, user) { | |
if (!user) { | |
user = new User({ | |
name: profile.displayName | |
, email: profile.emails[0].value | |
, username: profile.username | |
, provider: 'github' | |
, github: profile._json | |
}) | |
user.save(function (err) { | |
if (err) console.log(err) | |
return done(err, user) | |
}) | |
} else { | |
return done(err, user) | |
} | |
}) | |
} | |
)) | |
// use google strategy | |
passport.use(new GoogleStrategy({ | |
consumerKey: config.google.clientID, | |
consumerSecret: config.google.clientSecret, | |
callbackURL: config.google.callbackURL | |
}, | |
function(accessToken, refreshToken, profile, done) { | |
User.findOne({ 'google.id': profile.id }, function (err, user) { | |
if (!user) { | |
user = new User({ | |
name: profile.displayName | |
, email: profile.emails[0].value | |
, username: profile.username | |
, provider: 'google' | |
, google: profile._json | |
}) | |
user.save(function (err) { | |
if (err) console.log(err) | |
return done(err, user) | |
}) | |
} else { | |
return done(err, user) | |
} | |
}) | |
} | |
)); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require('express'), | |
root = global.root = process.cwd() + '/' | |
watcher = require('./app/controllers/saviors/watcher'), | |
twitter = require('./app/controllers/saviors/twitter'), | |
facebook = require('./app/controllers/facebook'), | |
nitrogram = require('./app/controllers/saviors/nitrogram'), | |
passport = require('passport'), | |
fs = require('fs'), | |
_ = require('underscore'), | |
sender = require('./app/controllers/sender'); | |
Reminder = require('reminder'), | |
push = require('pushover-notifications'); | |
/** | |
* Main application entry file. | |
* Please note that the order of loading is important. | |
*/ | |
// Load configurations | |
// if test env, load example file | |
var env = process.env.NODE_ENV || 'development', | |
config = require('./config/config')[env], | |
auth = require('./config/middlewares/authorization'), | |
mongoose = require('mongoose'); | |
// Bootstrap db connection | |
mongoose.connect(config.db) | |
//Bootstrap facebook connection | |
facebook.connect(config.facebook.clientID, config.facebook.clientSecret); | |
var remind = new Reminder(); | |
// Bootstrap models | |
var models_path = __dirname + '/app/models' | |
fs.readdirSync(models_path).forEach(function(file) { | |
if (file.indexOf('.js')) { | |
require(models_path + '/' + file); | |
} | |
}); | |
// bootstrap passport config | |
require('./config/passport')(passport, config) | |
var app = express(), | |
https = require('https'), | |
server = require('http').createServer(app), | |
socketServer = sender.attach(server); | |
//console.log(server); | |
var keys_dir = './key/', | |
server_options = { | |
key: fs.readFileSync(keys_dir + 'privatekey.pem'), | |
ca: fs.readFileSync(keys_dir + 'server.csr'), | |
cert: fs.readFileSync(keys_dir + 'server.pem') | |
}; | |
twitter.init(); | |
watcher.init(config.pathToWatch); | |
// express settings | |
require('./config/express')(app, config, passport); | |
// Bootstrap routes | |
require('./config/routes')(app, passport, auth); | |
// Start the app by listening on <port> | |
var port = process.env.PORT || 3000; | |
https.createServer(server_options, app).listen(7000) | |
server.listen(port, function() { | |
console.log("Ramsey app started on port " + port); | |
var p = new push({ | |
user: config.pushover.user, | |
token: config.pushover.token | |
}); | |
var msg = { | |
message: 'App is up and running on '+("http://" + require('os').hostname() + "/").toLowerCase(), | |
title: "App update", | |
sound: 'magic', | |
priority: 1 | |
}; | |
p.send(msg, function(err, result) { | |
if (err) { | |
throw err; | |
} | |
console.log(result); | |
}); | |
}); | |
// expose app | |
exports = module.exports = app |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment