Esempio n. 1
0
/**
 * Function to enable ajax testing of the mongo configuration
 */
function installUserTest(req, res, template, block, next) {

  if (calipso.config.get('installed')) {
    res.format = "json";
    res.end(JSON.stringify({status:"Invalid Request"}), "UTF-8");
  }

  calipso.form.process(req, function (form) {

    // Check to see if new passwords match
    var err;

    if (form.password != form.check_password) {
      err = new Error(req.t('Your passwords do not match.'));
    }

    // Check to see if new passwords are blank
    if (form.password === '') {
      err = new Error(req.t('Your password cannot be blank.'));
    }

    if (form.username === '') {
      err = new Error(req.t('Your username cannot be blank.'));
    }

    // Check to see if new passwords are blank
    if (form.email === '') {
      err = new Error(req.t('Your email cannot be blank.'));
    }

    var output = {};
    if (err) {
      output.status = "FAILED";
      output.message = "There was a problem because: " + err.message;
    } else {
      output.status = "OK";
    }
    res.format = "json";
    res.end(JSON.stringify(output), "UTF-8");

  });

}
Esempio n. 2
0
function buildPayment(recipient, amount, currency, fn) {
  var newPayment = {
    currency: currency.toUpperCase(),
    amount: amount,
    recipient: recipient
  };

  if (!currency == 'XRP') {
    newPayment.issuer = gateway.config.get('gateway_cold_wallet');
  }

  client.buildPayment(newPayment, function(err, resp) {
    if (err) { fn(err, null); return };
    if (resp.success) {
      fn(null, resp.payments[0]);  
    } else {
      fn(resp.error, null);
    }
  })
}
Esempio n. 3
0
function createWithdrawal(rippleTransaction, address, sqlTransaction, callback){
  gateway.data.models.externalTransactions.create({
    deposit: false,
    amount: rippleTransaction.to_amount * (1 - gateway.config.get("WITHDRAWAL_FEE")),
    currency: rippleTransaction.to_currency,
    status: 'queued',
    ripple_transaction_id: rippleTransaction.id,
    external_account_id: address.tag
  }).complete(function(err, withdrawal) {
    if (err) {
      sqlTransaction.rollback();
      callback(err);
    } else if (withdrawal) {
      callback();
    } else {
      sqlTransaction.rollback();
      callback('withdrawal not found');
    }
  });
}
Esempio n. 4
0
  render: function (path, locals, options) {
    options = _.assign({
      beautify: true,
      indent_size: 2,
      preserve_newlines: false
    }, options || {});

    var template = helpers.asset.read(path);
    var content  = _.template(template)(locals || {});

    if (options.beautify) {
      content = beautify(content, options);
    }

    if (helpers.config.supportsCoffee()) {
      content = this.getCoffeeConverter().build(content);
      content = content.code || content;
    }

    return content;
  }
Esempio n. 5
0
  fs.readdirSync(moduleTemplatePath).forEach(function(name) {

    // Template paths and functions
    var templatePath = moduleTemplatePath + "/" + name;
    var templateExtension = templatePath.match(/([^\.]+)$/)[0];
    var template = fs.readFileSync(templatePath, 'utf8');
    var templateName = name.replace(/\.([^\.]+)$/, '');

    // Load the template - only if not already loaded by theme (e.g. overriden)
    var hasTemplate = calipso.utils.hasProperty('theme.cache.modules.' + module.name + '.templates.' + templateName, calipso);

    if (hasTemplate) {

      // Use the theme version
      templates[templateName] = calipso.theme.cache.modules[module.name].templates[templateName];

    } else {

      // Else load it
      if (template) {
        // calipso.theme.compileTemplate => ./Theme.js
        templates[templateName] = calipso.theme.compileTemplate(template, templatePath, templateExtension);

        // Watch / unwatch files - always unwatch (e.g. around config changes)
        if (calipso.config.get('performance:watchFiles')) {

          fs.unwatchFile(templatePath); // Always unwatch first due to recursive behaviour
          fs.watchFile(templatePath, {
            persistent: true,
            interval: 200
          }, function(curr, prev) {
            loadModuleTemplates(module, moduleTemplatePath);
            calipso.silly("Module " + module.name + " template " + name + " reloaded.");
          });

        }

      }
    }
  });
Esempio n. 6
0
        function finish(err, ok) {
          if (user && !user.locked && ok) {
            found = true;
            calipso.e.post_emit('USER_LOGIN', user);
            createUserSession(req, res, user, function (err) {
              if (err) {
                calipso.error("Error saving session: " + err);
              }
            });
          }

          if (!found) {
            req.flash('error', req.t('You may have entered an incorrect username or password, please try again.  If you still cant login after a number of tries your account may be locked, please contact the site administrator.'));
          }

          if (res.statusCode != 302) {
            res.redirect(calipso.config.get('server:loginPath') || 'back');
            return;
          }
          next();
          return;
        }
