Skip to content
Permalink
Browse files

move things around

  • Loading branch information...
Karan Goel
Karan Goel committed Jul 19, 2014
1 parent 14c8796 commit 91a109256b8f783d144435303af7dc4282083583
@@ -1 +1,2 @@
server/node_modules/
node_modules/
.DS_Store
@@ -0,0 +1 @@
web: node .
@@ -0,0 +1,67 @@
var express = require('express'),
http = require('http'),
routes = require('./private/routes'),
path = require('path'),
db = require('./private/db/connect'),
passport = require('passport'),
auth = require('./private/auth'),
Constants = require('./private/constants');

var app = express();
var RedisStore = require('connect-redis')(express);
var redis;

if (Constants.REDISTOGO_URL) {
console.log("using reditogo");
rtg = require('url').parse(Constants.REDISTOGO_URL);
redis = require('redis').createClient(rtg.port, rtg.hostname);
redis.auth(rtg.auth.split(':')[1]); // auth 1st part is username and 2nd is password separated by ":"
} else {
console.log("using local redis");
redis = require("redis").createClient();
}

app.configure(function(){
app.set('port', process.env.PORT || 8888);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('keyboard cat'));
app.use(express.session({
secret: 'YOLO',
store: new RedisStore({ client: redis })
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
});

//
// Routes
//

// GET
app.get('/', routes.index);
app.get('/auth/facebook', passport.authenticate("facebook", {scope:'email'}));
app.get('/auth/facebook/callback',
passport.authenticate('facebook', { failureRedirect: '/auth/error' }),
routes.authSuccess);
app.get('/auth/error', routes.authError);

app.get('/user', routes.getUser);
app.get('/next_thing', auth.requiresLogin, routes.nextThing);

app.get('/leaderboard', routes.leaderboard);

// POST
app.post('/submit_score', auth.requiresLogin, routes.submitScore);


require('./private/pass.js')(passport);

http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
File renamed without changes.
@@ -0,0 +1,9 @@
// Auth stuff

exports.requiresLogin = function (req, res, next) {
if (req.isAuthenticated()) {
return next();
} else {
res.redirect('/');
}
}
File renamed without changes.
@@ -0,0 +1,39 @@
/**
* Helpful database connection methods
*/

var Constants = require('../constants');

// Established database connection

var mongoose = require('mongoose');

var dbURI = Constants.MONGOLAB_URI;
mongoose.connect(dbURI);

// when connected with db
mongoose.connection.on('connected', function() {
console.log('Connected to db ' + dbURI);
});

// some error when connecting
mongoose.connection.on('error', function(err) {
console.log('Connection error: ' + err);
});

// disconnected from db
mongoose.connection.on('disconnected', function() {
console.log('Disconnected from DB.');
});

// If the Node process ends, close the Mongoose connection
process.on('SIGINT', function() {
mongoose.connection.close(function() {
console.log('Disconnected from DB by app.');
process.exit(0);
});
});

// bring in all models
require('./../models/user');
require('./../models/thing');
@@ -0,0 +1,23 @@
var mongoose = require('mongoose'),
Schema = mongoose.Schema;


var thingSchema = new Schema({
created_at: {
// auto added user registration timestamp
type: Date,
default: Date.now
},
thingType: {
type: String // one of {word, sentence, paragraph}
},
lang: {
type: String // one of {en, es, zh}
},
thing: {
type: String
}
});


module.exports = mongoose.model('Thing', thingSchema);
@@ -0,0 +1,44 @@
/*
Schema for a user.
*/

var mongoose = require('mongoose'),
Schema = mongoose.Schema;


// For any user
var userSchema = new Schema({
created_at: {
// auto added user registration timestamp
type: Date,
default: Date.now
},
accessToken: {
type: String
},
accessTokenSecret: {
type: String
},
photo: {
type: String
},
username: {
type: String,
unique: true
},
email: {
type: String,
unique: true,
lowercase: true // force email lowercase
},
name: {
type: String
},
fbId: String,
// scores and levels for each language
// format: levels.en.scores, or levels.en.level
levels: Object
});


module.exports = mongoose.model('User', userSchema);
@@ -0,0 +1,75 @@
/*
This is a wrapper for all code used for user authentication.
*/

var FacebookStrategy = require('passport-facebook').Strategy;
var Constants = require('./constants');


// bring in the schema for user
var User = require('mongoose').model('User');
var Thing = require('mongoose').model('Thing');
var request = require('request');

module.exports = function (passport) {

/*
user ID is serialized to the session. When subsequent requests are
received, this ID is used to find the user, which will be restored
to req.user.
*/
passport.serializeUser(function(user, done) {
console.log('serializeUser: ' + user._id)
done(null, user._id);
});

/*
intended to return the user profile based on the id that was serialized
to the session.
*/
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user){
// console.log(user)
if(!err) done(null, user);
else done(err, null)
})
});

