Improved bitpay account pairing and management of paired state and data.

This commit is contained in:
Andy Phillipson 2017-01-06 12:11:47 -05:00
commit 63bc3d8f63
23 changed files with 691 additions and 208 deletions

View file

@ -0,0 +1,206 @@
'use strict';
angular.module('copayApp.services').factory('bitpayAccountService', function($log, lodash, platformInfo, appIdentityService, bitpayService, bitpayCardService, storageService, gettextCatalog, popupService) {
var root = {};
/*
* Pair this app with the bitpay server using the specified pairing data.
* An app identity will be created if one does not already exist.
* Pairing data is provided by an input URI provided by the bitpay server.
*
* pairData - data needed to complete the pairing process
* {
* secret: shared pairing secret
* email: email address associated with bitpay account
* otp: two-factor one-time use password
* }
*
* pairingReason - text string to be embedded into popup message. If `null` then the reason
* message is not shown to the UI.
* "To {{reason}} you must pair this app with your BitPay account ({{email}})."
*
* cb - callback after completion
* callback(err, paired, apiContext)
*
* err - something unexpected happened which prevented the pairing
*
* paired - boolean indicating whether the pairing was compledted by the user
*
* apiContext - the context needed for making future api calls
* {
* token: api token for use in future calls
* pairData: the input pair data
* appIdentity: the identity of this app
* }
*/
root.pair = function(pairData, pairingReason, cb) {
checkOtp(pairData, function(otp) {
pairData.otp = otp;
var deviceName = 'Unknown device';
if (platformInfo.isNW) {
deviceName = require('os').platform();
} else if (platformInfo.isCordova) {
deviceName = device.model;
}
var json = {
method: 'createToken',
params: {
secret: pairData.secret,
version: 2,
deviceName: deviceName,
code: pairData.otp
}
};
bitpayService.postAuth(json, function(data) {
if (data && data.data.error) {
return cb(data.data.error);
}
var apiContext = {
token: data.data.data,
pairData: pairData,
appIdentity: data.appIdentity
};
$log.info('BitPay service BitAuth create token: SUCCESS');
fetchBasicInfo(apiContext, function(err, basicInfo) {
if (err) return cb(err);
var title = gettextCatalog.getString('Add BitPay Account?');
var msgDetail = 'Add this BitPay account ({{email}})?';
if (pairingReason) {
msgDetail = 'To {{reason}} you must first add your BitPay account.<br/><br/>{{email}}';
}
var msg = gettextCatalog.getString(msgDetail, {
reason: pairingReason,
email: pairData.email
});
var ok = gettextCatalog.getString('Add Account');
var cancel = gettextCatalog.getString('Go back');
popupService.showConfirm(title, msg, ok, cancel, function(res) {
if (res) {
var acctData = {
token: apiContext.token,
email: pairData.email,
givenName: basicInfo.givenName,
familyName: basicInfo.familyName
};
setBitpayAccount(acctData, function(err) {
return cb(err, true, apiContext);
});
} else {
$log.info('User cancelled BitPay pairing process');
return cb(null, false);
}
});
});
}, function(data) {
return cb(_setError('BitPay service BitAuth create token: ERROR ', data));
});
});
};
var checkOtp = function(pairData, cb) {
if (pairData.otp) {
var msg = gettextCatalog.getString('Enter Two Factor for your BitPay account');
popupService.showPrompt(null, msg, null, function(res) {
cb(res);
});
} else {
cb();
}
};
var fetchBasicInfo = function(apiContext, cb) {
var json = {
method: 'getBasicInfo'
};
// Get basic account information
bitpayService.post('/api/v2/' + apiContext.token, json, function(data) {
if (data && data.data.error) return cb(data.data.error);
$log.info('BitPay Account Get Basic Info: SUCCESS');
return cb(null, data.data.data);
}, function(data) {
return cb(_setError('BitPay Account Error: Get Basic Info', data));
});
};
// Returns account objects as stored.
root.getAccountsAsStored = function(cb) {
storageService.getBitpayAccounts(bitpayService.getEnvironment().network, cb);
};
// Returns an array where each element represents an account including all information required for fetching data
// from the server for each account (apiContext).
root.getAccounts = function(cb) {
root.getAccountsAsStored(function(err, accounts) {
if (err || !accounts) {
return cb(err, []);
}
appIdentityService.getIdentity(bitpayService.getEnvironment().network, function(err, appIdentity) {
if (err) {
return cb(err);
}
var accountsArray = [];
lodash.forEach(Object.keys(accounts), function(key) {
accounts[key].bitpayDebitCards = accounts[key]['bitpayDebitCards-' + bitpayService.getEnvironment().network];
accounts[key].email = key;
accounts[key].firstName = accounts[key]['basicInfo-' + bitpayService.getEnvironment().network].givenName;
accounts[key].lastName = accounts[key]['basicInfo-' + bitpayService.getEnvironment().network].familyName;
accounts[key].apiContext = {
token: accounts[key]['bitpayApi-' + bitpayService.getEnvironment().network].token,
pairData: {
email: key
},
appIdentity: appIdentity
};
// Remove environment keyed attributes.
delete accounts[key]['bitpayApi-' + bitpayService.getEnvironment().network];
delete accounts[key]['bitpayDebitCards-' + bitpayService.getEnvironment().network];
accountsArray.push(accounts[key]);
});
return cb(null, accountsArray);
});
});
};
var setBitpayAccount = function(account, cb) {
var data = JSON.stringify(account);
storageService.setBitpayAccount(bitpayService.getEnvironment().network, data, function(err) {
if (err) {
return cb(err);
}
return cb();
});
};
root.removeAccount = function(account, cb) {
storageService.removeBitpayAccount(bitpayService.getEnvironment().network, account, function(err) {
if (err) {
$log.error('Error removing BitPay account: ' + err);
// Continue, try to remove next step if necessary
}
storageService.getBitpayDebitCards(bitpayService.getEnvironment().network, function(err, cards) {
if (err) {
$log.error('Error attempting to get BitPay debit cards after account removal: ' + err);
}
if (cards.length == 0) {
storageService.removeNextStep('BitpayCard', cb);
} else {
cb();
}
});
});
};
var _setError = function(msg, e) {
$log.error(msg);
var error = (e && e.data && e.data.error) ? e.data.error : msg;
return error;
};
return root;
});

