Begin reworking billing.nylas.com

This commit is contained in:
Ben Gotow 2017-07-31 15:51:59 -07:00
parent a8c6095d15
commit 20490a33b0
9 changed files with 46 additions and 69 deletions

View file

@ -76,7 +76,7 @@ describe("IdentityStore", function identityStoreSpec() {
const opts = IdentityStore.nylasIDRequest.calls[0].args[0] const opts = IdentityStore.nylasIDRequest.calls[0].args[0]
expect(opts).toEqual({ expect(opts).toEqual({
method: "POST", method: "POST",
url: "https://billing.nylas.com/n1/user/feature_usage_event", url: "https://billing.nylas.com/api/feature_usage_event",
body: { body: {
feature_name: 'snooze', feature_name: 'snooze',
}, },

View file

@ -71,7 +71,7 @@ export default class BillingModal extends React.Component {
Actions.closeModal() Actions.closeModal()
} }
}) })
await IdentityStore.asyncRefreshIdentity(); await IdentityStore.fetchIdentity();
}); });
/** /**

View file

@ -16,8 +16,6 @@ class _EdgehillAPI {
const env = NylasEnv.config.get('env') const env = NylasEnv.config.get('env')
if (['development', 'local'].includes(env)) { if (['development', 'local'].includes(env)) {
this.APIRoot = "http://n1-auth.lvh.me:5555"; this.APIRoot = "http://n1-auth.lvh.me:5555";
} else if (env === 'experimental') {
this.APIRoot = "https://edgehill-experimental.nylas.com";
} else if (env === 'staging') { } else if (env === 'staging') {
this.APIRoot = "https://n1-auth-staging.nylas.com"; this.APIRoot = "https://n1-auth-staging.nylas.com";
} else { } else {

View file

@ -7,8 +7,6 @@ class LegacyEdgehillAPI extends _EdgehillAPI {
const env = NylasEnv.config.get('env') const env = NylasEnv.config.get('env')
if (['development', 'local'].includes(env)) { if (['development', 'local'].includes(env)) {
this.APIRoot = "http://localhost:5009"; this.APIRoot = "http://localhost:5009";
} else if (env === 'experimental') {
this.APIRoot = "https://edgehill-experimental.nylas.com";
} else if (env === 'staging') { } else if (env === 'staging') {
this.APIRoot = "https://edgehill-staging.nylas.com"; this.APIRoot = "https://edgehill-staging.nylas.com";
} else { } else {

View file

@ -135,17 +135,17 @@ export default class Account extends ModelWithMetadata {
} }
canArchiveThreads() { canArchiveThreads() {
CategoryStore = CategoryStore || require('../stores/category-store') CategoryStore = CategoryStore || require('../stores/category-store').default
return CategoryStore.getArchiveCategory(this) return CategoryStore.getArchiveCategory(this)
} }
canTrashThreads() { canTrashThreads() {
CategoryStore = CategoryStore || require('../stores/category-store') CategoryStore = CategoryStore || require('../stores/category-store').default
return CategoryStore.getTrashCategory(this) return CategoryStore.getTrashCategory(this)
} }
preferredRemovalDestination() { preferredRemovalDestination() {
CategoryStore = CategoryStore || require('../stores/category-store') CategoryStore = CategoryStore || require('../stores/category-store').default
const preferDelete = NylasEnv.config.get('core.reading.backspaceDelete') const preferDelete = NylasEnv.config.get('core.reading.backspaceDelete')
if (preferDelete || !CategoryStore.getArchiveCategory(this)) { if (preferDelete || !CategoryStore.getArchiveCategory(this)) {
return CategoryStore.getTrashCategory(this); return CategoryStore.getTrashCategory(this);

View file

@ -90,7 +90,9 @@ class CategoryStore extends NylasStore {
if (!Category.StandardRoles.includes(role)) { if (!Category.StandardRoles.includes(role)) {
throw new Error(`'${role}' is not a standard category`); throw new Error(`'${role}' is not a standard category`);
} }
return this._standardCategories[asAccountId(accountOrId)].find(c => c.role === role);
const accountCategories = this._standardCategories[asAccountId(accountOrId)]
return accountCategories && accountCategories.find(c => c.role === role);
} }
// Public: Returns the set of all standard categories that match the given // Public: Returns the set of all standard categories that match the given

View file

@ -65,9 +65,9 @@ class IdentityStore extends NylasStore {
* We also update from the server's version every * We also update from the server's version every
* `SendFeatureUsageEventTask` * `SendFeatureUsageEventTask`
*/ */
setInterval(this._fetchIdentity.bind(this), 1000 * 60 * 10); // 10 minutes setInterval(this.fetchIdentity.bind(this), 1000 * 60 * 10); // 10 minutes
// Don't await for this! // Don't await for this!
this._fetchIdentity(); this.fetchIdentity();
} }
/** /**
@ -79,12 +79,13 @@ class IdentityStore extends NylasStore {
if (identity && identity.token) { if (identity && identity.token) {
KeyManager.replacePassword(KEYCHAIN_NAME, identity.token); KeyManager.replacePassword(KEYCHAIN_NAME, identity.token);
delete identity.token; const withoutToken = Object.assign({}, identity);
} delete withoutToken.token;
if (!identity) { NylasEnv.config.set('nylasid', withoutToken);
} else if (!identity) {
KeyManager.deletePassword(KEYCHAIN_NAME); KeyManager.deletePassword(KEYCHAIN_NAME);
NylasEnv.config.set('nylasid', null);
} }
NylasEnv.config.set('nylasid', identity);
} }
/** /**
@ -93,9 +94,7 @@ class IdentityStore extends NylasStore {
*/ */
_onIdentityChanged = () => { _onIdentityChanged = () => {
this._identity = NylasEnv.config.get('nylasid') || {}; this._identity = NylasEnv.config.get('nylasid') || {};
if (!this._identity.token) {
this._identity.token = KeyManager.getPassword(KEYCHAIN_NAME); this._identity.token = KeyManager.getPassword(KEYCHAIN_NAME);
}
this.trigger(); this.trigger();
} }
@ -110,13 +109,7 @@ class IdentityStore extends NylasStore {
_onEnvChanged = () => { _onEnvChanged = () => {
const env = NylasEnv.config.get('env') const env = NylasEnv.config.get('env')
if (['development', 'local'].includes(env)) { if (['development', 'local'].includes(env)) {
if (process.env.BILLING_URL) { this.URLRoot = "http://localhost:5101";
this.URLRoot = process.env.BILLING_URL;
} else {
this.URLRoot = "https://billing-staging.nylas.com";
}
} else if (env === 'experimental') {
this.URLRoot = "https://billing-experimental.nylas.com";
} else if (env === 'staging') { } else if (env === 'staging') {
this.URLRoot = "https://billing-staging.nylas.com"; this.URLRoot = "https://billing-staging.nylas.com";
} else { } else {
@ -156,33 +149,26 @@ class IdentityStore extends NylasStore {
body.append(key, qs[key]); body.append(key, qs[key]);
} }
body.append('next_path', pathWithUtm); body.append('next_path', pathWithUtm);
body.append('account_token', this._identity.token);
const resp = await fetch(`${this.URLRoot}/n1/login-link`, { try {
method: 'POST', const json = await this.nylasIDRequest({
path: '/api/login-link',
qs: qs, qs: qs,
timeout: 1500,
body: body, body: body,
timeout: 1500,
method: 'POST',
}); });
if (resp.ok) { return `${this.URLRoot}${json.path}`;
const text = await resp.text(); } catch (err) {
if (text.startsWith('http')) {
return text;
}
}
return `${this.URLRoot}${path}`; return `${this.URLRoot}${path}`;
} }
async asyncRefreshIdentity() {
await this._fetchIdentity();
return true
} }
async _fetchIdentity() { async fetchIdentity() {
if (!this._identity || !this._identity.token) { if (!this._identity || !this._identity.token) {
return Promise.resolve(); return Promise.resolve();
} }
const json = await this.fetchPath('/n1/user'); const json = await this.nylasIDRequest({path: '/api/me', method: 'GET'});
if (!json || !json.id || json.id !== this._identity.id) { if (!json || !json.id || json.id !== this._identity.id) {
console.error(json) console.error(json)
NylasEnv.reportError(new Error("Remote Identity returned invalid json"), json || {}) NylasEnv.reportError(new Error("Remote Identity returned invalid json"), json || {})
@ -192,23 +178,11 @@ class IdentityStore extends NylasStore {
return this.saveIdentity(nextIdentity); return this.saveIdentity(nextIdentity);
} }
fetchPath = async (path) => {
const options = {
method: 'GET',
url: `${this.URLRoot}${path}`,
startTime: Date.now(),
};
try {
const newIdentity = await this.nylasIDRequest(options);
return newIdentity
} catch (err) {
const error = err || new Error(`IdentityStore.fetchPath: ${path} ${err.message}.`)
NylasEnv.reportError(error)
return null
}
}
async nylasIDRequest(options) { async nylasIDRequest(options) {
try {
if (options.path) {
options.url = `${this.URLRoot}${options.path}`;
}
options.credentials = 'include'; options.credentials = 'include';
options.headers = new Headers(); options.headers = new Headers();
options.headers.set('Authorization', `Basic ${btoa(`${this._identity.token}:`)}`) options.headers.set('Authorization', `Basic ${btoa(`${this._identity.token}:`)}`)
@ -217,6 +191,11 @@ class IdentityStore extends NylasStore {
throw new Error(resp.statusText); throw new Error(resp.statusText);
} }
return resp.json(); return resp.json();
} catch (err) {
const error = err || new Error(`IdentityStore.nylasIDRequest: ${options.url} ${err.message}.`)
NylasEnv.reportError(error)
return null
}
} }
} }

View file

@ -27,7 +27,7 @@ export default class SendFeatureUsageEventTask extends Task {
body.append('feature_name', this.featureName); body.append('feature_name', this.featureName);
const options = { const options = {
method: 'POST', method: 'POST',
url: `${IdentityStore.URLRoot}/n1/user/feature_usage_event`, path: `/api/feature_usage_event`,
body: body, body: body,
}; };
try { try {

View file

@ -23,7 +23,7 @@ export default class PackageManager {
} }
} }
this.discoverPacakges(); this.discoverPackages();
} }
pluginIdFor(packageName) { pluginIdFor(packageName) {
@ -31,7 +31,7 @@ export default class PackageManager {
return null return null
} }
discoverPacakges() { discoverPackages() {
for (const dir of this.packageDirectories) { for (const dir of this.packageDirectories) {
let filenames = []; let filenames = [];
try { try {