Esempio n. 7
0
 _createWithdrawal: function(address, callback){
   var self = this;
   var rippleTransaction = self.incomingPayment;
   var amountMinusFees = rippleTransaction.to_amount * (1 - gateway.config.get("WITHDRAWAL_FEE"));
   gateway.data.models.externalTransactions.create({
     deposit: false,
     amount: amountMinusFees,
     currency: rippleTransaction.to_currency,
     status: 'queued',
     ripple_transaction_id: rippleTransaction.id,
     external_account_id: address.tag
   }).complete(function(error, withdrawal) {
     if (error) {
       callback(error);
     } else if (withdrawal) {
       self.externalTransactionWithdrawal = withdrawal;
       callback();
     } else {
       callback('withdrawal not found');
     }
   });
 },
Esempio n. 8
0
    sql.transaction(function(t) {

      gateway.data.externalTransactions.create({
        deposit: false,
        amount: payment.to_amount * (1 - gateway.config.get("WITHDRAWAL_FEE")),
        currency: payment.to_currency,
        status: 'queued',
        ripple_transaction_id: payment.id,
        external_account_id: address.tag
      }, function(err, withdrawal) {

        console.log(err, withdrawal);
        
        if (err) {
          t.rollback();
          return;
        } 
        
        gateway.data.rippleTransactions.update({
          id: payment.id,
          transaction_state: 'tesSUCCESS'
        }, function(err, rippleTransaction) {

          if (err) {
            t.rollback();
            return;
          } else {
            if (rippleTransaction.transaction_state == 'incoming') {
              t.rollback();
              return;
            } 
            t.commit();
            console.log('commit!');
          }

        })
      });
    });
Esempio n. 9
0
  .on('response', function (res) {
    if (res.statusCode === 404) {
      return callback(new Error('No such file'));
    }
    else if (res.statusCode !== 200) {
      return callback(new Error('Unknown status code: ' + res.statusCode));
    }
    if (!rpi.config.get('raw') && process.stdout.isTTY ) {
      var bar = new ProgressBar('info'.green +':\t'+ ' Downloading: [:bar] :percent time: :elapseds eta: :etas',{
        total: parseInt(res.headers['content-length'], 10),
        width: 30,
        complete: '=',
        incomplete: ' '
      });

      res.on('data', function (chunk) {
        bar.tick(chunk.length);
      });

      res.on('end', function () {
        // fix for bar that sometimes hangs at 99%
        if (bar) {
          bar.tick(bar.total - bar.curr);
        }

        console.log('\n');
      });
    }
    var filename = url.parse(link).pathname.split('/').pop();
    var home = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
    var filePath = path.resolve(path.join(home,'.rpi-tool', filename));
    console.log(filePath);
    res.pipe(fs.createWriteStream(filePath)).on('close', function () {
      rpi.log.info('Saved to file ' + filePath + '.');
      return callback(null);
    });
  });
Esempio n. 10
0
          calipso.lib.crypto.check(old_password, u.hash, function (err, ok) {
            if (u.hash != '' && !ok) {
              req.flash('error', req.t('Your old password was invalid.'));
              res.redirect('back');
              return;
            }

            // Check to see if new passwords match
            if (new_password != repeat_password) {
              req.flash('error', req.t('Your new passwords do not match.'));
              res.redirect('back');
              return;
            }

            // Check to see if new passwords are blank
            if (new_password === '') {
              req.flash('error', req.t('Your password cannot be blank.'));
              res.redirect('back');
              return;
            }

            u.password = ''; // Temporary for migration to hash, remove later
            // Create the hash
            calipso.lib.crypto.hash(new_password, calipso.config.get('session:secret'), function (err, hash) {
              if (err) {
                req.flash('error', req.t('Could not hash password because {msg}.', {msg:err.message}));
                if (res.statusCode != 302) {
                  res.redirect('/');
                  return;
                }
                next();
                return;
              }
              u.hash = hash;
              saveUser();
            });
          });
Esempio n. 11
0
      calipso.e.pre_emit('CONFIG_UPDATE', {module:moduleName, config:moduleConfig}, function (config) {

        calipso.config.save(function (err) {

          if (err) {

            req.flash('error', req.t('Could not save the updated configuration, there was an error: ' + err.message));
            res.redirect('/admin/modules?module=' + moduleName);

          } else {

            // Set the reload config flag for event handler to pick up
            calipso.e.post_emit('CONFIG_UPDATE', {module:moduleName, config:moduleConfig}, function (config) {

              req.flash('info', req.t('Changes to configuration saved.'));
              res.redirect('/admin');
              next();

            });

          }
        });

      });
