Skip to content

Commit

Permalink
feat(env): turn off events
Browse files Browse the repository at this point in the history
This commit adds environmental variable control of the events emitted by
Topic.  By setting the variable `DISABLE_EVENTS` to false, no Redis
subscriptions will be made at runtime.  In fact, the code is read as
dead code and returns immediately on entry into the function.

Closes #948.
  • Loading branch information
Jonathan Niles authored and jniles committed Feb 19, 2017
1 parent fa2f00a commit a4de769
Show file tree
Hide file tree
Showing 7 changed files with 127 additions and 99 deletions.
32 changes: 20 additions & 12 deletions .env.sample
Original file line number Diff line number Diff line change
@@ -1,27 +1,35 @@
# Server Config
PORT=8080
HTTPS=1

# database configuration
DB_HOST='localhost'
DB_USER='YOUR_USERNAME'
DB_USER='bhima'
DB_PASS='YOUR_PASSWORD'
DB_NAME='YOUR_DATABASE'
DB_NAME='bhima'

# session variables
SESS_SECRET='YOUR_SECRET'
SESS_SECRET='X0pEn Bl0wF1SH'
SESS_RESAVE=0
SESS_SAVE_UNINITIALIZED=0
SESS_REAP_INTERVAL=-1
SESS_UNSET='destroy'

# logger configuration
LOG_LEVEL='debug'
# log level
LOG_LEVEL='verbose'
LOG_FILE='access.log'

# uploads
UPLOAD_FOLDER='client/upload'
UPLOAD_DIR='client/upload'

# SSL/TLS config
TLS_KEY='server/config/keys/server.key'
TLS_CERT='server/config/keys/server.crt'
# for sentry.io error reporting
SENTRY_DSN=''
SENTRY_NAME=''
SENTRY_ENVIRONMENT=''

# used for broadcasting email reports
SYSTEM_EMAIL_ADDRESS=''

# used to log in to the mailgun service
MAILGUN_DOMAIN=''
MAILGUN_API_KEY=''

# control Redis Pub/Sub
ENABLE_EVENTS=false
18 changes: 9 additions & 9 deletions .env.staging
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
# Server Config
PORT=8080
HTTPS=1

# database configuration
DB_URL = 'mysql://bhima_staging:STAGING_PASSWORD@localhost:3306/bhima_staging'
Expand All @@ -12,17 +11,18 @@ DB_HOST= 'localhost'
# session variables
SESS_SECRET='Tr@v1$_S3CR3T'
SESS_RESAVE=0
SESS_SAVE_UNINITIALIZED=0
SESS_REAP_INTERVAL=-1
SESS_UNSET='destroy'

# logger configuraion params
LOG_LEVEL='warn'
# logger configuration parameters
LOG_LEVEL='verbose'
LOG_FILE='access.log'

# uploads
UPLOAD_FOLDER='client/upload'
UPLOAD_DIR='client/upload'

# SSL/TLS config
TLS_KEY='server/config/keys/server.key'
TLS_CERT='server/config/keys/server.crt'
# used for broadcasting email reports
SYSTEM_EMAIL_ADDRESS='staging@bhi.ma'

# control Redis Pub/Sub events
# for staging purposes, we will turn those off.
ENABLE_EVENTS=false
20 changes: 8 additions & 12 deletions server/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,18 +39,17 @@ const app = express();
* defaults to 'production'
*/
function configureEnvironmentVariables() {

// if the process NODE_ENV is not set, default to production.
process.env.NODE_ENV = process.env.NODE_ENV || 'production';

// normalize the environmental variable name
let env = process.env.NODE_ENV.toLowerCase();
const env = process.env.NODE_ENV.toLowerCase();

// decode the file path for the environmental variables.
let dotfile = `server/.env.${env}`.trim();
const dotfile = `server/.env.${env}`.trim();

// load the environmental variables into process using the dotenv module
console.log(`[app] Loading configuration from ${dotfile}.`);
winston.info(`[app] Loading configuration from ${dotfile}.`);
require('dotenv').config({ path : dotfile });
}

