Merge pull request #1 from designcreateplay/master

Merge changes into repo for edit
v1.18.x
Quinton Marchi 11 years ago
commit f5c4f98834

@ -66,6 +66,7 @@
nconf.set('upload_url', nconf.get('url') + 'uploads/'); nconf.set('upload_url', nconf.get('url') + 'uploads/');
winston.info('Initializing NodeBB v' + pkg.version + ', on port ' + nconf.get('port') + ', using Redis store at ' + nconf.get('redis:host') + ':' + nconf.get('redis:port') + '.'); winston.info('Initializing NodeBB v' + pkg.version + ', on port ' + nconf.get('port') + ', using Redis store at ' + nconf.get('redis:host') + ':' + nconf.get('redis:port') + '.');
winston.info('NodeBB instance bound to: ' + (nconf.get('bind_address') || 'Any address'));
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
winston.info('Base Configuration OK.'); winston.info('Base Configuration OK.');

@ -1,7 +1,4 @@
{ {
"disconnect.title": "Socket Disconnect",
"disconnect.message": "Looks like you disconnected, try reloading the page.",
"disconnect.reload_button": "Reload",
"chat.chatting_with": "Chat with <span id='chat-with-name'></span>", "chat.chatting_with": "Chat with <span id='chat-with-name'></span>",
"chat.placeholder": "type chat message, here press enter to send", "chat.placeholder": "type chat message, here press enter to send",
"chat.send": "Send", "chat.send": "Send",

@ -1,5 +1,6 @@
{ {
"profile": "Profile", "profile": "Profile",
"posted_by": "Posted by",
"chat": "Chat", "chat": "Chat",
"notify_me": "Be notified of new replies in this topic", "notify_me": "Be notified of new replies in this topic",
"favourite": "Favourite", "favourite": "Favourite",

@ -38,8 +38,8 @@ var ajaxify = {};
window.onscroll = null; window.onscroll = null;
// end // end
// Remove trailing slash
var url = url.replace(/\/$/, ""); url = url.replace(/\/$/, "");
var hash = window.location.hash; var hash = window.location.hash;

@ -1,8 +1,6 @@
var socket, var socket,
config, config,
app = {}, app = {};
API_URL = null;
(function () { (function () {
var showWelcomeMessage = false; var showWelcomeMessage = false;
@ -12,8 +10,6 @@ var socket,
$.ajax({ $.ajax({
url: RELATIVE_PATH + '/api/config', url: RELATIVE_PATH + '/api/config',
success: function (data) { success: function (data) {
API_URL = data.api_url;
config = data; config = data;
if(socket) { if(socket) {
socket.disconnect(); socket.disconnect();
@ -23,8 +19,8 @@ var socket,
} else { } else {
socket = io.connect(config.socket.address); socket = io.connect(config.socket.address);
var reconnecting = false; var reconnecting = false,
var reconnectTries = 0; reconnectEl, reconnectTimer;
socket.on('event:connect', function (data) { socket.on('event:connect', function (data) {
app.username = data.username; app.username = data.username;
@ -40,17 +36,12 @@ var socket,
socket.on('connect', function (data) { socket.on('connect', function (data) {
if (reconnecting) { if (reconnecting) {
setTimeout(function () { reconnectEl.html('<i class="icon-ok"></i> Connected!');
app.alert({
alert_id: 'connection_alert',
title: 'Connected',
message: 'Connection successful.',
type: 'success',
timeout: 5000
});
}, 1000);
reconnecting = false; reconnecting = false;
reconnectTries = 0;
setTimeout(function() {
reconnectEl.removeClass('active');
}, 3000);
} }
socket.emit('api:updateHeader', { socket.emit('api:updateHeader', {
@ -63,33 +54,11 @@ var socket,
}); });
socket.on('reconnecting', function (data) { socket.on('reconnecting', function (data) {
function showDisconnectModal() { if (!reconnectEl) reconnectEl = $('#reconnect');
$('#disconnect-modal').modal({
backdrop: 'static',
show: true
});
$('#reload-button').on('click', function () {
$('#disconnect-modal').modal('hide');
window.location.reload();
});
}
reconnecting = true; reconnecting = true;
reconnectTries++;
if (reconnectTries > 4) {
showDisconnectModal();
return;
}
app.alert({ reconnectEl.addClass('active');
alert_id: 'connection_alert', reconnectEl.html('<i class="icon-spinner icon-spin"></i> Reconnecting...');
title: 'Reconnecting',
message: 'You have disconnected from NodeBB, we will try to reconnect you. <br/><i class="icon-refresh icon-spin"></i>',
type: 'warning',
timeout: 5000
});
}); });
socket.on('api:user.get_online_users', function (users) { socket.on('api:user.get_online_users', function (users) {

@ -102,7 +102,7 @@ var nodebb_admin = (function(nodebb_admin) {
alert_id: 'config_status', alert_id: 'config_status',
timeout: 2500, timeout: 2500,
title: 'Changes Saved', title: 'Changes Saved',
message: 'Your changes to the NodeBB configuration have been saved. You may have to restart NodeBB to see the changes.', message: 'Your changes to the NodeBB configuration have been saved.',
type: 'success' type: 'success'
}); });
} else { } else {

@ -83,23 +83,6 @@
return false; return false;
}); });
$('#users-container').on('click', '.delete-btn', function() {
var deleteBtn = $(this);
var isAdmin = isUserAdmin(deleteBtn);
var parent = deleteBtn.parents('.users-box');
var uid = getUID(deleteBtn);
if (!isAdmin) {
bootbox.confirm('Do you really want to delete "' + parent.attr('data-username') + '"?', function(confirm) {
if (confirm) {
socket.emit('api:admin.user.deleteUser', uid);
}
});
}
return false;
});
$('#users-container').on('click', '.ban-btn', function() { $('#users-container').on('click', '.ban-btn', function() {
var banBtn = $(this); var banBtn = $(this);
var isAdmin = isUserAdmin(banBtn); var isAdmin = isUserAdmin(banBtn);

@ -234,7 +234,6 @@
if ($(window).scrollTop() > bottom && !app.infiniteLoaderActive && $('#post-container').children().length) { if ($(window).scrollTop() > bottom && !app.infiniteLoaderActive && $('#post-container').children().length) {
app.loadMorePosts(tid); app.loadMorePosts(tid);
console.log('window scrolling');
} }
}); });
} }

@ -187,7 +187,15 @@ define(['taskbar'], function(taskbar) {
switch(action) { switch(action) {
case 'post': composer.post(uuid); break; case 'post': composer.post(uuid); break;
case 'minimize': composer.minimize(uuid); break; case 'minimize': composer.minimize(uuid); break;
case 'discard': composer.discard(uuid); break; case 'discard':
if (postContentEl.value.length > 0) {
bootbox.confirm('Are you sure you wish to discard this post?', function(discard) {
if (discard) composer.discard(uuid);
});
} else {
composer.discard(uuid);
}
break;
} }
}); });

@ -114,13 +114,9 @@
templates.load_template = function (callback, url, template) { templates.load_template = function (callback, url, template) {
var location = document.location || window.location, var location = document.location || window.location,
rootUrl = location.protocol + '//' + (location.hostname || location.host) + (location.port ? ':' + location.port : ''); api_url = (url === '' || url === '/') ? 'home' : url,
tpl_url = templates.get_custom_map(api_url.split('?')[0]),
var api_url = (url === '' || url === '/') ? 'home' : url; trimmed = api_url;
var tpl_url = templates.get_custom_map(api_url.split('?')[0]);
var trimmed = api_url;
if (!tpl_url) { if (!tpl_url) {
tpl_url = templates.getTemplateNameFromUrl(api_url); tpl_url = templates.getTemplateNameFromUrl(api_url);
@ -128,7 +124,6 @@
var template_data = null; var template_data = null;
(function () { (function () {
var timestamp = new Date().getTime(); //debug var timestamp = new Date().getTime(); //debug
@ -155,8 +150,7 @@
}()); }());
(function () { (function () {
jQuery.get(RELATIVE_PATH + '/api/' + api_url, function (data) {
jQuery.get(API_URL + api_url, function (data) {
if (!data) { if (!data) {
ajaxify.go('404'); ajaxify.go('404');

@ -58,6 +58,9 @@
<li> <li>
<a href="/admin/settings"><i class="icon-cogs"></i> Settings</a> <a href="/admin/settings"><i class="icon-cogs"></i> Settings</a>
</li> </li>
<li>
<a href="#" id="reconnect"></a>
</li>
</ul> </ul>
<ul class="nav pull-right" id="right-menu"> <ul class="nav pull-right" id="right-menu">
<li><a href="/users" id="user_label"></a></li> <li><a href="/users" id="user_label"></a></li>

@ -10,7 +10,7 @@ jQuery(document).ready(function () {
QUnit.init(); QUnit.init();
asyncTest( "Loading Categories", function() { asyncTest( "Loading Categories", function() {
jQuery.get(config.api_url + 'home', function(data) { jQuery.get(RELATIVE_PATH + '/api/home', function(data) {
ok( data.categories.length > 0, JSON.stringify(data.categories) ); ok( data.categories.length > 0, JSON.stringify(data.categories) );
start(); start();

@ -2,22 +2,6 @@
</div><!--END container --> </div><!--END container -->
<div id="disconnect-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="You were disconnected" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h3 id="myModalLabel">[[footer:disconnect.title]]</h3>
</div>
<div class="modal-body">
<span id="disconnect-text">[[footer:disconnect.message]]</span>
</div>
<div class="modal-footer">
<a id="reload-button" href="/" class="btn btn-primary">[[footer:disconnect.reload_button]]</a>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<div id="chat-modal" class="modal" tabindex="-1" role="dialog" aria-labelledby="Chat" aria-hidden="true"> <div id="chat-modal" class="modal" tabindex="-1" role="dialog" aria-labelledby="Chat" aria-hidden="true">
<div class="modal-dialog"> <div class="modal-dialog">
<div class="modal-content"> <div class="modal-content">

@ -69,6 +69,10 @@
</form> </form>
<ul id="logged-in-menu" class="nav navbar-nav navbar-right hide"> <ul id="logged-in-menu" class="nav navbar-nav navbar-right hide">
<li>
<a href="#" id="reconnect"></a>
</li>
<li id="notifications-list" class="notifications dropdown text-center hidden-xs"> <li id="notifications-list" class="notifications dropdown text-center hidden-xs">
<a class="dropdown-toggle" data-toggle="dropdown" href="#" id="notif_dropdown"><i class="icon-circle-blank"></i></a> <a class="dropdown-toggle" data-toggle="dropdown" href="#" id="notif_dropdown"><i class="icon-circle-blank"></i></a>
<ul id="notif-list" class="dropdown-menu" aria-labelledby="notif_dropdown"> <ul id="notif-list" class="dropdown-menu" aria-labelledby="notif_dropdown">

@ -27,7 +27,7 @@
<div class="topic-buttons"> <div class="topic-buttons">
<div class="btn-group"> <div class="btn-group">
<button class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" type="button" title="[[topic:posted_by, {main_posts.username}]]"> <button class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" type="button" title="[[topic:posted_by]] {main_posts.username}">
<span class="username-field" href="/user/{main_posts.userslug}">{main_posts.username}&nbsp;</span> <span class="username-field" href="/user/{main_posts.userslug}">{main_posts.username}&nbsp;</span>
<span class="caret"></span> <span class="caret"></span>
</button> </button>

@ -65,3 +65,19 @@
overflow: hidden; overflow: hidden;
} }
} }
#reconnect {
font-size: 14px;
-webkit-transition: opacity 250ms linear;
-moz-transition: opacity 250ms linear;
-ms-transition: opacity 250ms linear;
-o-transition: opacity 250ms linear;
transition: opacity 250ms linear;
-moz-opacity: 0.00;
opacity: 0.00;
&.active {
-moz-opacity: 1;
opacity: 1;
}
}

@ -11,8 +11,6 @@ var RDB = require('../redis'),
Groups.getGidFromName('Administrators', function(err, gid) { Groups.getGidFromName('Administrators', function(err, gid) {
Groups.join(gid, theirid, function(err) { Groups.join(gid, theirid, function(err) {
if (!err) { if (!err) {
user.setUserField(theirid, 'administrator', 1);
socket.emit('event:alert', { socket.emit('event:alert', {
title: 'User Modified', title: 'User Modified',
message: 'This user is now an administrator!', message: 'This user is now an administrator!',
@ -39,7 +37,6 @@ var RDB = require('../redis'),
Groups.getGidFromName('Administrators', function(err, gid) { Groups.getGidFromName('Administrators', function(err, gid) {
Groups.leave(gid, theirid, function(err) { Groups.leave(gid, theirid, function(err) {
if (!err) { if (!err) {
user.setUserField(theirid, 'administrator', 0);
socket.emit('event:alert', { socket.emit('event:alert', {
title: 'User Modified', title: 'User Modified',
@ -54,24 +51,6 @@ var RDB = require('../redis'),
}); });
}; };
UserAdmin.deleteUser = function(uid, theirid, socket) {
user.isAdministrator(uid, function(amIAdmin) {
user.isAdministrator(theirid, function(areTheyAdmin) {
if (amIAdmin && !areTheyAdmin) {
user.delete(theirid, function(data) {
socket.emit('event:alert', {
title: 'User Deleted',
message: 'This user is deleted!',
type: 'success',
timeout: 2000
});
});
}
});
});
};
UserAdmin.banUser = function(uid, theirid, socket) { UserAdmin.banUser = function(uid, theirid, socket) {
user.isAdministrator(uid, function(amIAdmin) { user.isAdministrator(uid, function(amIAdmin) {
user.isAdministrator(theirid, function(areTheyAdmin) { user.isAdministrator(theirid, function(areTheyAdmin) {

@ -7,9 +7,12 @@ var utils = require('./../public/src/utils.js'),
nconf = require('nconf'); nconf = require('nconf');
(function (Meta) { (function (Meta) {
Meta.config = {};
Meta.configs = { Meta.configs = {
init: function (callback) { init: function (callback) {
delete Meta.config;
Meta.configs.list(function (err, config) { Meta.configs.list(function (err, config) {
if (!err) { if (!err) {
Meta.config = config; Meta.config = config;
@ -39,6 +42,8 @@ var utils = require('./../public/src/utils.js'),
set: function (field, value, callback) { set: function (field, value, callback) {
RDB.hset('config', field, value, function (err, res) { RDB.hset('config', field, value, function (err, res) {
if (callback) { if (callback) {
if(!err && Meta.config)
Meta.config[field] = value;
callback(err, res); callback(err, res);
} }
}); });
@ -160,33 +165,7 @@ var utils = require('./../public/src/utils.js'),
'src/ajaxify.js', 'src/ajaxify.js',
'src/translator.js', 'src/translator.js',
'src/jquery.form.js', 'src/jquery.form.js',
'src/utils.js', 'src/utils.js'
'src/forum/account.js',
'src/forum/accountedit.js',
'src/forum/accountheader.js',
'src/forum/accountsettings.js',
'src/forum/category.js',
'src/forum/favourites.js',
'src/forum/followers.js',
'src/forum/following.js',
'src/forum/footer.js',
'src/forum/login.js',
'src/forum/recent.js',
'src/forum/register.js',
'src/forum/reset.js',
'src/forum/reset_code.js',
'src/forum/search.js',
'src/forum/topic.js',
'src/forum/unread.js',
'src/forum/users.js',
'src/forum/admin/categories.js',
'src/forum/admin/footer.js',
'src/forum/admin/groups.js',
'src/forum/admin/index.js',
'src/forum/admin/plugins.js',
'src/forum/admin/themes.js',
'src/forum/admin/topics.js',
'src/forum/admin/users'
], ],
minFile: path.join(__dirname, '..', 'public/src/nodebb.min.js'), minFile: path.join(__dirname, '..', 'public/src/nodebb.min.js'),
get: function (callback) { get: function (callback) {

@ -26,7 +26,6 @@ var fs = require('fs'),
function(plugins, next) { function(plugins, next) {
if (plugins && Array.isArray(plugins) && plugins.length > 0) { if (plugins && Array.isArray(plugins) && plugins.length > 0) {
async.each(plugins, function(plugin, next) { async.each(plugins, function(plugin, next) {
// TODO: Update this check to also check node_modules
var pluginPath = path.join(__dirname, '../plugins/', plugin), var pluginPath = path.join(__dirname, '../plugins/', plugin),
modulePath = path.join(__dirname, '../node_modules/', plugin); modulePath = path.join(__dirname, '../node_modules/', plugin);
if (fs.existsSync(pluginPath)) _self.loadPlugin(pluginPath, next); if (fs.existsSync(pluginPath)) _self.loadPlugin(pluginPath, next);
@ -57,11 +56,13 @@ var fs = require('fs'),
if (global.env === 'development') winston.info('[plugins] Plugins OK'); if (global.env === 'development') winston.info('[plugins] Plugins OK');
_self.initialized = true;
_self.readyEvent.emit('ready'); _self.readyEvent.emit('ready');
}); });
}, },
ready: function(callback) { ready: function(callback) {
this.readyEvent.once('ready', callback); if (!this.initialized) this.readyEvent.once('ready', callback);
else callback();
}, },
initialized: false, initialized: false,
loadPlugin: function(pluginPath, callback) { loadPlugin: function(pluginPath, callback) {
@ -161,7 +162,7 @@ var fs = require('fs'),
} }
} }
callback(returnVal); callback(err, returnVal);
}); });
break; break;
case 'action': case 'action':
@ -184,7 +185,7 @@ var fs = require('fs'),
} else { } else {
// Otherwise, this hook contains no methods // Otherwise, this hook contains no methods
var returnVal = (Array.isArray(args) ? args[0] : args); var returnVal = (Array.isArray(args) ? args[0] : args);
if (callback) callback(returnVal); if (callback) callback(err, returnVal);
} }
}, },
isActive: function(id, callback) { isActive: function(id, callback) {

@ -102,8 +102,8 @@ var RDB = require('./redis.js'),
PostTools.privileges(pid, uid, function(privileges) { PostTools.privileges(pid, uid, function(privileges) {
if (privileges.editable) { if (privileges.editable) {
plugins.fireHook('filter:post.save', content, function(parsedContent) { plugins.fireHook('filter:post.save', content, function(err, parsedContent) {
content = parsedContent; if (!err) content = parsedContent;
success(); success();
}); });
} }
@ -193,8 +193,8 @@ var RDB = require('./redis.js'),
PostTools.parse = function(raw, callback) { PostTools.parse = function(raw, callback) {
raw = raw || ''; raw = raw || '';
plugins.fireHook('filter:post.parse', raw, function(parsed) { plugins.fireHook('filter:post.parse', raw, function(err, parsed) {
callback(null, parsed); callback(null, !err ? parsed : raw);
}); });
} }

@ -19,7 +19,6 @@ var RDB = require('./redis.js'),
Posts.getPostsByTid = function(tid, start, end, callback) { Posts.getPostsByTid = function(tid, start, end, callback) {
RDB.lrange('tid:' + tid + ':posts', start, end, function(err, pids) { RDB.lrange('tid:' + tid + ':posts', start, end, function(err, pids) {
RDB.handle(err); RDB.handle(err);
if (pids.length) { if (pids.length) {
@ -123,8 +122,9 @@ var RDB = require('./redis.js'),
Posts.getPostData = function(pid, callback) { Posts.getPostData = function(pid, callback) {
RDB.hgetall('post:' + pid, function(err, data) { RDB.hgetall('post:' + pid, function(err, data) {
if (err === null) { if (err === null) {
plugins.fireHook('filter:post.get', data, function(data) { plugins.fireHook('filter:post.get', data, function(err, newData) {
callback(data); if (!err) callback(newData);
else callback(data);
}); });
} else } else
console.log(err); console.log(err);
@ -154,28 +154,23 @@ var RDB = require('./redis.js'),
RDB.hset('post:' + pid, field, value); RDB.hset('post:' + pid, field, value);
} }
/* getPostsByPids using redis's multi pipeline */
Posts.getPostsByPids = function(pids, callback) { Posts.getPostsByPids = function(pids, callback) {
var posts = [] var posts = [],
var multi = RDB.multi(); multi = RDB.multi();
for (v in pids) { for(var x=0,numPids=pids.length;x<numPids;x++) {
var _pid = pids[v] multi.hgetall("post:"+pids[x]);
multi.hgetall("post:"+_pid);
} }
multi.exec(function (err, replies) { multi.exec(function (err, replies) {
async.eachSeries(replies, function(postData, _callback) { async.map(replies, function(postData, _callback) {
if(postData) { if (postData) {
postData.relativeTime = new Date(parseInt(postData.timestamp,10)).toISOString(); postData.relativeTime = new Date(parseInt(postData.timestamp,10)).toISOString();
postData.post_rep = postData.reputation; postData.post_rep = postData.reputation;
postData['edited-class'] = postData.editor !== '' ? '' : 'none'; postData['edited-class'] = postData.editor !== '' ? '' : 'none';
postData['relativeEditTime'] = postData.edited !== '0' ? (new Date(parseInt(postData.edited,10)).toISOString()) : ''; postData['relativeEditTime'] = postData.edited !== '0' ? (new Date(parseInt(postData.edited,10)).toISOString()) : '';
if(postData.uploadedImages) { if (postData.uploadedImages) {
try { try {
postData.uploadedImages = JSON.parse(postData.uploadedImages); postData.uploadedImages = JSON.parse(postData.uploadedImages);
} catch(err) { } catch(err) {
@ -188,15 +183,13 @@ var RDB = require('./redis.js'),
postTools.parse(postData.content, function(err, content) { postTools.parse(postData.content, function(err, content) {
postData.content = content; postData.content = content;
posts.push(postData); _callback(null, postData);
}); });
return _callback(null) } else {
} _callback(null);
else {
return _callback(null)
} }
}, function(err) { }, function(err, posts) {
if(!err) { if (!err) {
return callback(null, posts); return callback(null, posts);
} else { } else {
return callback(err, null); return callback(err, null);
@ -205,37 +198,6 @@ var RDB = require('./redis.js'),
}) })
} }
Posts.getPostsByPids_original = function(pids, callback) {
var posts = [];
async.eachSeries(pids, function(pid, callback) {
Posts.getPostData(pid, function(postData) {
if (postData) {
postData.relativeTime = new Date(parseInt(postData.timestamp,10)).toISOString();
postData.post_rep = postData.reputation;
postData['edited-class'] = postData.editor !== '' ? '' : 'none';
postData['relativeEditTime'] = postData.edited !== '0' ? (new Date(parseInt(postData.edited,10)).toISOString()) : '';
postTools.parse(postData.content, function(err, content) {
postData.content = content;
posts.push(postData);
callback(null);
});
}
});
}, function(err) {
if (!err) {
callback(null, posts);
} else {
callback(err, null);
}
});
}
Posts.get_cid_by_pid = function(pid, callback) { Posts.get_cid_by_pid = function(pid, callback) {
Posts.getPostField(pid, 'tid', function(tid) { Posts.getPostField(pid, 'tid', function(tid) {
if (tid) { if (tid) {
@ -326,7 +288,9 @@ var RDB = require('./redis.js'),
RDB.incr('global:next_post_id', function(err, pid) { RDB.incr('global:next_post_id', function(err, pid) {
RDB.handle(err); RDB.handle(err);
plugins.fireHook('filter:post.save', content, function(content) { plugins.fireHook('filter:post.save', content, function(err, newContent) {
if (!err) content = newContent;
var timestamp = Date.now(), var timestamp = Date.now(),
postData = { postData = {
'pid': pid, 'pid': pid,
@ -376,7 +340,9 @@ var RDB = require('./redis.js'),
async.parallel({ async.parallel({
content: function(next) { content: function(next) {
plugins.fireHook('filter:post.get', postData, function(postData) { plugins.fireHook('filter:post.get', postData, function(err, newPostData) {
if (!err) postData = newPostData;
postTools.parse(postData.content, function(err, content) { postTools.parse(postData.content, function(err, content) {
next(null, content); next(null, content);
}); });

@ -123,7 +123,7 @@ var user = require('./../user.js'),
app.get('/category/:id/:slug?', function (req, res, next) { app.get('/category/:id/:slug?', function (req, res, next) {
var uid = (req.user) ? req.user.uid : 0; var uid = (req.user) ? req.user.uid : 0;
categories.getCategoryById(req.params.id, uid, function (err, data) { categories.getCategoryById(req.params.id, uid, function (err, data) {
if (!err) if (!err && data && data.disabled === "0")
res.json(data); res.json(data);
else else
next(); next();

@ -100,7 +100,7 @@ function upgradeUserHash(uid, callback) {
function upgradeAdmins(callback) { function upgradeAdmins(callback) {
Groups.getGidFromName('Administrators', function(err, gid) { Groups.getGidFromName('Administrators', function(err, gid) {
if (!err && !gid) { if (!err && !gid) {
winston.info('Upgading Administrators'); winston.info('Upgrading Administrators');
async.parallel([ async.parallel([
function(next) { function(next) {

@ -72,7 +72,6 @@ var utils = require('./../public/src/utils.js'),
'reputation': 0, 'reputation': 0,
'postcount': 0, 'postcount': 0,
'lastposttime': 0, 'lastposttime': 0,
'administrator': (uid == 1) ? 1 : 0,
'banned': 0, 'banned': 0,
'showemail': 0 'showemail': 0
}); });
@ -114,33 +113,6 @@ var utils = require('./../public/src/utils.js'),
}); });
}; };
User.delete = function(uid, callback) {
RDB.exists('user:' + uid, function(err, exists) {
if (exists === 1) {
console.log('deleting uid ' + uid);
User.getUserData(uid, function(err, data) {
RDB.hdel('username:uid', data['username']);
RDB.hdel('email:uid', data['email']);
RDB.hdel('userslug:uid', data['userslug']);
RDB.del('user:' + uid);
RDB.del('followers:' + uid);
RDB.del('following:' + uid);
RDB.zrem('users:joindate', uid);
RDB.zrem('users:postcount', uid);
RDB.zrem('users:reputation', uid);
callback(true);
});
} else {
callback(false);
}
});
}
User.ban = function(uid, callback) { User.ban = function(uid, callback) {
User.setUserField(uid, 'banned', 1, callback); User.setUserField(uid, 'banned', 1, callback);
} }

@ -22,7 +22,8 @@ var express = require('express'),
meta = require('./meta.js'), meta = require('./meta.js'),
feed = require('./feed'), feed = require('./feed'),
plugins = require('./plugins'), plugins = require('./plugins'),
nconf = require('nconf'); nconf = require('nconf'),
winston = require('winston');
(function (app) { (function (app) {
var templates = null, var templates = null,
@ -72,54 +73,104 @@ var express = require('express'),
}; };
// Middlewares // Middlewares
app.use(express.compress()); app.configure(function() {
app.use(express.favicon(path.join(__dirname, '../', 'public', 'favicon.ico'))); async.series([
app.use(require('less-middleware')({ function(next) {
src: path.join(__dirname, '../', 'public'), // Pre-router middlewares
prefix: nconf.get('relative_path'), app.use(express.compress());
yuicompress: true app.use(express.favicon(path.join(__dirname, '../', 'public', 'favicon.ico')));
})); app.use(require('less-middleware')({
app.use(nconf.get('relative_path'), express.static(path.join(__dirname, '../', 'public'))); src: path.join(__dirname, '../', 'public'),
app.use(express.bodyParser()); // Puts POST vars in request.body prefix: nconf.get('relative_path'),
yuicompress: true
app.use(express.cookieParser()); // If you want to parse cookies (res.cookies) }));
app.use(express.session({ app.use(nconf.get('relative_path'), express.static(path.join(__dirname, '../', 'public')));
store: new RedisStore({ app.use(express.bodyParser()); // Puts POST vars in request.body
client: RDB, app.use(express.cookieParser()); // If you want to parse cookies (res.cookies)
ttl: 60 * 60 * 24 * 30 app.use(express.session({
}), store: new RedisStore({
secret: nconf.get('secret'), client: RDB,
key: 'express.sid', ttl: 60 * 60 * 24 * 30
cookie: { }),
maxAge: 60 * 60 * 24 * 30 * 1000 // 30 days secret: nconf.get('secret'),
} key: 'express.sid',
})); cookie: {
app.use(express.csrf()); maxAge: 60 * 60 * 24 * 30 * 1000 // 30 days
app.use(function (req, res, next) { }
res.locals.csrf_token = req.session._csrf; }));
next(); app.use(express.csrf());
});
// Local vars, other assorted setup
app.use(function (req, res, next) {
nconf.set('https', req.secure);
res.locals.csrf_token = req.session._csrf;
next();
});
// Static Directories for NodeBB Plugins // Authentication Routes
app.configure(function () { auth.initialize(app);
var tailMiddlewares = [];
next();
plugins.ready(function () { },
// Remove some middlewares until the router is gone function(next) {
// This is not recommended behaviour: http://stackoverflow.com/a/13691542/122353 // Static Directories for NodeBB Plugins
// Also: https://www.exratione.com/2013/03/nodejs-abusing-express-3-to-enable-late-addition-of-middleware/ plugins.ready(function () {
tailMiddlewares.push(app.stack.pop()); for (d in plugins.staticDirs) {
tailMiddlewares.push(app.stack.pop()); app.use(nconf.get('relative_path') + '/plugins/' + d, express.static(plugins.staticDirs[d]));
tailMiddlewares.push(app.stack.pop()); winston.info('Static directory routed for plugin: ' + d);
for (d in plugins.staticDirs) { }
app.use(nconf.get('relative_path') + '/plugins/' + d, express.static(plugins.staticDirs[d]));
} next();
});
},
function(next) {
// Router & post-router middlewares
app.use(app.router);
// 404 catch-all
app.use(function (req, res, next) {
res.status(404);
// respond with html page
if (req.accepts('html')) {
res.redirect(nconf.get('relative_path') + '/404');
return;
}
// respond with json
if (req.accepts('json')) {
res.send({
error: 'Not found'
});
return;
}
// Push the removed middlewares back onto the application stack // default to plain-text. send()
tailMiddlewares.reverse(); res.type('txt').send('Not found');
app.stack.push(tailMiddlewares.shift()); });
app.stack.push(tailMiddlewares.shift());
app.stack.push(tailMiddlewares.shift()); app.use(function (err, req, res, next) {
// we may use properties of the error object
// here and next(err) appropriately, or if
// we possibly recovered from the error, simply next().
console.error(err.stack);
res.status(err.status || 500);
res.json('500', {
error: err.message
});
});
next();
}
], function(err) {
if (err) {
winston.error('Errors were encountered while attempting to initialise NodeBB.');
} else {
winston.info('Middlewares loaded.');
}
}); });
}); });
@ -137,59 +188,10 @@ var express = require('express'),
server.listen(nconf.get('PORT') || nconf.get('port'), nconf.get('bind_address')); server.listen(nconf.get('PORT') || nconf.get('port'), nconf.get('bind_address'));
} }
auth.initialize(app);
app.use(function (req, res, next) {
nconf.set('https', req.secure);
next();
});
app.use(app.router);
app.use(function (req, res, next) {
res.status(404);
// respond with html page
if (req.accepts('html')) {
//res.json('404', { url: req.url });
res.redirect(nconf.get('relative_path') + '/404');
return;
}
// respond with json
if (req.accepts('json')) {
res.send({
error: 'Not found'
});
return;
}
// default to plain-text. send()
res.type('txt').send('Not found');
});
app.use(function (err, req, res, next) {
// we may use properties of the error object
// here and next(err) appropriately, or if
// we possibly recovered from the error, simply next().
console.error(err.stack);
res.status(err.status || 500);
res.json('500', {
error: err.message
});
});
app.create_route = function (url, tpl) { // to remove app.create_route = function (url, tpl) { // to remove
return '<script>templates.ready(function(){ajaxify.go("' + url + '", null, "' + tpl + '");});</script>'; return '<script>templates.ready(function(){ajaxify.go("' + url + '", null, "' + tpl + '");});</script>';
}; };
app.namespace(nconf.get('relative_path'), function () { app.namespace(nconf.get('relative_path'), function () {
auth.create_routes(app); auth.create_routes(app);

Loading…
Cancel
Save