Exemplo n.º 1
0
    lawDoc.save(function (err, saved) {
      if (err) return _handleError(err, req, res);
      log('publish law %s at %s', lawDoc.id, lawDoc.publishedAt);

      if (notifier.enabled()) {

          var lawUrl = url.format({
              protocol: config('protocol')
            , hostname: config('host')
            , port: config('publicPort')
            , pathname: '/law/' + lawDoc.id
          });

          notifier.notify('law-published')
            .withData( { law: lawDoc, url: lawUrl } )
            .send(function (err, data) {
              if (err) {
                log('Error when sending notification for event %s', 'law-published');
                return _handleError(new Error('Error when sending notification for event %s', 'law-published'), req, res);
              }

              log('Law %s published', lawDoc.id);
              return res.json(200);
            })
      } else {
        if (err) return _handleError(err, req, res);
        return res.json(200);
      }
    });
Exemplo n.º 2
0
var exports = module.exports = function(app) {

  // Initialize data models
  var dataDb = db.getDefaultConnection();

  require('./law')(dataDb);
  require('./tag')(dataDb);
  require('./comment')(dataDb);
  require('./feed')(dataDb);
  require('./token')(dataDb);

  // Treat User model as per configuration

  var usersDb = dataDb;

  // If a separate database is configured, create a dedicated connection
  var usingSeparateUsersDb = !!(config('mongoUsersUrl') && (config('mongoUsersUrl') != config('mongoUrl')));
  if (usingSeparateUsersDb) {
    usersDb = db.createConnection(config('mongoUsersUrl'));
  }

  exports.User = require('./user')(usersDb);

  // Perform primary connection
  db.connect(config('mongoUrl'));
}
Exemplo n.º 3
0
      .populate('replies.author', 'id firstName lastName fullName email profilePictureUrl', function(err) {
        if (err) {
          log('Found error %j', err);
          return fn(err);
        };

        reply = comment.replies.id(doc.id);

        if (notifier.enabled() && comment.author != reply.author.id) {

          var lawUrl = url.format({
              protocol: config('protocol')
            , hostname: config('host')
            , port: config('publicPort')
            , pathname: '/law/' + comment.reference
          });

          notifier.notify('reply-argument')
            .to(reply.author.email)
            .withData( { reply: reply, comment: comment, url:  lawUrl} )
            .send(function (err, data) {
              if (err) {
                log('Error when sending notification for event %s', 'reply-argument');
                return fn(null, reply);
              }

              log('Delivering reply %s', reply.id);
              return fn(null, reply);
            })
        } else {
          log('Delivering reply %s', reply.id);
          return fn(null, reply);
        }
      });
Exemplo n.º 4
0
app.get('*', function(req, res, next){    
  log('Facebook Request generic page');
  var baseUrl = url.format({
      protocol: config('protocol')
    , hostname: config('host')
    , port: config('publicPort')
  });
  res.render(resolve(__dirname, 'generic.jade'),
                     { baseUrl : baseUrl,
                      config : config});
})
Exemplo n.º 5
0
  api.token.createEmailValidationToken(citizen, meta, function (err, token) {
    if (err) return callback(err);
    log('email validation token created %j', token);

    var validateUrl = url.format({
        protocol: config('protocol')
      , hostname: config('host')
      , port: config('publicPort')
      , pathname: '/signup/validate/' + token.id
      , query: (citizen.reference ? { reference: citizen.reference } : null)
    });

    if (notifier.enabled()) {

      // Notifier enabled, relying on it for signup mail
      var payload = {
        user: citizen.email,
        event: event,
        validateUrl: validateUrl
      }

      notifier.notify(event)
        .to(citizen.email)
        .withData( { validateUrl: validateUrl } )
        .send(function (err, data) {
          if (err) {
            log('Error when sending notification for event %s to user %j', event, citizen);
            return callback(err);
          }

          return callback(null, data);
        })
    } else {

      // Notifier disabled, send mail directly
      var subject = t('DemocracyOS - Welcome!');
      var htmlBody = template({
        citizenName: citizen.fullName,
        validateUrl: validateUrl,
        t: t
      });

      mailer.send(citizen, subject, htmlBody, { tags: [token.scope] }, function (err) {
        if (err) return callback(err);
        log('email validation mail sent to %s', citizen.email);
        return callback(err, citizen);
      });
    }
  });