Esempio n. 12
0
 _buildPayment: function(address, callback) {
   var self = this;
   self.rippleRestClient.buildPayment({
     amount: self.record.to_amount,
     currency: self.record.to_currency,
     issuer: gateway.config.get('COLD_WALLET'),
     account: hotWallet.address,
     recipient: address.address
   }, function(error, response) {
     if (error) { 
       return callback(error.message, null); 
     }
     if (response && response.success) {
       var payment = response.payments[0];
       if (payment) {
         callback(null, payment);
       } else {
         callback('BuildPaymentError', null);
       }
     } else {
       callback(response.message, null);
     }
   });
 },
Esempio n. 13
0
var Client = require('ripple-rest-client');
var gateway = require(__dirname+'/../');

var client = new Client({
  api: gateway.config.get('RIPPLE_REST_API'),
  account: gateway.config.get('gateway_hot_wallet').address,
  secret: gateway.config.get('gateway_hot_wallet').secret,
});

function buildPayment(recipient, amount, currency, fn) {
  var newPayment = {
    currency: currency.toUpperCase(),
    amount: amount,
    recipient: recipient
  };

  if (!currency == 'XRP') {
    newPayment.issuer = gateway.config.get('gateway_cold_wallet');
  }

  client.buildPayment(newPayment, function(err, resp) {
    if (err) { fn(err, null); return };
    if (resp.success) {
      fn(null, resp.payments[0]);  
    } else {
      fn(resp.error, null);
    }
  })
}

module.exports = buildPayment;
Esempio n. 14
0
 function saveConfiguration() {
   // Save configuration to file
   calipso.info("Saving configuration ... ");
   calipso.config.save(this);
 },
Esempio n. 15
0
Storage.prototype.mongoConnect = function(dbUri, checkInstalling, next) {

  // Test the mongodb configuration
  var isInstalled = calipso.config.get('installed');

  // If first option is callback, ste dbUri to config value
  if (typeof dbUri === "function") {
    next = dbUri;
    dbUri = calipso.config.get('database:uri');
    checkInstalling = false;
  }

  // Check we are installing ...
  if (checkInstalling) {
    var db = mongoose.createConnection(dbUri, function(err) {
      next(err, false);
    });
    return;
  }

  if (isInstalled) {

    // Always disconnect first just in case any left overs from installation
    mongoose.disconnect(function() {

      // TODO - what the hell is going on with mongoose?
      calipso.db = mongoose.createConnection(dbUri, function(err) {

        if (err) {

          // Add additional detail to know errors
          if (err.code === "ECONNREFUSED") {
            calipso.error("Unable to connect to the specified database: ".red + dbUri);
          } else {
            calipso.error("Fatal unknown error: ".magenta + err);
          }

          mongoose.disconnect(function() {
            next(err);
          });

        }

      });

      calipso.silly("Database connection to " + dbUri + " was successful.");

      // Replace the inmemory session with mongodb backed one
      var foundMiddleware = false, mw;

      calipso.app.stack.forEach(function(middleware, key) {
        if (middleware.handle.tag === 'session') {
          foundMiddleware = true;
          mw = calipso.lib.express.session({
            secret: calipso.config.get('session:secret'),
            store: mongoStore({
              url: calipso.config.get('database:uri')
            })
          });
          mw.tag = 'session';
          calipso.app.stack[key].handle = mw;
        }
      });

      if (!foundMiddleware) {
        return next(new Error("Unable to load the MongoDB backed session, please check your session and db configuration"), false);
      }

      return next(null, true);

    });

  } else {

    calipso.silly("Database connection not attempted to " + dbUri + " as in installation mode.");

    // Create a dummy connection to enable models to be defined
    calipso.db = mongoose.createConnection('');

    next(null, false);

  }

};
 before(function() {
   gateway.config.set('BASIC_AUTH', false);
 });
