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
|
import { observable, computed, action } from 'mobx';
import moment from 'moment';
import jwt from 'jsonwebtoken';
import Store from './lib/Store';
import Request from './lib/Request';
import CachedRequest from './lib/CachedRequest';
import { gaEvent } from '../lib/analytics';
// TODO: split stores into UserStore and AuthStore
export default class UserStore extends Store {
BASE_ROUTE = '/auth';
WELCOME_ROUTE = `${this.BASE_ROUTE}/welcome`;
LOGIN_ROUTE = `${this.BASE_ROUTE}/login`;
LOGOUT_ROUTE = `${this.BASE_ROUTE}/logout`;
SIGNUP_ROUTE = `${this.BASE_ROUTE}/signup`;
PRICING_ROUTE = `${this.BASE_ROUTE}/signup/pricing`;
IMPORT_ROUTE = `${this.BASE_ROUTE}/signup/import`;
INVITE_ROUTE = `${this.BASE_ROUTE}/signup/invite`;
PASSWORD_ROUTE = `${this.BASE_ROUTE}/password`;
@observable loginRequest = new Request(this.api.user, 'login');
@observable signupRequest = new Request(this.api.user, 'signup');
@observable passwordRequest = new Request(this.api.user, 'password');
@observable inviteRequest = new Request(this.api.user, 'invite');
@observable getUserInfoRequest = new CachedRequest(this.api.user, 'getInfo');
@observable updateUserInfoRequest = new Request(this.api.user, 'updateInfo');
@observable getLegacyServicesRequest = new CachedRequest(this.api.user, 'getLegacyServices');
@observable deleteAccountRequest = new CachedRequest(this.api.user, 'delete');
@observable isImportLegacyServicesExecuting = false;
@observable isImportLegacyServicesCompleted = false;
@observable id;
@observable authToken = localStorage.getItem('authToken') || null;
@observable accountType;
@observable hasCompletedSignup = null;
@observable userData = {};
@observable actionStatus = [];
logoutReasonTypes = {
SERVER: 'SERVER',
};
@observable logoutReason = null;
constructor(...args) {
super(...args);
// Register action handlers
this.actions.user.login.listen(this._login.bind(this));
this.actions.user.retrievePassword.listen(this._retrievePassword.bind(this));
this.actions.user.logout.listen(this._logout.bind(this));
this.actions.user.signup.listen(this._signup.bind(this));
this.actions.user.invite.listen(this._invite.bind(this));
this.actions.user.update.listen(this._update.bind(this));
this.actions.user.resetStatus.listen(this._resetStatus.bind(this));
this.actions.user.importLegacyServices.listen(this._importLegacyServices.bind(this));
this.actions.user.delete.listen(this._delete.bind(this));
// Reactions
this.registerReactions([
this._requireAuthenticatedUser,
this._getUserData.bind(this),
]);
}
// Routes
get loginRoute() {
return this.LOGIN_ROUTE;
}
get logoutRoute() {
return this.LOGOUT_ROUTE;
}
get signupRoute() {
return this.SIGNUP_ROUTE;
}
get pricingRoute() {
return this.PRICING_ROUTE;
}
get inviteRoute() {
return this.INVITE_ROUTE;
}
get importRoute() {
return this.IMPORT_ROUTE;
}
get passwordRoute() {
return this.PASSWORD_ROUTE;
}
// Data
@computed get isLoggedIn() {
return this.authToken !== null && this.authToken !== undefined;
}
// @computed get isTokenValid() {
// return this.authToken !== null && moment(this.tokenExpiry).isAfter(moment());
// }
@computed get isTokenExpired() {
if (!this.authToken) return false;
const { tokenExpiry } = this._parseToken(this.authToken);
return this.authToken !== null && moment(tokenExpiry).isBefore(moment());
}
@computed get data() {
this.getUserInfoRequest.execute();
return this.getUserInfoRequest.result || {};
}
@computed get legacyServices() {
this.getLegacyServicesRequest.execute();
return this.getLegacyServicesRequest.result || [];
}
// Actions
@action async _login({ email, password }) {
const authToken = await this.loginRequest.execute(email, password)._promise;
this._setUserData(authToken);
this.stores.router.push('/');
gaEvent('User', 'login');
}
@action async _signup({ firstname, lastname, email, password, accountType, company }) {
const authToken = await this.signupRequest.execute({
firstname,
lastname,
email,
password,
accountType,
company,
});
this.hasCompletedSignup = false;
this._setUserData(authToken);
this.stores.router.push(this.PRICING_ROUTE);
gaEvent('User', 'signup');
}
@action async _retrievePassword({ email }) {
const request = this.passwordRequest.execute(email);
await request._promise;
this.actionStatus = request.result.status || [];
gaEvent('User', 'retrievePassword');
}
@action _invite({ invites }) {
const data = invites.filter(invite => invite.email !== '');
this.inviteRequest.execute(data);
console.log(this.stores.router.location )
// we do not wait for a server response before redirecting the user
this.stores.router.push('/');
gaEvent('User', 'inviteUsers');
}
@action async _update({ userData }) {
const response = await this.updateUserInfoRequest.execute(userData)._promise;
this.getUserInfoRequest.patch(() => response.data);
this.actionStatus = response.status || [];
gaEvent('User', 'update');
}
@action _resetStatus() {
this.actionStatus = [];
}
@action _logout() {
localStorage.removeItem('authToken');
this.getUserInfoRequest.invalidate().reset();
this.authToken = null;
// this.data = {};
}
@action async _importLegacyServices({ services }) {
this.isImportLegacyServicesExecuting = true;
// Reduces recipe duplicates
const recipes = services.filter((obj, pos, arr) => arr.map(mapObj => mapObj.recipe.id).indexOf(obj.recipe.id) === pos).map(s => s.recipe.id);
// Install recipes
for (const recipe of recipes) {
// eslint-disable-next-line
await this.stores.recipes._install({ recipeId: recipe });
}
for (const service of services) {
this.actions.service.createFromLegacyService({
data: service,
});
await this.stores.services.createServiceRequest._promise; // eslint-disable-line
}
this.isImportLegacyServicesExecuting = false;
this.isImportLegacyServicesCompleted = true;
}
@action async _delete() {
this.deleteAccountRequest.execute();
}
// This is a mobx autorun which forces the user to login if not authenticated
_requireAuthenticatedUser = () => {
if (this.isTokenExpired) {
this._logout();
}
const { router } = this.stores;
const currentRoute = router.location.pathname;
if (!this.isLoggedIn
&& !currentRoute.includes(this.BASE_ROUTE)) {
router.push(this.WELCOME_ROUTE);
} else if (this.isLoggedIn
&& currentRoute === this.LOGOUT_ROUTE) {
this.actions.user.logout();
router.push(this.LOGIN_ROUTE);
} else if (this.isLoggedIn
&& currentRoute.includes(this.BASE_ROUTE)
&& (this.hasCompletedSignup
|| this.hasCompletedSignup === null)) {
if (!isDevMode) {
this.stores.router.push('/');
}
}
};
// Reactions
async _getUserData() {
if (this.isLoggedIn) {
const data = await this.getUserInfoRequest.execute()._promise;
// We need to set the beta flag for the SettingsStore
this.actions.settings.update({
settings: {
beta: data.beta,
},
});
}
}
// Helpers
_parseToken(authToken) {
try {
const decoded = jwt.decode(authToken);
return ({
id: decoded.userId,
tokenExpiry: moment.unix(decoded.exp).toISOString(),
authToken,
});
} catch (err) {
console.error('AccessToken Invalid');
return false;
}
}
_setUserData(authToken) {
const data = this._parseToken(authToken);
if (data.authToken) {
localStorage.setItem('authToken', data.authToken);
this.authToken = data.authToken;
this.id = data.id;
} else {
this.authToken = null;
this.id = null;
}
}
}
|