Exemplo n.º 6
0
 api.law.get(req.params.id, function (err, lawDoc) {
   if (err) return _handleError(err, req, res);
   log('Serving Facebook law %s', lawDoc.id);
   var baseUrl = url.format({
       protocol: config('protocol')
     , hostname: config('host')
     , port: config('publicPort')
   });
   res.render(resolve(__dirname, 'law.jade'),
                      { law: lawDoc,
                        baseUrl : baseUrl,
                        config : config,
                        strip: strip
                      });
 });
Exemplo n.º 7
0
exports.create = function (name, fn) {
  var database = [name, date(), crypto.randomBytes(2).toString('hex')].join('-');
  var username = name + '-' + crypto.randomBytes(12).toString('hex');
  var password = crypto.randomBytes(48).toString('base64');

  var uri = mongodbUri.parse(config('deploymentMongoUrl'));

  uri.database = database;
  uri.username = username;
  uri.password = password;

  uri = urlencode.decode(mongodbUri.format(uri));

  adminClient.connect(function(err, client){
    if (err) return fn(err);

    var db = client.db(database);

    db.addUser(username, password, {
      roles: [{ role: 'readWrite', db: database }]
    }, function(err) {
      if (err) return fn(err);
      log('User "%s" created for database "%s".', username, database);
      fn(null, uri);
    });
  });
}
Exemplo n.º 8
0
Arquivo: index.js Projeto: 3manuek/app
module.exports = function(app) {

  /*
   *  Connect to mongo
   */

  mongoose.connect(config('mongoUrl'), { db: { safe: true }});

  /*
   *  Citizen Model
   */

  require('./citizen');

  /*
   *  Proposal Model
   */

  require('./proposal');

  /*
   *  Law Model
   */
 
  require('./law');

  /**
   * Tag Model
   */

  require('./tag');

  /*
   *  Delegation Model
   */

  require('./delegation');

  /*
   *  Comment Model
   */

  require('./comment');

  /*
   *  Feed Model
   */

  require('./feed');

  /*
   *  Token Model
   */

  require('./token');


}
Exemplo n.º 9
0
  api.token.createEmailValidationToken(citizen, meta, function (err, token) {
    if (err) return callback(err);
    log('email validation token created %j', token);
    var subject = t('DemocracyOS - Welcome!');
    var validateUrl = url.format({
        protocol: config('protocol')
      , hostname: config('host')
      , port: config('publicPort')
      , pathname: '/signup/validate/' + token.id
    });

    var htmlBody = template({
      citizenName: citizen.fullName,
      validateUrl: validateUrl,
      t: t
    });

    mailer.send(citizen, subject, htmlBody, { tags: [token.scope] }, function (err) {
      if (err) return callback(err);
      log('email validation mail sent to %s', citizen.email);
      return callback(err, citizen); 
    });
  });  
Exemplo n.º 10
0
    api.token.createPasswordResetToken(citizen, meta, function (err, token) {
      if (err) return callback(err);
      log('password reset token created %j', token);
      var subject = t('DemocracyOS - Password reset requested');
      var resetUrl = url.format({
          protocol: config('protocol')
        , hostname: config('host')
        , port: config('publicPort')
        , pathname: '/forgot/reset/' + token.id
      });

      var htmlBody = template({
        citizenName: citizen.fullName,
        resetUrl: resetUrl,
        t: t
      });

      mailer.send(citizen, subject, htmlBody, { tags: [token.scope] }, function (err) {
        if (err) return callback(err);
        log('password reset mail sent to %s', citizen.email);
        return callback(err, citizen); 
      });
    });