Esempio n. 17
0
function loadModules(next) {

  var configuredModules = calipso.config.get('modules') || {};

  // Run any disable hooks
  for (var module in calipso.modules) {
    // Check to see if the module is currently enabled, if we are disabling it.
    if (calipso.modules[module].enabled && configuredModules[module].enabled === false && typeof calipso.modules[module].fn.disable === 'function') {
      calipso.modules[module].fn.disable();
    }
  }

  // Clear the modules object (not sure if this is required, but was getting strange errors initially)
  delete calipso.modules; // 'Delete' it.
  calipso.modules = {}; // Always reset it

  var moduleBasePath = path.join(rootpath, calipso.config.get('server:modulePath'));

  // Read the modules in from the file system, sync is fine as we do it once on load.
  calipso.lib.fs.readdirSync(moduleBasePath).forEach(function(type) {

	// Check for all files or folder starting with "." so that we can handle ".svn", ".git" and so on without problems.

    if (type != "README" && type[0] != '.') { // Ignore the readme file and .DS_Store file for Macs
      calipso.lib.fs.readdirSync(path.join(moduleBasePath, type)).forEach(function(moduleFolderName) {

        if (moduleFolderName != "README" && moduleFolderName[0] != '.') { // Ignore the readme file and .DS_Store file for Macs

          var modulePath = path.join(moduleBasePath, type, moduleFolderName);

          var module = {
            name: moduleFolderName,
            folder: moduleFolderName,
            library: moduleFolderName,
            type: type,
            path: modulePath,
            enabled: false,
            inited: false
          };

          // Add about info to it
          loadAbout(module, modulePath, 'package.json');

          // Set the module name to what is in the package.json, default to folder name
          module.name = (module.about && module.about.name) ? module.about.name : moduleFolderName;

          // Now set the module
          calipso.modules[module.name] = module;

          // Set if it is enabled or not
          module.enabled = configuredModules[module.name] ? configuredModules[module.name].enabled : false;

          if (module.enabled) {

            // Load the module itself via require
            requireModule(calipso.modules[module.name], modulePath);

            // Load the templates (factored out so it can be recalled by watcher)
            loadModuleTemplates(calipso.modules[module.name], path.join(modulePath,'templates'));

          }

        }

      });
    }

  });

  // Now that all are loaded, attach events & depends
  attachModuleEventsAndDependencies();

  // Save configuration changes (if required)
  if (calipso.config.dirty) {
    calipso.config.save(next);
  } else {
    return next();
  }

}
Esempio n. 18
0
module.exports = function(req, res){
  res.send({ 'RIPPLE_REST_API': gateway.config.get('RIPPLE_REST_API') });
};
Esempio n. 19
0
module.exports = function(req, res){

  gateway.config.set('DATABASE_URL', req.body.database_url);
  res.send({ 'DATABASE_URL': gateway.config.get('DATABASE_URL') });

};
Esempio n. 20
0
 }, function(error, depositRecord) {
   deposit = depositRecord;
   gateway.config.set('DEPOSIT_FEE', 0.02);
   depositProcessor = new DepositProcessor(deposit);
   depositProcessor.processDeposit(done);
 });
Esempio n. 21
0
/**
 * Show the current configuration
 * TODO Refactor this to a proper form
 */