// Logic for facebook strategy
passport.use(new FacebookStrategy({
clientID: Constants.Facebook.APPID,
clientSecret: Constants.Facebook.SECRET,
callbackURL: Constants.Facebook.CALLBACK
},
function(token, tokenSecret, profile, done) {
console.log(profile);
console.log('facebook authentication for ' + profile.displayName)
User.findOne({$or: [{fbId : profile.id }, {email: profile.emails[0].value}]}, function(err, oldUser) {
if (oldUser) {
return done(null, oldUser);
} else {
if (err) return done(err);

new User({
linkedinId: profile.id,
accessToken: token,
accessTokenSecret: tokenSecret,
email: profile.emails[0].value,
name: profile.displayName,
photo: profile._json.pictureUrl,
username: profile.emails[0].value.split('@')[0],
levels: {
en: { scores: 0, level: 1 },
es: { scores: 0, level: 1 },
zh: { scores: 0, level: 1 },
fr: { scores: 0, level: 1 }
}
}).save(function(err, newUser) {
if (err) return done(err);
return done(null, newUser);
});
}
});
}));

}
@@ -0,0 +1,68 @@
var User = require('./../models/user');
var Thing = require('./../models/thing');

exports.index = function (req, res){
// require('./../../save_gen');
if (req.isAuthenticated()) {
return res.render('index', {user: req.user});
} else {
return res.render('index');
}
};

exports.authError = function(req, res) {
res.redirect('/');
};

exports.authSuccess = function(req, res) {
res.redirect('/');
};

// Main functions

// get details for logged in user
exports.getUser = function(req, res) {
if (req.isAuthenticated()) {
return res.send(200, req.user);
} else {
return res.send(401, {});
}
}

// return next thing for the passed language
exports.nextThing = function(req, res) {
var lang = req.query.lang;
Thing.find({'lang': lang, 'thingType': req.user.levels[lang].level}, function(err, docs) {
if (err) return res.send(500);
res.send(200, docs[Math.floor(Math.random()*docs.length)]);
});
}

// submits the score for a thing
exports.submitScore = function(req, res) {
var lang = req.body.lang;
var score = +req.body.score;

User.findById(req.user._id, function(err, user) {
var newScore = user.levels[lang].scores + score;
if (newScore >= 200) {
newScore = 199;
}
req.user.levels[lang].scores = newScore;
req.user.levels[lang].level = Math.floor(newScore/100) + 1;

User.update({_id: req.user._id}, {$set: {levels: req.user.levels}},
function(err, newUser) {
console.log(req.user);
res.send(200, req.user)
});
});

}

// get all users for the leaderboard
exports.leaderboard = function(req, res) {
User.find({}, function(err, users) {
res.send(200, users);
});
}
Oops, something went wrong.

0 comments on commit 91a1092

Please sign in to comment.
You can’t perform that action at this time.