<commit_before>var controller = require('./controller.js');

var WalletController = function (root, express, db, bitcoind, websocket) {
  var that = this;
  that.bitcoind = bitcoind;

  // Set up a websocket for streaming transactions.
  websocket.on('connection', function(conn) {
    conn.on('data', function(message) {
      var req = JSON.parse(message);

      if(req.method == 'listUnspent')
        that.listUnspent(req.addresses, function(err, unspent) {
          if(err)
            conn.write(JSON.stringify(err));
          else
            conn.write(JSON.stringify({method: 'listUnspent', result: unspent}));
        });
    });
  });

  // Singleton REST endpoint.
  express.get(root, that._read.bind(that))

  // Call our parent constructor.
  controller.Controller.call(that, root, express, db);
};

// Inherit from Controller.
WalletController.prototype = new controller.Controller();
WalletController.prototype.constructor = WalletController;

/**
 * Create a new wallet for the user. 
 */
WalletController.prototype._create = function(req,res) {
  var that = this;

  that.db.getWalletRecord(req.body.serverKey, function(err, record) {
    if(err) {
      console.log('Database error: '+err);
      return res.send(that.errorResponse('There was a server error, please try again later.'));
    }

    // New wallet
    if(!req.body.override) {
      if(record && record.wallet)
        return res.send({result: 'exists'});

      if(req.body.payload.email != undefined) {
        return that.db.checkEmailExists(req.body.payload.email, function(err, response) {
          if(response == true)
            return res.send({result: 'error', messages: ['Email address already exists']});
          that.saveWalletAndAddresses(req, res);
        });
      }

      that.saveWalletAndAddresses(req, res);
    } else {
      // Not new, check the session key
      that.db.sessionKeyValid(req.body.serverKey, req.body.sessionKey, function(err, isValid) {
        if(err)
          return res.send({result: 'error', messages: ['Database error, please try again later']});
        if(isValid == false)
          return res.send({result: 'error', messages: ['Invalid session key']});

        that.saveWalletAndAddresses(req, res);
      });
    }
  });
};

/**
 * Update the current user's wallet.
 */
WalletController.prototype._update = function (req, res) {
  var that = this;

  that.db.getWalletRecord(req.body.serverKey, function(err, record) {
    if(err) {
      console.log('Database error: '+err);
      return res.send(that.errorResponse('There was a server error, please try again later.'));
    }

    that.db.sessionKeyValid(req.body.serverKey, req.body.sessionKey, function(err, isValid) {
      if(err)
        return res.send({result: 'error', messages: ['Database error, please try again later']});
      if(isValid == false)
        return res.send({result: 'error', messages: ['Invalid session key']});

      that.saveWalletAndAddresses(req, res);
    });
  });
};

/**
 * Retrieve the user's wallet, if they are logged in.
 */
WalletController.prototype._read = function(req,res) {
  var that = this;

  that.db.getWalletRecord(req.query.serverKey, function(err, payload) {
    if(err) {
      console.log('Wallet Get Error: '+err);
      return res.send({result: 'error', message: 'Error retreiving wallet'});
    }

    if(!payload || !payload.wallet)
      return res.send({result: 'error', message: 'Wallet not found'});

    if(typeof req.query.authCode == 'undefined' && payload.authKey)
      return res.send({result: 'authCodeNeeded', message: 'Two factor authentication code needed'});

    if(payload.authKey) {
      var code = speakeasy.time({key: payload.authKey, encoding: 'base32'});
      if(req.query.authCode != code)
        return res.send({result: 'error', message: 'Two factor authentication code was invalid'});
    }

    that.db.generateSessionKey(req.query.serverKey, function(err, key) {
      if(err)
        return res.send({result: 'error', message: 'Error generating session key, please try again later'});
      res.send({wallet: payload.wallet, sessionKey: key});
    });
  });
};

/**
 * Delete the user's wallet, if they are logged in.
 */<commit_msg>Made the 'login failed' message less terrifying.<commit_after>var controller = require('./controller.js');

