aboutsummaryrefslogtreecommitdiffstats
path: root/src/stores/UserStore.ts
blob: adf144b74d4e9e8b5e80c9b2412d15b8fc946b0a (plain) (blame)
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
import { ipcRenderer } from 'electron';
import jwt from 'jsonwebtoken';
import { action, computed, makeObservable, observable } from 'mobx';
import localStorage from 'mobx-localstorage';
import moment from 'moment';

import type { Stores } from '../@types/stores.types';
import type { Actions } from '../actions/lib/actions';
import type { ApiInterface } from '../api';
import { TODOS_PARTITION_ID } from '../config';
import { isDevMode } from '../environment-remote';
import CachedRequest from './lib/CachedRequest';
import Request from './lib/Request';
import TypedStore from './lib/TypedStore';

const debug = require('../preload-safe-debug')('Ferdium:UserStore');

// TODO: split stores into UserStore and AuthStore
export default class UserStore extends TypedStore {
  BASE_ROUTE: string = '/auth';

  WELCOME_ROUTE: string = `${this.BASE_ROUTE}/welcome`;

  LOGIN_ROUTE: string = `${this.BASE_ROUTE}/login`;

  LOGOUT_ROUTE: string = `${this.BASE_ROUTE}/logout`;

  SIGNUP_ROUTE: string = `${this.BASE_ROUTE}/signup`;

  SETUP_ROUTE: string = `${this.BASE_ROUTE}/signup/setup`;

  IMPORT_ROUTE: string = `${this.BASE_ROUTE}/signup/import`;

  INVITE_ROUTE: string = `${this.BASE_ROUTE}/signup/invite`;

  PASSWORD_ROUTE: string = `${this.BASE_ROUTE}/password`;

  CHANGE_SERVER_ROUTE: string = `${this.BASE_ROUTE}/server`;

  @observable loginRequest: Request = new Request(this.api.user, 'login');

  @observable signupRequest: Request = new Request(this.api.user, 'signup');

  @observable passwordRequest: Request = new Request(this.api.user, 'password');

  @observable inviteRequest: Request = new Request(this.api.user, 'invite');

  @observable getUserInfoRequest: CachedRequest = new CachedRequest(
    this.api.user,
    'getInfo',
  );

  @observable requestNewTokenRequest: CachedRequest = new CachedRequest(
    this.api.user,
    'requestNewToken',
  );

  @observable updateUserInfoRequest: Request = new Request(
    this.api.user,
    'updateInfo',
  );

  @observable deleteAccountRequest: CachedRequest = new CachedRequest(
    this.api.user,
    'delete',
  );

  @observable isImportLegacyServicesExecuting: boolean = false;

  @observable isImportLegacyServicesCompleted: boolean = false;

  @observable isLoggingOut: boolean = false;

  @observable id: string | null | undefined;

  @observable authToken: string | null =
    localStorage.getItem('authToken') || null;

  @observable accountType: string | undefined;

  @observable hasCompletedSignup: boolean = false;

  @observable userData: object = {};

  logoutReasonTypes = {
    SERVER: 'SERVER',
  };

  @observable logoutReason: string | null = null;

