-
Notifications
You must be signed in to change notification settings - Fork 144
/
Copy pathAccount.js
451 lines (415 loc) · 12.7 KB
/
Account.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
/* eslint-disable class-methods-use-this */
/**
* User Accounts
*
* Provides functionality for login, create account and settings sync.
*
* Ghostery Browser Extension
* https://www.ghostery.com/
*
* Copyright 2020 Ghostery, Inc. All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0
*/
import { isEqual } from 'underscore';
import build from 'redux-object';
import normalize from '../utils/json-api-normalizer';
import globals from './Globals';
import conf from './Conf';
import dispatcher from './Dispatcher';
import { alwaysLog, log } from '../utils/common';
import Api from '../utils/api';
import metrics from './MetricsWrapper';
import ghosteryDebugger from './Debugger';
import { cookiesGet, setAllLoginCookies, cookiesRemove } from '../utils/cookies';
const api = new Api();
const {
COOKIE_URL, AUTH_SERVER, ACCOUNT_SERVER, SYNC_ARRAY
} = globals;
const SYNC_SET = new Set(SYNC_ARRAY);
class Account {
constructor() {
const apiConfig = {
AUTH_SERVER,
ACCOUNT_SERVER,
COOKIE_URL
};
const opts = {
errorHandler: errors => (
new Promise((resolve, reject) => {
// eslint-disable-next-line no-unreachable-loop
for (let i = 0; i < errors.length; i++) {
const err = errors[i];
switch (err.code) {
case '10020': // token is not valid
case '10060': // user id does not match
case '10180': // user ID not found
case '10181': // user ID is missing
case '10190': // refresh token is expired
case '10200': // refresh token does not exist
case '10201': // refresh token is missing
case '10300': // csrf token is missing
case '10301': // csrf tokens do not match
// eslint-disable-next-line no-promise-executor-return
return this.logout()
.then(() => resolve())
.catch(() => resolve());
case '10030': // email not validated
case 'not-found':
// eslint-disable-next-line no-promise-executor-return
return reject(err);
default:
// eslint-disable-next-line no-promise-executor-return
return resolve();
}
}
// eslint-disable-next-line no-promise-executor-return
return resolve();
})
)
};
api.init(apiConfig, opts);
}
login = (email, password) => {
const data = `email=${window.encodeURIComponent(email)}&password=${encodeURIComponent(password)}`;
return fetch(`${AUTH_SERVER}/api/v2/login`, {
method: 'POST',
body: data,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
credentials: 'omit',
}).then((res) => {
if (res.status >= 400) {
throw res.json();
}
return res.json();
}).then(response => setAllLoginCookies({
accessToken: response.access_token,
refreshToken: response.refresh_token,
csrfToken: response.csrf_token,
userId: response.user_id,
})).then(() => {
ghosteryDebugger.addAccountEvent('login', 'cookie set by fetch POST');
this._getUserIDFromCookie().then((userID) => {
this._setAccountInfo(userID);
this.getUserSubscriptionData({ calledFrom: 'login' });
});
return {};
}).catch((err) => {
alwaysLog(err);
return err;
});
};
async logout() {
try {
const csrfCookie = await cookiesGet({ name: 'csrf_token' });
const accessTokenCookie = await cookiesGet({ name: 'access_token' });
if (!csrfCookie || !accessTokenCookie) {
throw new Error('no cookie');
}
const res = await fetch(`${AUTH_SERVER}/api/v2/logout`, {
method: 'POST',
credentials: 'omit',
headers: {
'X-CSRF-Token': csrfCookie.value,
Authorization: `Bearer ${accessTokenCookie.value}`,
},
});
if (res.status < 400) {
ghosteryDebugger.addAccountEvent('logout', 'cookie set by fetch POST');
return;
}
throw new Error(await res.json());
} finally {
// remove cookies in case fetch fails
this._removeCookies();
this._clearAccountInfo();
}
}
refreshToken = () => api.refreshToken();
// @TODO a 404 here should trigger a logout
getUser = () => (
this._getUserID()
.then(userID => api.get('users', userID))
.then((res) => {
if (Array.isArray(res?.errors) && res.errors.length > 0) {
log('We have a userID but we are not able to get data from the server. Force a logout. Errors:', res.errors);
throw new Error('Unable to fetch the user acount (forcing logout)');
}
if (!res.data?.id) {
alwaysLog('Unexpected case: the server sent missing data:', res);
throw new Error('User not properly logged in (got corrupted response)');
}
const user = build(normalize(res), 'users', res.data.id);
this._setAccountUserInfo(user);
return user;
})
);
getUserSettings = () => (
this._getUserIDIfEmailIsValidated()
.then(userID => api.get('settings', userID))
.then((res) => {
const settings = build(normalize(res, { camelizeKeys: false }), 'settings', res.data.id);
const { settings_json } = settings;
// if not onboarded do not let sync toggle the ONBOARDED_FEATURES features
if (!conf.setup_complete) {
globals.ONBOARDED_FEATURES.forEach((confName) => {
delete settings_json[confName];
});
}
// @TODO setConfUserSettings settings.settingsJson
this._setConfUserSettings(settings_json);
this._setAccountUserSettings(settings_json);
return settings_json;
})
// Fetching the settings from the account server failed,
// or they have simply never been synced to the account server yet
// In that case, just use the local settings
.catch(() => this.buildUserSettings())
);
/**
* @return {array} All subscriptions the user has, empty if none
*/
getUserSubscriptionData = options => (
this._getUserID()
.then(userID => api.get('stripe/customers', userID, 'cards,subscriptions'))
.then((res) => {
const customer = build(normalize(res), 'customers', res.data.id);
// TODO temporary fix to handle multiple subscriptions
let sub = customer.subscriptions;
if (!Array.isArray(sub)) {
sub = [sub];
}
const subscriptions = [];
const premiumSubscription = sub.find(subscription => subscription.productName.includes('Ghostery Premium'));
if (premiumSubscription) {
subscriptions.push(premiumSubscription);
this._setSubscriptionData(premiumSubscription);
}
const plusSubscription = sub.find(subscription => subscription.productName.includes('Ghostery Plus'));
if (plusSubscription) {
subscriptions.push(plusSubscription);
if (!premiumSubscription) {
this._setSubscriptionData(plusSubscription);
}
}
return subscriptions;
})
.finally(() => {
if (options && options.calledFrom === 'login') {
metrics.ping('sign_in_success');
}
})
);
saveUserSettings = () => (
this._getUserIDIfEmailIsValidated()
.then(userID => (
api.update('settings', {
type: 'settings',
id: userID,
attributes: {
settings_json: this.buildUserSettings()
}
})
))
);
getTheme = name => (
this._getUserID()
.then(() => {
const now = Date.now();
const { themeData } = conf.account;
if (!themeData || !themeData[name]) { return true; }
const { timestamp } = themeData[name];
return now - timestamp > 86400000; // true if 24hrs have passed
})
.then((shouldGet) => {
if (!shouldGet) {
return conf.account.themeData[name].css;
}
return api.get('themes', `${name}.css`)
.then((res) => {
const { css } = build(normalize(res), 'themes', res.data.id);
this._setThemeData({ name, css });
return css;
});
})
);
sendValidateAccountEmail = () => (
this._getUserID()
.then(userID => fetch(`${AUTH_SERVER}/api/v2/send_email/validate_account/${userID}`))
.then(res => res.status < 400)
);
resetPassword = (email) => {
const data = `email=${window.encodeURIComponent(email)}`;
return fetch(`${AUTH_SERVER}/api/v2/send_email/reset_password`, {
method: 'POST',
body: data,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
}).then((res) => {
if (res.status >= 400) {
return res.json();
}
return {};
});
};
/**
* Determines if the user has the required scope combination(s) to access a resource.
* It takes a rest parameter of string arrays, each of which must be a possible combination of
* scope strings that would allow a user to access a resource. For example, if the required
* scopes for a resource are "resource:read" AND "resource:write" OR ONLY "resource:god", call
* this function with parameters (['resource:read', 'resource:write'], ['resource:god'])
* IMPORTANT: this function does NOT verify the content of the user scopes, therefore scopes
* could have been tampered with.
*
* @param {...array} string arrays containing the required scope combination(s)
* @return {boolean} true if the user scopes match at least one of the required scope combination(s)
*/
hasScopesUnverified = (...required) => {
if (!conf.account) { return false; }
if (!conf.account.user) { return false; }
const userScopes = conf.account.user.scopes;
if (!userScopes) { return false; }
if (required.length === 0) { return false; }
// check scopes
if (userScopes.indexOf('god') >= 0) { return true; }
for (let i = 0; i < required.length; i++) {
const sArr = required[i];
let matches = true;
if (sArr.length > 0) {
for (let j = 0; j < sArr.length; j++) {
const s = sArr[j];
if (userScopes.indexOf(s) === -1) {
matches = false;
break;
}
}
if (matches) {
return true;
}
}
}
return false;
};
/**
* Create settings object for syncing and/or Export.
* @memberOf BackgroundUtils
*
* @return {Object} jsonifyable settings object for syncing
*/
buildUserSettings = () => {
const settings = {};
SYNC_SET.forEach((key) => {
settings[key] = conf[key];
});
return settings;
};
async _getUserID() {
if (!conf.account) {
try {
const userID = await this._getUserIDFromCookie();
if (userID) {
log('Found user ID', userID, 'in cookies');
this._setAccountInfo(userID);
}
} catch (e) {
log('Unable to get userID from cookie');
}
}
const userID = conf.account?.userID;
if (!userID) {
throw new Error('_getUserID: cannot find userID (neither in account or cookies)');
}
return userID;
}
async _getUserIDIfEmailIsValidated() {
const userID = await this._getUserID();
let { user } = conf.account;
if (!user) {
user = await this.getUser();
}
if (user?.emailValidated) {
return userID;
}
return new Error('_getUserIDIfEmailIsValidated(): email not validated');
}
_setAccountInfo = (userID) => {
conf.account = {
userID,
user: null,
userSettings: null,
subscriptionData: null,
themeData: null,
};
};
_setAccountUserInfo = (user) => {
conf.account.user = user;
dispatcher.trigger('conf.save.account');
};
_setAccountUserSettings = (settings) => {
conf.account.userSettings = settings;
dispatcher.trigger('conf.save.account');
};
_setSubscriptionData = (data) => {
// TODO: Change this so that we aren't writing over data
if (!conf.paid_subscription && data) {
conf.paid_subscription = true;
dispatcher.trigger('conf.save.paid_subscription');
}
conf.account.subscriptionData = data || null;
dispatcher.trigger('conf.save.account');
};
_setThemeData = (data) => {
if (!conf.account.themeData) {
conf.account.themeData = {};
}
const { name } = data;
conf.account.themeData[name] = { timestamp: Date.now(), ...data };
dispatcher.trigger('conf.save.account');
};
_clearAccountInfo = () => {
conf.account = null;
conf.current_theme = 'default';
};
_getUserIDFromCookie = async () => {
const cookie = await cookiesGet({ name: 'user_id' });
if (!cookie) {
throw new Error('err getting login user_id cookie');
}
return cookie.value;
};
/**
* GET user settings from ConsumerAPI
* @private
*
* @return {Promise} user settings json or error
*/
_setConfUserSettings = (settings) => {
const returnedSettings = { ...settings };
log('SET USER SETTINGS', returnedSettings);
SYNC_SET.forEach((key) => {
if (returnedSettings[key] !== undefined &&
!isEqual(conf[key], returnedSettings[key])) {
conf[key] = returnedSettings[key];
}
});
return returnedSettings;
};
_removeCookies = () => {
const cookies = ['user_id', 'access_token', 'refresh_token', 'csrf_token', 'AUTH'];
cookies.forEach(async (name) => {
try {
await cookiesRemove({ name });
log(`Removed cookie with name: ${name}`);
} catch (e) {
log(`Could not remove cookie with a name: ${name}`, e);
}
});
};
}
// Return the class as a singleton
export default new Account();