Exemplo n.º 11
0
exports.doSignUp = function doSignUp (profile, meta, callback) {
  var citizen = new Citizen(profile);

  log('new citizen [%s] from Local signup [%s]', citizen.id, profile.email);

  citizen.avatar = 'http://gravatar.com/avatar/'.concat(utils.md5(citizen.email)).concat('?d=mm&size=200');
  citizen.firstName = profile.firstName;
  citizen.lastName = profile.lastName;
  if (config('env') == 'development') citizen.emailValidated = true;
  Citizen.register(citizen, profile.password, function(err, citizen) {
    if (err) return callback(err);
    log('Saved citizen [%s]', citizen.id);
    sendValidationEmail(citizen, meta, callback);
  });
}
Exemplo n.º 12
0
module.exports = function setupSSL(app) {

  var ssl = 'https' == config('protocol');

  if (ssl) {
    var redirect = config('ssl').redirect;

    log('SSL is enabled and SSL mode is "%s"', redirect);

    switch (redirect) {
      case 'normal':
        app.use(enforce.HTTPS());
        log('SSL is enabled with HTTP -> HTTPS automatic redirection');
        break;
      case 'reverse-proxy':
        app.use(enforce.HTTPS(true));
        log('Using redirection to HTTPS compatible with reverse-proxies (e.g.: Heroku/Nodejitsu/nginx)');
        log('**WARNING** Do NOT use if not behind a reverse proxy; this can be easily spoofed in a direct client/server connection!');
        break;
      case 'azure':
        app.use(enforce.HTTPS(false, true));
        log('Using redirection to HTTPS compatible with Windows Azure');
        log('**WARNING** Do NOT use outside Windows Azure; this can be easily spoofed outside their environment!');
        break;
      case 'no-redirect':
        log('SSL is enabled with NO HTTP -> HTTPS redirection');
        log('**WARNING** This is not recommended for production environments unless you have other means of redirection.');
        log('It\'s ok if you are in a development environment');
      default:
        log('**WARNING**SSL is enabled but no valid redirection strategy was configured');
        log('Defaulting to no-redirect strategy. This is NOT recommended for production enviroments!');
        log('It\'s ok if you are in a development environment');
        break;
    }
  }
};
Exemplo n.º 13
0
module.exports = function language(req, res, next) {
  var user = req.user;
  var lang = config('locale');

  if (req.query.lang) {
    // set
    lang = valid(req.query.lang) ? req.query.lang : lang;

    log('Setting language %s', lang);
    if (user) {
      log('User %s signed in, changing their language', user.id);
      res.cookie('lang', lang);
      user.lang = lang;
      user.save(function (err) {
        if (err) return res.send(500);
        return res.redirect(req.path);
      });
    } else {
      log('No user signed in, setting cookie value to %s', lang);
      return res.cookie('lang', lang).redirect(req.path);
    }
  } else {
    // get
    if (user) {
      if (!user.lang) {
        lang = req.cookies.lang
        res.cookie('lang', lang);
        user.lang = lang;
        return user.save(function (err) {
          if (err) return res.send(500);
          return res.redirect(req.path);
        });
      }
      lang = user.lang;
    } else {
      lang = req.cookies.lang || lang;
    }
    log('Setting language to %s', lang);
    res.cookie('lang', lang);
    next();
  }
}
Exemplo n.º 14
0
exports.getFor = function getFor(query, paging, fn) {
  log('Looking for comments for %s %s', query.context, query.reference);

  paging = paging || { page: 0, limit: config('comments per page'), sort: 'score', exclude_user: null };

  Comment
  .find(query)
  .populate('author', 'id firstName lastName fullName email profilePictureUrl')
  .sort(paging.sort || 'score')
  .skip(paging.page * paging.limit)
  .limit(paging.limit)
  .exec(function(err, comments) {
    if (err) {
      log('Found error %j', err);
      return fn(err);
    };

    log('Delivering comments %j', pluck(comments, 'id'));
    fn(null, comments);
  });
};
Exemplo n.º 15
0
var exports = module.exports = function models() {

  /**
   *  Connect to mongo
   */

  var dataDb = db.getDefaultConnection();

  /**
   * Register Models
   */
  [
    'deployment',
    'feed'
  ].forEach(function(model){
    require('./'+model)(dataDb);
  });

  // Register user separately since we need to expose it
  exports.User = require('./user')(dataDb);

  // Perform primary connection
  db.connect(config('mongoUrl'));
}
Exemplo n.º 16
0
/**
 * Module dependencies.
 */