Expand All @@ -67,22 +66,21 @@ function configureEnvironmentVariables() {
*
*/
function configureLogger() {

// set logging levels to that found in the configuration file (default: warn)
winston.level = process.env.LOG_LEVEL || 'warn';
winston.level = (process.env.LOG_LEVEL || 'warn');

const logFile = process.env.LOG_FILE;

// allow logging to a file if needed
if (logFile) {
winston.add(winston.transports.File, { filename : logFile });
winston.add(winston.transports.File, { filename: logFile });
}

// be sure to log unhandled exceptions
winston.handleExceptions(new winston.transports.Console({
humanReadableUnhandledException: true,
colorize: true,
prettyPrint: true
humanReadableUnhandledException : true,
colorize : true,
prettyPrint : true,
}));
}

Expand All @@ -93,7 +91,6 @@ function configureLogger() {
* Set up the HTTP server to listen on the correct
*/
function configureServer() {

// destruct the environmental variables
const port = process.env.PORT;
const mode = process.env.NODE_ENV;
Expand All @@ -103,7 +100,6 @@ function configureServer() {
.listen(process.env.PORT, () => {
winston.info(`Server started in mode ${mode} on port ${port}.`);
});

}

// run configuration tools
Expand Down
34 changes: 17 additions & 17 deletions server/config/express.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ const path = require('path');

const interceptors = require('./interceptors');
const Unauthorized = require('../lib/errors/Unauthorized');
const uploads = require('../lib/uploader');
const uploads = require('../lib/uploader');

// accept generic express instances (initialised in app.js)
exports.configure = function configure(app) {
// TODO - things don't work well yet.
//const isProduction = (process.env.NODE_ENV === 'production');
// const isProduction = (process.env.NODE_ENV === 'production');
const isProduction = false;

winston.debug('Configuring middleware.');
Expand All @@ -34,7 +34,7 @@ exports.configure = function configure(app) {
app.use(helmet());
app.use(compress());

app.use(bodyParser.json({ limit : '8mb' }));
app.use(bodyParser.json({ limit: '8mb' }));
app.use(bodyParser.urlencoded({ extended: false }));

// this will disable the session from expiring on the server (redis-session)
Expand All @@ -44,16 +44,16 @@ exports.configure = function configure(app) {
// stores session in a file store so that server restarts do not interrupt
// client sessions.
const sess = {
store: new RedisStore({
client: new Redis(),
disableTTL: disableTTL
store : new RedisStore({
disableTTL,
client : new Redis(),
}),
secret: process.env.SESS_SECRET,
resave: Boolean(process.env.SESS_RESAVE),
saveUninitialized: Boolean(process.env.SESS_UNINITIALIZED),
unset: process.env.SESS_UNSET,
cookie: { httpOnly : true },
retries: 20
secret : process.env.SESS_SECRET,
resave : Boolean(process.env.SESS_RESAVE),
saveUninitialized : false,
unset : process.env.SESS_UNSET,
cookie : { httpOnly: true },
retries : 20,
};

// indicate that we are running behind a trust proxy and should use a secure cookie
Expand All @@ -67,18 +67,18 @@ exports.configure = function configure(app) {

// provide a stream for morgan to write to
winston.stream = {
write : message => winston.info(message.trim())
write : message => winston.silly(message.trim()),
};

// http logger setup
// options: combined | common | dev | short | tiny
app.use(morgan('combined', { stream : winston.stream }));
app.use(morgan('combined', { stream: winston.stream }));

// public static directories include the entire client and the uploads
// directory.
const days = 1000 * 60 * 60 * 24;
const params = {};
params.maxAge = isProduction ? 7*days : 0;
params.maxAge = isProduction ? 7 * days : 0;
app.use(express.static('client/', params));
app.use(`/${uploads.directory}`, express.static(uploads.directory));

Expand All @@ -87,9 +87,9 @@ exports.configure = function configure(app) {

// Only allow routes to use /login, /projects, /logout, and /languages if a
// user session does not exists
let publicRoutes = ['/auth/login', '/languages', '/projects/', '/auth/logout'];
const publicRoutes = ['/auth/login', '/languages', '/projects/', '/auth/logout'];

app.use(function (req, res, next) {
app.use((req, res, next) => {
if (_.isUndefined(req.session.user) && !within(req.path, publicRoutes)) {
winston.debug(`Rejecting unauthorized access to ${req.path} from ${req.ip}`);
next(new Unauthorized('You are not logged into the system.'));
Expand Down
17 changes: 12 additions & 5 deletions server/controllers/finance/cash.create.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@

const uuid = require('node-uuid');
const _ = require('lodash');
const db = require('../../lib/db');
const db = require('../../lib/db');
const BadRequest = require('../../lib/errors/BadRequest');
const util = require('../../lib/util');
const Topic = require('../../lib/topic');

module.exports = create;

Expand All @@ -25,7 +26,6 @@ function processCashItems(cashUuid, items) {
items.forEach(item => {
item.cash_uuid = cashUuid;
item.uuid = item.uuid || uuid.v4();

item = db.convert(item, ['uuid', 'invoice_uuid']);
});

Expand Down Expand Up @@ -75,10 +75,9 @@ function processCash(cashUuid, payment) {
* POST /cash
*/
function create(req, res, next) {

// alias insertion data
let data = req.body.payment;
const isInvoicePayment = !Boolean(data.is_caution);
const isInvoicePayment = !data.is_caution;
const hasItems = (data.items && data.items.length > 0);

// disallow invoice payments with empty items by returning a 400 to the client
Expand Down Expand Up @@ -143,7 +142,15 @@ function create(req, res, next) {

transaction.execute()
.then(() => {
res.status(201).json({ uuid : uuid.unparse(cashUuid) });
res.status(201).json({ uuid: uuid.unparse(cashUuid) });

Topic.publish(Topic.channels.FINANCE, {
event : Topic.events.CREATE,
entity : Topic.entities.PAYMENT,
user_id : req.session.user.id,
user : req.session.user.display_name,
uuid : uuid.unparse(cashUuid),
});
})
.catch(next)
.done();
Expand Down
8 changes: 4 additions & 4 deletions server/controllers/medical/patients/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -141,10 +141,10 @@ function create(req, res, next) {

// publish a CREATE event on the medical channel
topic.publish(topic.channels.MEDICAL, {
event: topic.events.CREATE,
entity: topic.entities.PATIENT,
user_id: req.session.user.id,
uuid: uuid.unparse(medical.uuid)
event : topic.events.CREATE,
entity : topic.entities.PATIENT,
user_id : req.session.user.id,
uuid : uuid.unparse(medical.uuid),
});
})
.catch(next)
Expand Down
Loading

0 comments on commit a4de769

Please sign in to comment.