From bd8b510a73ad8dccfcf7a7565e889332f1e260ed Mon Sep 17 00:00:00 2001 From: Curtis SerVaas Date: Thu, 7 Aug 2014 16:21:19 -0400 Subject: [PATCH] Auth- Added Back-end Logic removed personal details --- app.js | 68 ++++++++++++++++++++++----------------- config/auth.js | 8 +++++ config/database.js | 15 +++++++++ config/passport.js | 80 ++++++++++++++++++++++++++++++++++++++++++++++ lib/db.js | 25 --------------- lib/routes.js | 65 +++++++++++++++++++++++++++++++++++++ models/User.js | 37 ++++++--------------- package.json | 5 ++- 8 files changed, 220 insertions(+), 83 deletions(-) create mode 100644 config/auth.js create mode 100644 config/database.js create mode 100644 config/passport.js delete mode 100644 lib/db.js create mode 100644 lib/routes.js diff --git a/app.js b/app.js index d995fca..e0debe4 100644 --- a/app.js +++ b/app.js @@ -1,55 +1,63 @@ - -/** - * Module dependencies. - */ - var express = require('express'); -// var routes = require('./routes/routes.js'); -var fs = require('fs'); -var http = require('http'); -var path = require('path'); -var crypto = require('crypto'); +var app = express(); +var port = process.env.PORT || 3000; + +var passport = require('passport'); +var flash = require('connect-flash'); +require('./config/passport')(passport); // pass passport for configuration + + +require('./config/database.js').safeConnect(); + var db = require('./lib/db'); var helperLib = require('./lib/helperLib.js'); -var app = express() -var server = http.Server(app); -helperLib.createSocket(server); -server.listen(process.env.PORT || 3000); +// var routes = require('./routes/routes.js'); +var http = require('http'); +var path = require('path'); // all environments -app.set('port', process.env.PORT || 3000); -app.set('views', path.join(__dirname, 'views')); +app.set('port', port); + +// app.set('views', path.join(__dirname, 'views')); +app.set('views', __dirname + '/views'); +// app.use(express.static(path.join(__dirname, 'public'))); +app.use(express.static(__dirname + '/public')); //ALREADY USING IT. app.set('view engine', 'ejs'); -app.use(express.favicon()); + app.use(express.logger('dev')); +app.use(express.favicon()); app.use(express.json()); app.use(express.urlencoded()); app.use(express.methodOverride()); app.use(app.router); -app.use(express.static(path.join(__dirname, 'public'))); +app.use(express.cookieParser()); //(I've also installed cookie module) +app.use(express.bodyParser()); //not sure... app.use(express.session({secret: 'secretpasswordforsessions', store: helperLib.getSessionStore()})); +//the session stuff differs from the scotch tutorial. + +app.use(passport.initialize()); +app.use(passport.session()); +app.use(flash()); -app.configure(function () { - app.use(express.bodyParser()); //not sure... - app.set('views', __dirname + '/views'); - app.set('view engine', 'ejs'); - app.use(express.static(__dirname + '/public')); //ALREADY USING IT. -}); app.set('view options', { layout: false }); -app.get('/',function(req,res){ - console.log("\n\nrenderingIndex\n") - res.render('index'); -}); + + + + +var server = http.Server(app); +helperLib.createSocket(server); +server.listen(port); + + if(process.argv[2] == "restart"){ console.log("restarting"); helperLib.setUpDB(); -} - +} \ No newline at end of file diff --git a/config/auth.js b/config/auth.js new file mode 100644 index 0000000..461932a --- /dev/null +++ b/config/auth.js @@ -0,0 +1,8 @@ +module.exports = { + 'googleAuth' : { + 'clientID' : 'your-secret-clientID-here', + 'clientSecret' : 'your-client-secret-here', + 'callbackURL' : 'http://localhost:3000/auth/google/callback' + } +}; + diff --git a/config/database.js b/config/database.js new file mode 100644 index 0000000..58dd181 --- /dev/null +++ b/config/database.js @@ -0,0 +1,15 @@ +var mongoose = require('mongoose'); + +// Connect to cloud database +//https://mongolab.com/ +var username = "throwaway" +var password = "throwaway1"; +var address = '@ds037637.mongolab.com:37637/throwaway_db'; +var url = 'mongodb://' + username + ':' + password + address; + +function safeConnect() { + try { mongoose.connect(url); } + catch(err) { console.log("Error: Sign In to MongoLab") } + // console.log("error caught"); +} + diff --git a/config/passport.js b/config/passport.js new file mode 100644 index 0000000..c1781a8 --- /dev/null +++ b/config/passport.js @@ -0,0 +1,80 @@ +// config/passport.js + +// load all the things we need +// var LocalStrategy = require('passport-local').Strategy; +var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy; + +// load up the user model +var User = require('../models/user'); + +// load the auth variables +var configAuth = require('./auth'); + +module.exports = function(passport) { + + // used to serialize the user for the session + passport.serializeUser(function(user, done) { + done(null, user.id); + }); + + // used to deserialize the user + passport.deserializeUser(function(id, done) { + User.findById(id, function(err, user) { + done(err, user); + }); + }); + + // code for login (use('local-login', new LocalStategy)) + // code for signup (use('local-signup', new LocalStategy)) + // code for facebook (use('facebook', new FacebookStrategy)) + // code for twitter (use('twitter', new TwitterStrategy)) + + // ========================================================================= + // GOOGLE ================================================================== + // ========================================================================= + passport.use(new GoogleStrategy({ + + clientID : configAuth.googleAuth.clientID, + clientSecret : configAuth.googleAuth.clientSecret, + callbackURL : configAuth.googleAuth.callbackURL, + + }, + function(token, refreshToken, profile, done) { + + // make the code asynchronous + // User.findOne won't fire until we have all our data back from Google + process.nextTick(function() { + + // try to find the user based on their google id + User.findOne({ 'google.id' : profile.id }, function(err, user) { + if (err) + return done(err); + + if (user) { // if a user is found, log them in + return done(null, user); + } + + else { + // if the user isnt in our database, create a new user + var newUser = new User(); + + // set all of the relevant information + newUser.google.id = profile.id; + newUser.google.token = token; + newUser.google.name = profile.displayName; + newUser.google.email = profile.emails[0].value; // pull the first email + + // save the user + newUser.save(function(err) { + if (err) + throw err; + return done(null, newUser); + }); + } + }); + }); + + })); + +}; + diff --git a/lib/db.js b/lib/db.js deleted file mode 100644 index 4963d13..0000000 --- a/lib/db.js +++ /dev/null @@ -1,25 +0,0 @@ -var mongoose = require('mongoose'); -var Schema = mongoose.Schema; -module.exports.mongoose = mongoose; -module.exports.Schema = Schema; - -// Connect to cloud database -//https://mongolab.com/ -var username = "throwaway" -var password = "throwaway1";// -var address = '@ds037637.mongolab.com:37637/throwaway_db'; -connect(); - - -// Connect to mongo -function connect() { - - var url = 'mongodb://' + username + ':' + password + address; - try { mongoose.connect(url); } - catch(err) { console.log("Error: Sign In to MongoLab") } - console.log("error caught"); - -} -function disconnect() { - mongoose.disconnect() -} diff --git a/lib/routes.js b/lib/routes.js new file mode 100644 index 0000000..4784a06 --- /dev/null +++ b/lib/routes.js @@ -0,0 +1,65 @@ +module.exports = function(app, passport) { + + app.get('/', function(req, res) { res.render('index'); } ); + + // route for logging out + app.get('/logout', function(req, res) { + req.logout(); + res.redirect('/'); + }); + + + + + app.get('/auth/google', passport.authenticate('google', { scope : ['profile', 'email'] })); + + // the callback after google has authenticated the user + app.get('/auth/google/callback', + passport.authenticate('google', { + successRedirect : '/profile', + failureRedirect : '/' + })); +}; + +// route middleware to make sure a user is logged in +function isLoggedIn(req, res, next) { + + // if user is authenticated in the session, carry on + if (req.isAuthenticated()) + return next(); + + // if they aren't redirect them to the home page + res.redirect('/'); +} + + + + + + + + + + + +// // route for login form +// // route for processing the login form +// // route for signup form +// // route for processing the signup form + +// // route for showing the profile page +// app.get('/profile', isLoggedIn, function(req, res) { +// res.render('profile.ejs', { +// user : req.user // get the user out of session and pass to template +// }); +// }); + +// // facebook routes +// // twitter routes + +// // ===================================== +// // GOOGLE ROUTES ======================= +// // ===================================== +// // send to google to do the authentication +// // profile gets us their basic information including their name +// // email gets their emails \ No newline at end of file diff --git a/models/User.js b/models/User.js index e9f187d..17c01e5 100644 --- a/models/User.js +++ b/models/User.js @@ -1,29 +1,12 @@ -//(not being used yet) +var mongoose = require('mongoose'); -var crypto = require('crypto') -var db = require('../lib/db'); -var UserSchema = new db.Schema({ - username : {type: String, unique: true} - , password : String -}) -var MyUser = db.mongoose.model('User', UserSchema); -// Exports -module.exports.addUser = addUser; -// Add user to database -function addUser(username, password, callback) { - var instance = new MyUser(); - instance.username = username; - instance.password = encryptPassword(password); - instance.save(function (err) { - if (err) { - callback(err); -} - else { - callback(null, instance); +var userSchema = mongoose.Schema({ + google : { + id : String, + token : String, + email : String, + name : String } - }); -} - -function encryptPassword(plainText) { - return crypto.createHash('md5').update(plainText).digest('hex'); -} \ No newline at end of file +}); +// create the model for users and expose it to our app +module.exports = mongoose.model('User', userSchema); \ No newline at end of file diff --git a/package.json b/package.json index fe1ffa2..290259f 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,10 @@ "mongodb": "^1.1.7", "socket.io": "0.9.13", "cookie": "0.0.4", - "underscore": "1.5.2" + "underscore": "1.5.2", + "passport": "^0.2.0", + "passport-google-oauth": "^0.1.5", + "connect-flash": "^0.1.1" }, "subdomain": "ndent", "engines": {