var express = require('express');
var config = require('lib/config');

/**
 * Exports Application
 */

var app = module.exports = express();

function redirect(req, res, next) {
  var path = req.params.path || '';
  var url = config('settings url') + (path ? '/' + path : '');
  res.redirect(url);
}

if (config('settings url')) {
  app.get('/settings', redirect);
  app.get('/settings/:path', redirect);
};

app.get('/settings', require('lib/layout'));
app.get('/settings/profile', require('lib/layout'));
app.get('/settings/password', require('lib/layout'));
app.get('/settings/notifications', require('lib/layout'));
Exemplo n.º 17
0
Arquivo: index.js Projeto: 3manuek/app
 server.listen(config('privatePort'), function() {
   log('Application started on port %d', config('privatePort'));
 });
Exemplo n.º 18
0
module.exports = function configuration (app) {
  
  /**
   * Load configuration settings
   * for development setup
   */
  
  if (config('env') == 'development') {

    /**
     * Add build middleware
     */

    app.use(require('lib/build').middleware);
  }

  /**
   * Load configuration settings
   * for testing setup
   */
  
  if (config('env') == 'testing') {

    // Log config settigs load
    log( 'testing settings' );

  }

  /**
   * Load configuration settings
   * for production setup
   */
  
  if (config('env') == 'production') {

    // Log config settigs load
    log( 'production settings' );

    /**
     * Set `nowww` middleware helper
     */

    app.use( nowww() );
    
    /**
     * Set `native` express compression middleware
     */

    app.use( compression() );
  }

  /**
   * Load configuration settings
   * for common setup
   */

   /**
    * Save config in app
    */

  app.set('config', config);

  /**
   * Set application port
   */
  
  app.set('port', app.get('config').port || 3000);

  /**
   * Set `public-assets` default path
   */

  app.use(express.static(resolve('public')));
  
  /**
   * Configure native `express` body parser
   */

  // parse application/x-www-form-urlencoded
  app.use(bodyParser.urlencoded())

  // parse application/json
  app.use(bodyParser.json())

  // parse application/vnd.api+json as json
  app.use(bodyParser.json({ type: 'application/vnd.api+json' }))
  
  /**
   * Configure native `express` cookie parser
   */

  app.use( cookieParser('nodejs-boilerplate') );
    
  /**
   * Configure native `express` session middleware
   */

  app.use(session({
    cookie: {
      maxAge: 1000 * 60 * 60 * 24 * 7
    },
    secret: 'nodejs-boilerplate',
    store: new MongoStore({
      url: config('mongoUrl')
    })
  }));

  /**
   * Use `passport` setup & helpers middleware
   */

  app.use(passport.initialize());
  
  /**
   * Use `passport` sessions middleware
   */

  app.use(passport.session());
  
  /**
   * Set custom error handler
   */

  app.use(function(err, req, res, next) {
    // log
    console.log('Some odd error: %j', err);
    // now let it go
    next();
  });

  /**
   * Set native `express` error handler
   */

  app.use(errorhandler());
}
Exemplo n.º 19
0
var log = require('lib/debug')('manager:db-handler')
var config = require('lib/config');
var crypto = require('crypto');
var mongodbUri = require('mongodb-uri');
var urlencode = require('urlencode');
var AdminClient = require('./admin-client');

var adminClient = new AdminClient(config('deploymentMongoUrl'));