  constructor(stores: Stores, api: ApiInterface, actions: Actions) {
    super(stores, api, actions);

    makeObservable(this);

    // 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.bind(this),
      this._getUserData.bind(this),
    ]);
  }

  setup(): void {
    // Data migration
    this._migrateUserLocale();
  }

  // Routes
  get loginRoute(): string {
    return this.LOGIN_ROUTE;
  }

  get signupRoute(): string {
    return this.SIGNUP_ROUTE;
  }

  get passwordRoute(): string {
    return this.PASSWORD_ROUTE;
  }

  get changeServerRoute(): string {
    return this.CHANGE_SERVER_ROUTE;
  }

  // Data
  @computed get isLoggedIn(): boolean {
    return Boolean(localStorage.getItem('authToken'));
  }

  @computed get isTokenExpired(): boolean {
    if (!this.authToken) return false;
    const parsedToken = this._parseToken(this.authToken);

    return (
      parsedToken !== false &&
      this.authToken !== null &&
      moment(parsedToken.tokenExpiry).isBefore(moment())
    );
  }

  @computed get data() {
    if (!this.isLoggedIn) return {};

    const newTokenNeeded = this._shouldRequestNewToken(this.authToken);
    if (newTokenNeeded) {
      this._requestNewToken();
    }

    return this.getUserInfoRequest.execute().result || {};
  }

  @computed get team(): any {
    return this.data.team || null;
  }

  // Actions
  @action async _login({ email, password }): Promise<void> {
    const authToken = await this.loginRequest.execute(email, password).promise;
    this._setUserData(authToken);

    this.stores.router.push('/');
  }

  @action _tokenLogin(authToken: string): void {
    this._setUserData(authToken);

    this.stores.router.push('/');
  }

  @action async _signup({
    firstname,
    lastname,
    email,
    password,
    accountType,
    company,
    plan,
    currency,
  }): Promise<void> {
    // TODO: [TS DEBT] Need to find a way proper to implement promise's then and catch in request class
    // @ts-expect-error Fix me
    const authToken = await this.signupRequest.execute({
      firstname,
      lastname,
      email,
      password,
      accountType,
      company,
      locale: this.stores.app.locale,
      plan,
      currency,
    });

    this.hasCompletedSignup = true;

    this._setUserData(authToken);

    this.stores.router.push(this.SETUP_ROUTE);
  }

  @action async _retrievePassword({ email }): Promise<void> {
    const request = this.passwordRequest.execute(email);

    await request.promise;
    this.actionStatus = request.result.status || [];
  }

  @action async _invite({ invites }): Promise<void> {
    const data = invites.filter(invite => invite.email !== '');

    const response = await this.inviteRequest.execute(data).promise;

    this.actionStatus = response.status || [];

    // we do not wait for a server response before redirecting the user ONLY DURING SIGNUP
    if (this.stores.router.location.pathname.includes(this.INVITE_ROUTE)) {
      this.stores.router.push('/');
    }
  }

  @action async _update({ userData }): Promise<void> {
    if (!this.isLoggedIn) return;

    const response = await this.updateUserInfoRequest.execute(userData).promise;

    this.getUserInfoRequest.patch(() => response.data);
    this.actionStatus = response.status || [];
  }

  @action _resetStatus(): void {
    this.actionStatus = [];
  }

  @action _logout(): void {
    // workaround mobx issue
    localStorage.removeItem('authToken');
    window.localStorage.removeItem('authToken');

    this.getUserInfoRequest.invalidate().reset();
    this.authToken = null;

    this.stores.services.allServicesRequest.invalidate().reset();

    if (this.stores.todos.isTodosEnabled) {
      ipcRenderer.send('clear-storage-data', { sessionId: TODOS_PARTITION_ID });
    }
  }

  @action async _importLegacyServices({ services }): Promise<void> {
    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 no-await-in-loop
      await this.stores.recipes._install({ recipeId: recipe });
    }

    for (const service of services) {
      this.actions.service.createFromLegacyService({
        data: service,
      });
      // eslint-disable-next-line no-await-in-loop
      await this.stores.services.createServiceRequest.promise;
    }

    this.isImportLegacyServicesExecuting = false;
    this.isImportLegacyServicesCompleted = true;
  }

  @action async _delete(): Promise<void> {
    this.deleteAccountRequest.execute();
  }

  // This is a mobx autorun which forces the user to login if not authenticated
  _requireAuthenticatedUser = (): void => {
    if (this.isTokenExpired) {
      this._logout();
    }

    const { router } = this.stores;
    const currentRoute = window.location.hash;
    if (!this.isLoggedIn && currentRoute.includes('token=')) {
      router.push(this.WELCOME_ROUTE);
      const token = currentRoute.split('=')[1];

      const data = this._parseToken(token);
      if (data) {
        // Give this some time to sink
        setTimeout(() => {
          this._tokenLogin(token);
        }, 1000);
      }
    } else 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) &&
      !isDevMode
    ) {
      this.stores.router.push('/');
    }
  };

  // Reactions
  async _getUserData(): Promise<void> {
    if (this.isLoggedIn) {
      let data;
      try {
        data = await this.getUserInfoRequest.execute().promise;
      } catch {
        return;
      }

      // We need to set the beta flag for the SettingsStore
      this.actions.settings.update({
        type: 'app',
        data: {
          beta: data.beta,
          locale: data.locale,
        },
      });
    }
  }

  // Helpers
  _shouldRequestNewToken(authToken): boolean {
    try {
      const decoded = jwt.decode(authToken);
      if (!decoded) {
        throw new Error('Invalid token');
      }

      if (decoded.uid) {
        return true;
      }

      return false;
    } catch {
      return true;
    }
  }

  _requestNewToken(): void {
    // Logic to request new token (use an endpoint for that)
    const data = this.requestNewTokenRequest.execute().result;
    if (data) {
      this.authToken = data.token;
      localStorage.setItem('authToken', data.token);
    }
  }

  _parseToken(authToken) {
    try {
      const decoded = jwt.decode(authToken);

      return {
        id: decoded.userId,
        tokenExpiry: moment.unix(decoded.exp).toISOString(),
        authToken,
      };
    } catch {
      this._logout();
      return false;
    }
  }

  _setUserData(authToken: any): void {
    const data = this._parseToken(authToken);
    if (data !== false && data.authToken) {
      localStorage.setItem('authToken', data.authToken);

      this.authToken = data.authToken;
      this.id = data.id;
    } else {
      this.authToken = null;
      this.id = null;
    }
  }

  getAuthURL(url: string): string {
    const parsedUrl = new URL(url);
    const params = new URLSearchParams(parsedUrl.search.slice(1));

    // TODO: Remove the necessity for `as string`
    params.append('authToken', this.authToken!);

    return `${parsedUrl.origin}${parsedUrl.pathname}?${params.toString()}`;
  }

  async _migrateUserLocale(): Promise<void> {
    try {
      await this.getUserInfoRequest.promise;
    } catch {
      return;
    }

    if (!this.data.locale) {
      debug('Migrate "locale" to user data');
      this.actions.user.update({
        userData: {
          locale: this.stores.app.locale,
        },
      });
    }
  }
}