var express = require('express'),
WebServer = express(),
server = require('http').createServer(WebServer),
RedisStore = require('connect-redis')(express),
path = require('path'),
config = require('../config.js'),
redis = require('redis'),
redisServer = redis.createClient(config.redis.port, config.redis.host, config.redis.options),
passport = require('passport'),
passportLocal = require('passport-local').Strategy,
passportTwitter = require('passport-twitter').Strategy,
passportGoogle = require('passport-google-oauth').OAuth2Strategy,
passportFacebook = require('passport-facebook').Strategy,
user = require('./user.js'),
utils = require('./utils.js'),
login_strategies = [];
passport.use(new passportLocal(function(user, password, next) {
global.modules.user.loginViaLocal(user, password, function(login) {
if (login.status === 'ok') next(null, login.user);
else next(null, false, login);
});
}));
if (config.twitter && config.twitter.key && config.twitter.key.length > 0 && config.twitter.secret.length > 0) {
passport.use(new passportTwitter({
consumerKey: config.twitter.key,
consumerSecret: config.twitter.secret,
callbackURL: config.url + 'auth/twitter/callback'
}, function(token, tokenSecret, profile, done) {
global.modules.user.loginViaTwitter(profile.id, profile.username, function(err, user) {
if (err) { return done(err); }
done(null, user);
});
}));
login_strategies.push('twitter');
}
if (config.google && config.google.id.length > 0 && config.google.secret.length > 0) {
passport.use(new passportGoogle({
clientID: config.google.id,
clientSecret: config.google.secret,
callbackURL: config.url + 'auth/google/callback'
}, function(accessToken, refreshToken, profile, done) {
global.modules.user.loginViaGoogle(profile.id, profile.displayName, profile.emails[0].value, function(err, user) {
if (err) { return done(err); }
done(null, user);
});
}));
login_strategies.push('google');
}
if (config.facebook && config.facebook.app_id.length > 0 && config.facebook.secret.length > 0) {
passport.use(new passportFacebook({
clientID: config.facebook.app_id,
clientSecret: config.facebook.secret,
callbackURL: config.url + 'auth/facebook/callback'
}, function(accessToken, refreshToken, profile, done) {
global.modules.user.loginViaFacebook(profile.id, profile.displayName, profile.emails[0].value, function(err, user) {
if (err) { return done(err); }
done(null, user);
});
}));
login_strategies.push('facebook');
}
passport.serializeUser(function(user, done) {
done(null, user.uid);
});
passport.deserializeUser(function(uid, done) {
done(null, {
uid: uid
});
});
(function(app) {
var templates = global.templates;
// Middlewares
app.use(express.favicon()); // 2 args: string path and object options (i.e. expire time etc)
app.use(require('less-middleware')({ src: path.join(__dirname, '../', '/public') }));
app.use(express.static(path.join(__dirname, '../', 'public')));
app.use(express.bodyParser()); // Puts POST vars in request.body
app.use(express.cookieParser()); // If you want to parse cookies (res.cookies)
app.use(express.compress());
app.use(express.session({
store: new RedisStore({
client: redisServer,
ttl: 60*60*24*14
}),
secret: config.secret,
key: 'express.sid'
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(function(req, res, next) {
// Don't bother with session handling for API requests
if (/^\/api\//.test(req.url)) return next();
if (req.user && req.user.uid) {
global.modules.user.session_ping(req.sessionID, req.user.uid);
}
// (Re-)register the session as active
global.modules.user.active.register(req.sessionID);
next();
});
// Dunno wtf this does
// app.use(express.logger({ format: '\x1b[1m:method\x1b[0m \x1b[33m:url\x1b[0m :response-time ms' }));
// Useful if you want to use app.put and app.delete (instead of app.post all the time)
// app.use(express.methodOverride());
app.get('/403', function(req, res) {
res.send(templates['header'] + templates['403'] + templates['footer']);
});
function create_route(url, tpl) {
return '';
}
// Basic Routes (entirely client-side parsed, goal is to move the rest of the crap in this file into this one section)
(function() {
var routes = ['', 'login', 'register', 'account', 'latest', 'popular', 'active'];
for (var i=0, ii=routes.length; i 0)) {
res.redirect('/account');
return;
}
res.send(templates['header'] + create_route(route) + templates['footer']);
});
}(routes[i]));
}
}());
// Complex Routes
app.get('/topic/:topic_id/:slug?', function(req, res) {
var topic_url = req.params.topic_id + (req.params.slug ? '/' + req.params.slug : '');
res.send(templates['header'] + '' + templates['footer']);
});
app.get('/category/:category_id/:slug?', function(req, res) {
var category_url = req.params.category_id + (req.params.slug ? '/' + req.params.slug : '');
res.send(templates['header'] + '' + templates['footer']);
});
app.get('/confirm/:code', function(req, res) {
res.send(templates['header'] + '' + templates['footer']);
});
// These functions are called via ajax once the initial page is loaded to populate templates with data
function api_method(req, res) {
switch(req.params.method) {
case 'home' :
global.modules.categories.get(function(data) {
res.send(JSON.stringify(data));
});
break;
case 'login' :
var data = {},
num_strategies = login_strategies.length;
if (num_strategies == 0) {
data = {
'login_window:spansize': 'span12',
'alternate_logins:display': 'none'
};
} else {
data = {
'login_window:spansize': 'span6',
'alternate_logins:display': 'block'
}
for (var i=0, ii=num_strategies; itemplates.ready(function(){ajaxify.go("users/' + req.params.uid+'/edit");});' + templates['footer']);
}
else
return res.redirect('/403');
});
app.get('/users/:username*', handleUserProfile);
function handleUserProfile(req, res) {
if(!req.params.username) {
res.send("User doesn't exist!");
return;
}
user.get_uid_by_username(req.params.username, function(uid) {
user.getUserData(uid, function(data) {
if(data) {
//res.send(templates['header'] + '' + templates['footer']);
res.send(templates['header'] + create_route('users/'+data.username,'users') + templates['footer']);
}
else {
res.send("User doesn't exist! /users/"+req.params.username);
}
});
});
}
app.get('/test', function(req, res) {
global.modules.topics.delete(1, 1);
res.send();
});
}(WebServer));
server.listen(config.port);
global.server = server;