function coreConfig(req, res, template, block, next) {

  calipso.data.themes = [];
  calipso.data.adminThemes = []; // TODO
  for (var themeName in calipso.availableThemes) {
    var theme = calipso.availableThemes[themeName];
    if (theme.about && theme.about.type) {
      if (theme.about.type === "full" || theme.about.type === "frontend") {
        calipso.data.themes.push(themeName);
      }
      if (theme.about.type === "full" || theme.about.type === "admin") {
        calipso.data.adminThemes.push(themeName);
      }
    }
    else {
      calipso.warn("Theme " + themeName + " not enabled due to missing type.  Is theme.json valid JSON?");
    }
  }

  var adminForm = {
    id:'admin-form',
    title:'Administration',
    type:'form',
    method:'POST',
    action:'/admin/core/config/save',
    tabs:true,
    sections:[
      {
        id:'form-section-core',
        label:'Site',
        fields:[
          {
            label:'Site Name',
            name:'server:name',
            type:'text',
            placeholder:"My Site Name",
            required:true
          },
          {
            label:'Login Path',
            name:'server:loginPath',
            type:'text',
            placeholder:"/"
          },
          {
            label:'Modules Location',
            name:'server:modulePath',
            type:'text'
          },
          {
            label:'Themes Location',
            name:'server:themePath',
            type:'text',
            placeholder:"./themes",
            required:true
          },
          {
            label:'Server URL',
            name:'server:url',
            type:'url',
            placeholder:"./themes",
            required:true
          },
          {
            label:'Session Secret',
            name:'session:secret',
            type:'password',
            placeholder:"http://localhost:3000",
            required:true
          },
          {
            label:'Session Max Age (seconds)',
            name:'session:maxAge',
            type:'text',
            placeholder:"960000"
          }
        ]
      },
      {
        id:'form-section-language',
        label:'Language',
        fields:[
          {
            label:'Default Language',
            name:'i18n:language',
            type:'select',
            options:req.languages,
            required:true
          },
          {
            label:'Add Unknown Terms',
            name:'i18n:additive',
            type:'checkbox',
            labelFirst:true
          }
        ]
      },
      {
        id:'form-section-performance',
        label:'Performance & Clustering',
        fields:[
          {
            label:'Performance',
            legend:'Performance',
            type:'fieldset',
            fields:[
              {
                label:'Enable Cache',
                name:'performance:cache:enabled',
                type:'checkbox',
                description:'Experimental - will probably break things!',
                labelFirst:true
              },
              {
                label:'Default Cache TTL',
                name:'performance:cache:ttl',
                type:'text',
                description:'Default age (in seconds) for cache items.',
                placeholder:"96000"
              },
              {
                label:'Watch Template Files',
                name:'performance:watchFiles',
                type:'checkbox',
                labelFirst:true
              }
            ]
          },
          {
            label:'Clustering',
            legend:'Clustering',
            type:'fieldset',
            fields:[
              {
                label:'Number Workers',
                description:'Number of workers to start, set to 0 to have Calipso default to number of available cpus.',
                name:'server:cluster:workers',
                type:'text',
                placeholder:"ex: 600"
              },
              {
                label:'Restart Workers',
                name:'server:cluster:restartWorkers',
                description:'Automatically restart workers if they die.',
                type:'checkbox',
                labelFirst:true
              },
              {
                label:'Maximum Restarts',
                name:'server:cluster:maximumRestarts',
                description:'Number of failures before it will stop attempting to restart a worker.',
                type:'text',
                placeholder:"3"
              }
            ]
          },
          {
            label:'Event Emitter',
            legend:'Event Emitter',
            type:'fieldset',
            fields:[
              {
                label:'EventEmitter Max Listeners',
                name:'server:events:maxListeners',
                type:'text',
                placeholder:"500"
              }
            ]
          }
        ]
      },
      {
        id:'form-section-authentication',
        label:'Authentication',
        fields:[
          {
            label:'Password Login and Registration (changes require a restart of calipso)',
            legend:'Password Login and Registration (changes require a restart of calipso)',
            type:'fieldset',
            fields:[
              {
                label:'Enable password authentication and registration',
                type:'checkbox',
                name:'server:authentication:password',
                defaultValue:true,
                description:'Please make sure you have made an external user (google, facebook or twitter an admin account) so you don\'t lose access to your system.'
              },
              {
                label:'Enable password migration to pbkdf2 hash',
                type:'checkbox',
                name:'server:authentication:migrate2pbkdf2',
                description:'As new people create password hashes they will be converted to pbkdf2 hashes.'
              }
            ]
          },
          {
            label:'Facebook Authentication (changes require a restart of calipso)',
            legend:'Set this information to enable Facebook Authentication (changes require a restart of calipso)',
            type:'fieldset',
            fields:[
              {
                label:'AppId',
                description:'Set AppId and Secret to enable facebook authentication',
                name:'server:authentication:facebookAppId',
                type:'password',
                placeholder:"short number you could potentially memorize"
              },
              {
                label:'AppSecret',
                description:'AppSecret for this application to allow facebook authentication',
                name:'server:authentication:facebookAppSecret',
                type:'password',
                placeholder:"long-ass hash code that you would never memorize"
              }
            ]
          },
          {
            label:'Google Authentication (changes require a restart of calipso)',
            legend:'Set this information to enable Google Authentication (changes require a restart of calipso)',
            type:'fieldset',
            fields:[
              {
                label:'ClientId',
                description:'Set ClientId and ClientSecret to enable google authentication',
                name:'server:authentication:googleClientId',
                type:'password',
                placeholder:"short number you could potentially memorize"
              },
              {
                label:'ClientSecret',
                description:'ClientSecret for this application to allow google authentication',
                name:'server:authentication:googleClientSecret',
                type:'password',
                placeholder:"you could never memorize this"
              },
              {
                label:'Google Callback',
                description:'Callback URL for google authentication',
                type:'readonlytext',
                value:calipso.config.get('server:url') + '/auth/google/callback',
                placeholder:"Callback URL for google authentication"
              }
            ]
          },
          {
            label:'Twitter Authentication (changes require a restart of calipso)',
            legend:'Set this information to enable Twitter Authentication (changes require a restart of calipso)',
            type:'fieldset',
            fields:[
              {
                label:'Twitter ConsumerKey',
                description:'Set ConsumerKey and ConsumerSecret to allow twitter authentication',
                name:'server:authentication:twitterConsumerKey',
                type:'password',
                placeholder:"short number you could potentially memorize"
              },
              {
                label:'Twitter ConsumerSecret',
                description:'ConsumerSecret for this application to allow twitter authentication',
                name:'server:authentication:twitterConsumerSecret',
                type:'password',
                placeholder:"This is long, so copy-paste from Twitter"
              },
              {
                label:'Twitter Callback',
                description:'Callback URL for twitter authentication',
                type:'readonlytext',
                value:calipso.config.get('server:url') + '/auth/twitter/callback',
                placeholder:"Your callback URL here"
              }
            ]
          }
        ]
      },
      {
        id:'form-section-theme',
        label:'Theme',
        fields:[
          {
            label:'Frontend Theme',
            name:'theme:front',
            type:'select',
            options:calipso.data.themes,
            description:'Theme used for all web pages excluding admin pages'
          },
          {
            label:'Admin Theme',
            name:'theme:admin',
            type:'select',
            options:calipso.data.adminThemes,
            description:'Administration theme [NOT YET IMPLEMENTED]'
          },
          {
        	  label:'Background Color',
              name:'theme:background-color',
              type:'text'
          },
          {
            name:'theme:default',
            type:'hidden'
          },
          {
            label:'Stylus Middleware',
            legend:'Stylus Middleware',
            type:'fieldset',
            fields:[
              {
                label:'Enable Stylus',
                type:'checkbox',
                defaultValue:false,
                name:'libraries:stylus:enable'
              },
              {
                label:'Show Warnings',
                type:'checkbox',
                defaultValue:false,
                name:'libraries:stylus:warn'
              },
              {
                label:'Compress CSS',
                type:'checkbox',
                defaultValue:false,
                name:'libraries:stylus:compress'
              }
            ]
          }
        ]
      },
      {
        id:'form-section-logging',
        label:'Logging',
        fields:[
          {
            label:'Console Logging',
            name:'logging:console:enabled',
            type:'checkbox',
            labelFirst:true,
            description:'Enable logging to the console.'
          },
          {
            label:'Console Log Level',
            name:'logging:console:level',
            type:'select',
            options:calipso.data.loglevels,
            description:'Log level that controls verbosity of display on the console.'
          },
          {
            label:'Console Timestamp',
            name:'logging:console:timestamp',
            type:'checkbox',
            labelFirst:true,
            description:'Prepend timestamps to console logs.'
          },
          {
            label:'Console Colorize',
            name:'logging:console:colorize',
            type:'checkbox',
            labelFirst:true,
            description:'Show colors on the console logs'
          },
          {
            label:'File Logging',
            name:'logging:file:enabled',
            type:'checkbox',
            labelFirst:true
          },
          {
            label:'File Log Level',
            name:'logging:file:level',
            type:'select',
            options:calipso.data.loglevels,
            description:'Log level that controls verbosity of display in the file logs.'
          },
          {
            label:'File Log Path',
            name:'logging:file:filepath',
            type:'text',
            description:'Path to create the file logs.'
          },
          {
            label:'File Log Timestamp',
            name:'logging:file:timestamp',
            type:'checkbox',
            labelFirst:true,
            description:'Prepend timestamps to file logs.'
          }
        ]
      },
      {
        id:'form-section-modules',
        label:'Modules',
        fields:[] // populated in a loop just below
      }
    ],
    fields:[
      {
        label:'',
        name:'returnTo',
        type:'hidden'
      }
    ],
    buttons:[
      {
        name:'submit',
        type:'submit',
        value:'Save Configuration'
      },
      {
        name:'cancel',
        type:'button',
        href:'/admin',
        value:'Cancel'
      },
      {
          name:'rebuildSass',
          type:'button',
          href:'/admin/rebuildSass',
          value:'Rebuild Sass'
        },
      {
        name:'download',
        type:'button',
        href:'/admin/config.json',
        value:'Download JSON'
      }
    ]
  };

  // Values can come straight off the config.
  var values = calipso.config;

  var adminModuleFields = adminForm.sections[6].fields;
  createModuleFields(adminModuleFields);

  res.layout = 'admin';

  calipso.form.render(adminForm, values, req, function (form) {
    calipso.theme.renderItem(req, res, form, block, {}, next);
  });

}
Esempio n. 22
0
var gateway = require(__dirname + '/../');
var express = require('express');
var bodyParser = require('body-parser');
var passport = require('passport');
var userCtrl = require(__dirname + '/http/controllers/users');
var publicCtrl = require(__dirname + '/http/controllers/public');
var ApiRouter = require(__dirname+'/http/routers/api_router.js');
var resourcesRouter = require(__dirname+'/http/routers/resources_router.js');
var passportAuth = require(__dirname + '/http/passport_auth');
const cors = require('cors')();