exports.create = function (name, fn) {
  var database = [name, date(), crypto.randomBytes(2).toString('hex')].join('-');
  var username = name + '-' + crypto.randomBytes(12).toString('hex');
  var password = crypto.randomBytes(48).toString('base64');

  var uri = mongodbUri.parse(config('deploymentMongoUrl'));

  uri.database = database;
  uri.username = username;
  uri.password = password;

  uri = urlencode.decode(mongodbUri.format(uri));

  adminClient.connect(function(err, client){
    if (err) return fn(err);

    var db = client.db(database);

    db.addUser(username, password, {
      roles: [{ role: 'readWrite', db: database }]
    }, function(err) {
      if (err) return fn(err);
Exemplo n.º 20
0
  app.configure(function() {
    // Log config settigs load
    log( 'common settings' );

    /**
     * Save config in app
     */

    app.set('config', config);

    /**
     * Basic HTTP-Auth restriction middleware
     * for production access only.
     */

    if (config.auth.basic && config.auth.basic.username && config.auth.basic.password) {
      var basic = auth({
        authRealm: 'Authentication required',
        authList : [config.auth.basic.username+':'+config.auth.basic.password]
      });
      app.use(function(req, res, next) {
        basic.apply(req, res, function(username) {
          return next();
        });
      });
    }

    /**
     * Set application http server port from `env`
     * Defaults to 3000
     */

    app.set( 'port', config('privatePort') || 3000 );

    /**
     * Set `public-assets` default path
     */

    app.use(express.static(resolve('public')));

    app.use(express.urlencoded());
    app.use(express.json());

    /**
     * Cross Origin Resource Sharing
     */

    var domains = config('cors domains');
    if (domains && domains.length) {
      var options;
      if (domains.length == 1 && domains[0] == '*') {
        options = null;
      } else {
        options = {
          origin: function(origin, callback){
            var originIsWhitelisted = domains.indexOf(origin) !== -1;
            callback(null, originIsWhitelisted);
          }
        };
      }
      app.use(cors(options));
    }

    /**
     * Use `passport` setup & helpers middleware
     */

    app.use(passport.initialize());

    /**
     * Configure native `express` cookie parser
     */

    app.use(cookieParser(config('secret')));

    /**
     * JSON Web Tokens
     */

    app.use(jwt.middlewares.user(config('secret')));

    /**
     * Set template local variables
     */

    app.use(function(req, res, next) {

      // Set user as local var if authenticated
      if(req.isAuthenticated() && req.user) res.locals.citizen = req.user;

      res.locals.t = t;

      // Call next middleware
      next();

    });

    /**
     * Use `twitter-card` and 'facebook-card' middlewares
     */

    app.use(require('lib/twitter-card/middleware'));
    app.use(require('lib/facebook-card/middleware'));

  });
Exemplo n.º 21
0
 * Delegation API Service
 */

app.use('/api', require('lib/delegation'));

/**
 * Load localization dictionaries to translation application
 */

translations.help(t);

/**
 * Init `t-component` component with parameter locale
 */

t.lang(config('locale'));

/**
 * Set native `express` router middleware
 */

app.use(app.router);

// Here we should have our own error handler!

/**
 * Set native `express` error handler
 */

app.use(express.errorHandler());
Exemplo n.º 22
0
  app.configure(function() {
    // Log config settigs load
    log( 'common settings' );

    /**
     * Save config in app
     */
    
    app.set('config', config);

    /**
     * Config mandrill mailer
     */

    mandrillMailer(app);

    /**
     * Basic HTTP-Auth restriction middleware
     * for production access only.
     */

    if (config.auth.basic && config.auth.basic.username && config.auth.basic.password) {
      var basic = auth({
        authRealm: "Authentication required",
        authList : [config.auth.basic.username+":"+config.auth.basic.password]
      });
      app.use(function(req, res, next) {
        basic.apply(req, res, function(username) {
          return next();
        });
      });
    }

    /**
     * Set application http server port from `env`
     * Defaults to 3005
     */

    app.set( 'port', config('privatePort') || 3005 );
    
    /**
     * Set `public-assets` default path
     */

    app.use(express.static(resolve('public')));
    
    /**
     * Configure native `express` body parser
     */

    // `express.bodyParsers()` uses `connect.multipart()`
    // check https://github.com/senchalabs/connect/wiki/Connect-3.0
    // for more details on the temporal fix.
    // app.use( express.bodyParser() );
    app.use(express.urlencoded());
    app.use(express.json());

    /**
     * Configure native `express` cookie parser
     */

    app.use( express.cookieParser('democracyos-cookie') );
    
    /**
     * Configure native `express` session middleware
     */

    app.use( express.session( {
        cookie: { maxAge: 1000 * 60 * 60 * 24 * 7 },
        secret: 'democracyos-secret',
        key: "democracyos.org",
        store: new MongoStore( { mongoose_connection: mongoose.connection } )
      } )
    );

    /**
     * Use `express.csrf` middleware
     */

    app.use(express.csrf());
    app.use(function (req, res, next) {
      res.locals.csrfToken = req.csrfToken();
      next();
    });

    /**
     * Use `passport` setup & helpers middleware
     */

    app.use(passport.initialize());

    /**
     * Use `passport` sessions middleware
     */

    app.use(passport.session());

    /**
     * Set template local variables
     */

    app.use(function(req, res, next) {

      // Set user as local var if authenticated
      if(req.isAuthenticated() && req.user) res.locals.citizen = req.user;

      res.locals.t = t;

      // Call next middleware
      next();

    });

    /**
     * Use `twitter-card` and 'facebook-card' middlewares
     */

    app.use(require('lib/twitter-card/middleware'));
    app.use(require('lib/facebook-card/middleware'));

  });
Exemplo n.º 23
0
Arquivo: index.js Projeto: NoGRo/app
  app.configure(function() {
    // Log config settigs load
    log( 'common settings' );

    /**
     * Save config in app
     */
    
    app.set('config', config);

    /**
     * Set `mongoUrl` from config settings
     */

    app.set( 'mongoUrl', config('mongoUrl') );

    /**
     * Config mandrill mailer
     */

    mandrillMailer(app);

    /**
     * Basic HTTP-Auth restriction middleware
     * for production access only.
     */

    if (config.auth.basic && config.auth.basic.username && config.auth.basic.password) {
      var basic = auth({
        authRealm: "Authentication required",
        authList : [config.auth.basic.username+":"+config.auth.basic.password]
      });
      app.use(function(req, res, next) {
        basic.apply(req, res, function(username) {
          return next();
        });
      });
    }

    /**
     * Set application http server port from `env`
     * Defaults to 3005
     */

    app.set( 'port', config('port') || 3005 );
    
    /**
     * Set `public-assets` default path
     */

    app.use( express.static( path.join(__dirname, '..', '/public') ) );
    
    /**
     * Configure native `express` body parser
     */

    app.use( express.bodyParser() );
    
    /**
     * Configure native `express` cookie parser
     */

    app.use( express.cookieParser('democracyos-cookie') );
    
    /**
     * Configure native `express` session middleware
     */

    app.use( express.session( {
        cookie: { maxAge: 1000 * 60 * 60 * 24 * 7 },
        secret: 'democracyos-secret',
        key: "democracyos.org",
        store: new MongoStore( { url: app.get('mongoUrl') } )
      } )
    );

    /**
     * Use `passport` setup & helpers middleware
     */

    app.use(passport.initialize());

    /**
     * Use `passport` sessions middleware
     */

    app.use(passport.session());

    /**
     * Set template local variables
     */

    app.use(function(req, res, next) {

      // Set user as local var if authenticated
      if(req.isAuthenticated() && req.user) res.locals.citizen = req.user;

      res.locals.t = t;

      // Call next middleware
      next();

    });
        
    /**
     * Set native `express` router middleware
     */

    app.use(app.router);
    
    // Here we should have our own error handler!
    
    /**
     * Set native `express` error handler
     */

    app.use(express.errorHandler());


  });
Exemplo n.º 24
0
function redirect(req, res, next) {
  var path = req.params.path || '';
  var url = config('settings url') + (path ? '/' + path : '');
  res.redirect(url);
}