View file

@ -47,28 +47,13 @@ angular.module('copayApp.services').factory('bitpayCardService', function($log,
bitpayService.post('/api/v2/' + apiContext.token, json, function(data) {
if (data && data.data.error) return cb(data.data.error);
$log.info('BitPay Get Debit Cards: SUCCESS');
var cards = [];
lodash.each(data.data.data, function(x) {
var n = {};
if (!x.eid || !x.id || !x.lastFourDigits || !x.token) {
$log.warn('BAD data from Bitpay card' + JSON.stringify(x));
return;
}
n.eid = x.eid;
n.id = x.id;
n.lastFourDigits = x.lastFourDigits;
n.token = x.token;
cards.push(n);
});
storageService.setBitpayDebitCards(bitpayService.getEnvironment().network, apiContext.pairData.email, cards, function(err) {
register();
return cb(err, cards);
// Cache card data in storage
var cardData = {
cards: data.data.data,
email: apiContext.pairData.email
}
root.setBitpayDebitCards(cardData, function(err) {
return cb(err, {token: apiContext.token, cards: data.data.data, email: apiContext.pairData.email});
});
}, function(data) {
return cb(_setError('BitPay Card Error: Get Debit Cards', data));
@ -201,15 +186,32 @@ angular.module('copayApp.services').factory('bitpayCardService', function($log,
}, cb);
};
root.remove = function(cardId, cb) {
storageService.removeBitpayDebitCard(bitpayService.getEnvironment().network, cardId, function(err) {
root.removeCard = function(card, cb) {
storageService.removeBitpayDebitCard(bitpayService.getEnvironment().network, card, function(err) {
if (err) {
$log.error('Error removing BitPay debit card: ' + err);
return cb(err);
// Continue, try to remove/cleanup next step and card history
}
register();
storageService.removeBalanceCache(cardId, cb);
// Next two items in parallel
//
// If there are no more cards in storage then re-enable the next step entry
storageService.getBitpayDebitCards(bitpayService.getEnvironment().network, function(err, cards) {
if (err) {
$log.error('Error getting BitPay debit cards after remove: ' + err);
// Continue, try to remove next step if necessary
}
if (cards.length == 0) {
storageService.removeNextStep('BitpayCard', cb);
}
});
storageService.removeBitpayDebitCardHistory(bitpayService.getEnvironment().network, card, function(err) {
if (err) {
$log.error('Error removing BitPay debit card transaction history: ' + err);
return cb(err);
}
$log.info('Successfully removed BitPay debit card');
return cb();
});
});
};

View file

@ -1,6 +1,6 @@
'use strict';
angular.module('copayApp.services').factory('bitpayService', function($log, $http, platformInfo, appIdentityService, bitauthService, storageService, gettextCatalog, popupService, ongoingProcess) {
angular.module('copayApp.services').factory('bitpayService', function($log, $http, appIdentityService, bitauthService) {
var root = {};
var NETWORK = 'livenet';
@ -12,99 +12,6 @@ angular.module('copayApp.services').factory('bitpayService', function($log, $htt
};
};
/*
* Pair this app with the bitpay server using the specified pairing data.
* An app identity will be created if one does not already exist.
* Pairing data is provided by an input URI provided by the bitpay server.
*
* pairData - data needed to complete the pairing process
* {
* secret: shared pairing secret
* email: email address associated with bitpay account
* otp: two-factor one-time use password
* }
*
* pairingReason - text string to be embedded into popup message. If `null` then the reason
* message is not shown to the UI.
* "To {{reason}} you must pair this app with your BitPay account ({{email}})."
*
* cb - callback after completion
* callback(err, paired, apiContext)
*
* err - something unexpected happened which prevented the pairing
*
* paired - boolean indicating whether the pairing was compledted by the user
*
* apiContext - the context needed for making future api calls
* {
* token: api token for use in future calls
* pairData: the input pair data
* appIdentity: the identity of this app
* }
*/
root.pair = function(pairData, pairingReason, cb) {
checkOtp(pairData, function(otp) {
pairData.otp = otp;
var deviceName = 'Unknown device';
if (platformInfo.isNW) {
deviceName = require('os').platform();
} else if (platformInfo.isCordova) {
deviceName = device.model;
}
var json = {
method: 'createToken',
params: {
secret: pairData.secret,
version: 2,
deviceName: deviceName,
code: pairData.otp
}
};
appIdentityService.getIdentity(root.getEnvironment().network, function(err, appIdentity) {
if (err) return cb(err);
ongoingProcess.set('fetchingBitPayAccount', true);
$http(_postAuth('/api/v2/', json, appIdentity)).then(function(data) {
ongoingProcess.set('fetchingBitPayAccount', false);
if (data && data.data.error) return cb(data.data.error);
$log.info('BitPay service BitAuth create token: SUCCESS');
var title = gettextCatalog.getString('Link BitPay Account?');
var msgDetail = 'Link BitPay account ({{email}})?';
if (pairingReason) {
msgDetail = 'To add your {{reason}} please link your BitPay account {{email}}';
}
var msg = gettextCatalog.getString(msgDetail, {
reason: pairingReason,
email: pairData.email
});
var ok = gettextCatalog.getString('Confirm');
var cancel = gettextCatalog.getString('Cancel');
popupService.showConfirm(title, msg, ok, cancel, function(res) {
if (res) {
var acctData = {
token: data.data.data,
email: pairData.email
};
setBitpayAccount(acctData, function(err) {
if (err) return cb(err);
return cb(null, true, {
token: acctData.token,
pairData: pairData,
appIdentity: appIdentity
});
});
} else {
$log.info('User cancelled BitPay pairing process');
return cb(null, false);
}
});
}, function(data) {
return cb(_setError('BitPay service BitAuth create token: ERROR ', data));
});
});
});
};
root.get = function(endpoint, successCallback, errorCallback) {
$http(_get(endpoint)).then(function(data) {
successCallback(data);
@ -115,7 +22,9 @@ angular.module('copayApp.services').factory('bitpayService', function($log, $htt
root.post = function(endpoint, json, successCallback, errorCallback) {
appIdentityService.getIdentity(root.getEnvironment().network, function(err, appIdentity) {
if (err) return errorCallback(err);
if (err) {
return errorCallback(err);
}
$http(_post(endpoint, json, appIdentity)).then(function(data) {
successCallback(data);
}, function(data) {
@ -124,22 +33,20 @@ angular.module('copayApp.services').factory('bitpayService', function($log, $htt
});
};
var checkOtp = function(pairData, cb) {
if (pairData.otp) {
var msg = gettextCatalog.getString('Enter Two Factor for your BitPay account');
popupService.showPrompt(null, msg, null, function(res) {
cb(res);
root.postAuth = function(json, successCallback, errorCallback) {
appIdentityService.getIdentity(root.getEnvironment().network, function(err, appIdentity) {
if (err) {
return errorCallback(err);
}
$http(_postAuth('/api/v2/', json, appIdentity)).then(function(data) {
data.appIdentity = appIdentity;
successCallback(data);
}, function(data) {
errorCallback(data);
});
} else {
cb();
}
});
};
var setBitpayAccount = function(accountData, cb) {
storageService.setBitpayAccount(root.getEnvironment().network, accountData, cb);
};
var _get = function(endpoint) {
return {
method: 'GET',
@ -184,12 +91,6 @@ angular.module('copayApp.services').factory('bitpayService', function($log, $htt
return ret;
};
var _setError = function(msg, e) {
$log.error(msg);
var error = (e && e.data && e.data.error) ? e.data.error : msg;
return error;
};
return root;
});

View file

@ -190,6 +190,9 @@ angular.module('copayApp.services').factory('configService', function(storageSer
if (!configCache.pushNotifications) {
configCache.pushNotifications = defaultConfig.pushNotifications;
}
if (!configCache.bitpayAccount) {
configCache.bitpayAccount = defaultConfig.bitpayAccount;
}
} else {
configCache = lodash.clone(defaultConfig);

View file

@ -362,17 +362,25 @@ angular.module('copayApp.services')
// lastFourDigits: card number
// token: card token
// ]
root.setBitpayDebitCards = function(network, email, cards, cb) {
root.getBitpayAccounts(network, function(err, allAccounts) {
// email: account email
// token: account token
// }
root.setBitpayDebitCards = function(network, data, cb) {
if (lodash.isString(data)) {
data = JSON.parse(data);
}
data = data || {};
if (lodash.isEmpty(data) || !data.email) return cb('Cannot set cards: no account to set');
storage.get('bitpayAccounts-v3-' + network, function(err, bitpayAccounts) {
if (err) return cb(err);
if (!allAccounts[email]) {
return cb('Cannot set cards for unknown account ' + email);
}
allAccounts[email].cards = cards;
storage.set('bitpayAccounts-v2-' + network, allAccounts, cb);
bitpayAccounts = bitpayAccounts || {};
bitpayAccounts[data.email] = bitpayAccounts[data.email] || {};
bitpayAccounts[data.email]['bitpayDebitCards-' + network] = data.cards;
storage.set('bitpayAccounts-v2-' + network, JSON.stringify(bitpayAccounts), cb);
});
};
@ -385,7 +393,6 @@ angular.module('copayApp.services')
// email: account email
// ]
root.getBitpayDebitCards = function(network, cb) {
root.getBitpayAccounts(network, function(err, allAccounts) {
if (err) return cb(err);
@ -510,6 +517,28 @@ angular.module('copayApp.services')
});
};
// account: {
// email: account email
// apiContext: the context needed for making future api calls
// bitpayDebitCards: an array of cards
// }
root.removeBitpayAccount = function(network, account, cb) {
if (lodash.isString(account)) {
account = JSON.parse(account);
}
account = account || {};
if (lodash.isEmpty(account)) return cb('No account to remove');
storage.get('bitpayAccounts-v3-' + network, function(err, bitpayAccounts) {
if (err) cb(err);
if (lodash.isString(bitpayAccounts)) {
bitpayAccounts = JSON.parse(bitpayAccounts);
}
bitpayAccounts = bitpayAccounts || {};
delete bitpayAccounts[account.email];
storage.set('bitpayAccounts-v3-' + network, JSON.stringify(bitpayAccounts), cb);
});
};
root.setAppIdentity = function(network, data, cb) {
storage.set('appIdentity-' + network, data, cb);
};