process.env.DATABASE_URL = gateway.config.get('DATABASE_URL');

passport.use(passportAuth.adminBasic);
passport.use(passportAuth.userBasic);

var app = express();
app.use(cors);
app.use('/', express.static(gateway.config.get('WEBAPP_PATH')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(passport.initialize());

var apiRouter = new ApiRouter({
  passport: passport,
  authName: 'adminBasic'
});

if (gateway.config.get('BASIC_AUTH')) {
  app.use('/v1', passport.authenticate('adminBasic', { session: false }), resourcesRouter);
} else {
const gatewayd = require(process.env.GATEWAYD_PATH);
const blockchain = require('blockchain-account-monitor');
const async = require('async');

var ExternalAccount = gatewayd.data.models.externalAccounts;
var ExternalTransaction = gatewayd.data.models.externalTransactions; //#THIS is what you change!
const Promise = require('bluebird');
const monitor = new blockchain.AccountMonitor({
  blockchainClient: new blockchain.Client(
    gatewayd.config.get('DOGECOIND')
  ),
  onBlock: function(block, next) {
    var blockHash = block[0].blockhash;
    var transactions = [];
    var records = [];
    async.all(block, function(transaction, callback) {
      ExternalAccount.findOrCreate({              //include in new db model
        uid: transaction.address,
        name: 'dogecoin'
      })
      .then(function(externalAccount) {
        return ExternalTransaction.create({
          uid: transaction.txid,
          amount: transaction.amount,
          currency: 'DOG',
          external_account_id: externalAccount.id, //include in new db model
          deposit: true,
          status: 'incoming'
        })
      })
      .then(function(transaction) {
Esempio n. 24
0
module.exports = function(req, res){
  res.send({ 'LAST_PAYMENT_HASH': gateway.config.get('LAST_PAYMENT_HASH') });
};
Esempio n. 25
0
function toUser(user, template, data, callback) {
  var host = calipso.config.getModuleConfig("mail", "host");
  var port = calipso.config.getModuleConfig("mail", "port");
  var domain = calipso.config.getModuleConfig("mail", "domain");
  var base64 = calipso.config.getModuleConfig("mail", "base64")
  var username = calipso.config.getModuleConfig("mail", "username");
  var password = calipso.config.getModuleConfig("mail", "password");
  if (!host || !port || !domain || !username || !password) {
    return;
  }
  if (base64) {
    username = (new Buffer(username)).toString("base64");
    password = (new Buffer(password)).toString("base64");
  }
  var body = mustache.to_html(template.body, {
    toUser:user.username || '-',
    servername:calipso.config.get('server:name'),
    address:calipso.config.get('server:url'),
    data:data
  });
  mail.send({
      host:host, // smtp server hostname
      port:port, // smtp server port
      domain:domain, // domain used by client to identify itself to server
      to:user.email,
      from:calipso.config.getModuleConfig("mail", "from"),
      subject:template.subject,
      body:body,
      authentication:calipso.config.getModuleConfig("mail", "authentication") ? 'login' : '',
      ssl:calipso.config.getModuleConfig("mail", "ssl") == true ? true : false, // true/false
      username:username, // Account username
      password:password               // Account password
    },
    function (err, result) {
      if (err) {
        calipso.debug("Error in mail.js: " + err);
      } else {
        calipso.debug("Email sent with result: " + result);
      }
      callback();
    });
}
Esempio n. 26
0
var RippleRestClient = require('ripple-rest-client');
var uuid = require('node-uuid');
var async = require('async');
var gateway = require(__dirname+'/../../');
var hotWallet = gateway.config.get('HOT_WALLET');

function OutgoingPayment(outgoingPaymentRecord) {
  this.record = outgoingPaymentRecord;
  this.rippleRestClient = new RippleRestClient({
    account: hotWallet.address,
    secret: hotWallet.secret
  });
}

OutgoingPayment.prototype = {

  processOutgoingPayment: function(callback) {
    var self = this;
    async.waterfall([
      function(next) {
        self._getRippleAddressRecord(next);
      },
      function(address, next) {
        self._buildPayment(address, next);
      },
      function(payment, next) {
        self._sendPayment(payment, next);
      },
      function(response, next) {
        self._markRecordAsSent(response, next);
      },
Esempio n. 27
0
/**
 * Installation routine, this is triggered by the install flag being set
 * in the configuration, which is detected in the core routing function
 * in calipso.js and redirected here.
 */
function install(req, res, template, block, next) {


  // If not in install mode, do not install
  if (calipso.config.get('installed')) {
    res.redirect("/");
    next();
    return;
  }

  // Ensure we are using the install layout
  res.layout = "install";

  // The install process will work in steps
  var installStep = req.moduleParams.installStep || "welcome";

  // Process the input from the previous step
  calipso.form.process(req, function (form) {

    if (form) {

      if (form.userStep) {
        // Store the user for later
        calipso.data.adminUser = form.user;
      } else {
        // Update the configuration
        updateConfiguration(form);
      }
      // Override install step
      installStep = form.installStep
      if (form.installPassword !== installPass) {
        installStep = 'welcome';
      }
    }
    
    // Process the installation
    switch (installStep) {
      case "welcome":
        console.log('Installation Password: "******" (inside quotes)');
        installWelcome(req, res, localNext);
        break;
      case "mongodb":
        installMongo(req, res, localNext);
        break;
      case "user":
        installUser(req, res, localNext);
        break;
      case "modules":
        installModules(req, res, localNext);
        break;
      case "finalise":
        doInstallation(req, res, localNext);
        break;
      default:
        localNext(new Error("A step was specified that is not defined in the install process: " + installStep));
    }

  });

  function localNext(err) {
    if (err) {
      res.statusCode = 500;
      res.errorMessage = err.message;
      req.flash('error', req.t('Calipso has become stuck in install mode. The specific error returned was: ' + err.message));
    }
    next();
  }

}
Esempio n. 28
0
  calipso.form.process(req, function (form) {

    if (form) {

      var User = calipso.db.model('User');

      // Get the password values and remove from form
      // This ensures they are never stored
      var new_password = form.user.new_password;
      delete form.user.new_password;
      var repeat_password = form.user.repeat_password;
      delete form.user.repeat_password;

      var u = new User(form.user);

      // Over ride admin
      if (req.session.user && req.session.user.isAdmin) {

        var newRoles = [];
        u.isAdmin = false; // TO-DO Replace
        for (var role in
          form.user.roles) {
          if (form.user.roles[role] === 'on') {
            newRoles.push(role);
            if (calipso.data.roles[role].isAdmin) {
              u.isAdmin = true;
            }
          }
        }
        u.roles = newRoles;

      } else {

        u.roles = ['Guest']; // Todo - need to make sure guest role can't be deleted?

      }

      //TODO : Add form validation and email confirmation

      // Check to see if new passwords match
      if (new_password != repeat_password) {
        req.flash('error', req.t('Your passwords do not match.'));
        res.redirect('back');
        return;
      }

      // Check to see if new passwords are blank
      if (new_password === '') {
        req.flash('error', req.t('Your password cannot be blank.'));
        res.redirect('back');
        return;
      }

      // Create the hash
      calipso.lib.crypto.hash(new_password, calipso.config.get('session:secret'), function (err, hash) {
        if (err) {
          req.flash('error', req.t('Could not hash user password because {msg}.', {msg:msg}));
          if (res.statusCode != 302 && !res.noRedirect) {
            res.redirect('back');
            return;
          }
          next(err);
        }
        u.hash = hash;
        saveUser();
      });

      function saveUser() {
        calipso.e.pre_emit('USER_CREATE', u);
        u.save(function (err) {

          if (err) {
            var msg = err.message;
            if (err.code === 11000) {
              msg = "a user has already registered with that email";
            }
            req.flash('error', req.t('Could not save user because {msg}.', {msg:msg}));
            if (res.statusCode != 302 && !res.noRedirect) {
              res.redirect('back');
              return;
            }
          } else {
            calipso.e.post_emit('USER_CREATE', u);
            if (!res.noRedirect) {
              req.flash('info', req.t('Profile created, you can now login using this account.'));
              res.redirect('/user/profile/' + encodeURIComponent(u.username));
              return;
            }
          }

          // If not already redirecting, then redirect
          next(err);

        });
      }
    }

  });
Esempio n. 29
0
var RippleRestClient = require('ripple-rest-client');
var PrettyPrintTable = require(__dirname+'/../views/text/');
var gateway = require(__dirname+'/../../');
var async = require('async');

var rippleRestClient = new RippleRestClient({
  api: gateway.config.get('RIPPLE_REST_API'),
  account: gateway.config.get('HOT_WALLET').address
});

function fundHotWallet(amount, currency, secret, callback) {
  var options = {
    amount: amount,
    currency: currency,
    secret: secret
  };

  async.waterfall([
    function(next){
      gateway.api.fundHotWallet(options, next);
    },
    function(){
      rippleRestClient.getAccountBalance(function(error, balances) {
        if (error) {
          return callback(error, null);
        } else {
          PrettyPrintTable.balances(balances.balances);
        }
      });
    }
  ], callback);
Esempio n. 30
0
const RippleRestClient = require('ripple-rest-client');
const uuid = require('node-uuid');
const gatewayd = require(__dirname+'/../../');
const hotWallet = gatewayd.config.get('HOT_WALLET');
const util = require('util');
const Promise = require('bluebird');
var RippleAddresses = gatewayd.data.models.rippleAddresses;
var _ = require('underscore-node');

function OutgoingPayment(outgoingPaymentRecord) {
  this.record = outgoingPaymentRecord;
  this.rippleRestClient = new RippleRestClient({
    api: gatewayd.config.get('RIPPLE_REST_API'),
    account: hotWallet.address,
    secret: hotWallet.secret
  });
}

OutgoingPayment.prototype = {

  processOutgoingPayment: function(callback) {
    var _this = this;

    _this._getRippleAddressRecord()
      .then(function(address){
        return _this._buildPayment(address);
      })

      .then(function(payment){
        return _this._sendPayment(payment);
      })