Auth- Added Back-end Logic

removed personal details
This commit is contained in:
Curtis SerVaas
2014-08-07 16:21:19 -04:00
parent 91661c448c
commit bd8b510a73
8 changed files with 220 additions and 83 deletions
+38 -30
View File
@@ -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();
}
}
+8
View File
@@ -0,0 +1,8 @@
module.exports = {
'googleAuth' : {
'clientID' : 'your-secret-clientID-here',
'clientSecret' : 'your-client-secret-here',
'callbackURL' : 'http://localhost:3000/auth/google/callback'
}
};
+15
View File
@@ -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");
}
+80
View File
@@ -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);
});
}
});
});
}));
};
-25
View File
@@ -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()
}
+65
View File
@@ -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
+10 -27
View File
@@ -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');
}
});
// create the model for users and expose it to our app
module.exports = mongoose.model('User', userSchema);
+4 -1
View File
@@ -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": {