var WalletController = function (root, express, db, bitcoind, websocket) {
  var that = this;
  that.bitcoind = bitcoind;

  // Set up a websocket for streaming transactions.
  websocket.on('connection', function(conn) {
    conn.on('data', function(message) {
      var req = JSON.parse(message);

      if(req.method == 'listUnspent')
        that.listUnspent(req.addresses, function(err, unspent) {
          if(err)
            conn.write(JSON.stringify(err));
          else
            conn.write(JSON.stringify({method: 'listUnspent', result: unspent}));
        });
    });
  });

  // Singleton REST endpoint.
  express.get(root, that._read.bind(that))

  // Call our parent constructor.
  controller.Controller.call(that, root, express, db);
};

// Inherit from Controller.
WalletController.prototype = new controller.Controller();
WalletController.prototype.constructor = WalletController;

/**
 * Create a new wallet for the user. 
 */
WalletController.prototype._create = function(req,res) {
  var that = this;

  that.db.getWalletRecord(req.body.serverKey, function(err, record) {
    if(err) {
      console.log('Database error: '+err);
      return res.send(that.errorResponse('There was a server error, please try again later.'));
    }

    // New wallet
    if(!req.body.override) {
      if(record && record.wallet)
        return res.send({result: 'exists'});

      if(req.body.payload.email != undefined) {
        return that.db.checkEmailExists(req.body.payload.email, function(err, response) {
          if(response == true)
            return res.send({result: 'error', messages: ['Email address already exists']});
          that.saveWalletAndAddresses(req, res);
        });
      }

      that.saveWalletAndAddresses(req, res);
    } else {
      // Not new, check the session key
      that.db.sessionKeyValid(req.body.serverKey, req.body.sessionKey, function(err, isValid) {
        if(err)
          return res.send({result: 'error', messages: ['Database error, please try again later']});
        if(isValid == false)
          return res.send({result: 'error', messages: ['Invalid session key']});

        that.saveWalletAndAddresses(req, res);
      });
    }
  });
};

/**
 * Update the current user's wallet.
 */
WalletController.prototype._update = function (req, res) {
  var that = this;

  that.db.getWalletRecord(req.body.serverKey, function(err, record) {
    if(err) {
      console.log('Database error: '+err);
      return res.send(that.errorResponse('There was a server error, please try again later.'));
    }

    that.db.sessionKeyValid(req.body.serverKey, req.body.sessionKey, function(err, isValid) {
      if(err)
        return res.send({result: 'error', messages: ['Database error, please try again later']});
      if(isValid == false)
        return res.send({result: 'error', messages: ['Invalid session key']});

      that.saveWalletAndAddresses(req, res);
    });
  });
};

/**
 * Retrieve the user's wallet, if they are logged in.
 */
WalletController.prototype._read = function(req,res) {
  var that = this;

  that.db.getWalletRecord(req.query.serverKey, function(err, payload) {
    if(err) {
      console.log('Wallet Get Error: '+err);
      return res.send({result: 'error', message: 'Error retreiving wallet'});
    }

    if(!payload || !payload.wallet)
      return res.send({result: 'error', message: 'Invalid login information'});

    if(typeof req.query.authCode == 'undefined' && payload.authKey)
      return res.send({result: 'authCodeNeeded', message: 'Two factor authentication code needed'});

    if(payload.authKey) {
      var code = speakeasy.time({key: payload.authKey, encoding: 'base32'});
      if(req.query.authCode != code)
        return res.send({result: 'error', message: 'Two factor authentication code was invalid'});
    }

    that.db.generateSessionKey(req.query.serverKey, function(err, key) {
      if(err)
        return res.send({result: 'error', message: 'Error generating session key, please try again later'});
      res.send({wallet: payload.wallet, sessionKey: key});
    });
  });
};

/**
 * Delete the user's wallet, if they are logged in.
 */
{'fraction_non_alphanumeric': 0.14772459325630746, 'fraction_numerical': 0.0004715868898844612, 'mean_word_length': 3.203666997026759, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6868357', 'n_tokens_mistral': 2549, 'n_tokens_neox': 2533, 'n_words': 620}