touchstudy-core 0.1.3 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,4 @@
1
+ import { createBrowserHistory } from 'history';
1
2
  import { createAction, createReducer, configureStore } from '@reduxjs/toolkit';
2
3
  import moment from 'moment';
3
4
  import React, { useCallback, useState, useEffect, Fragment, useRef, useMemo } from 'react';
@@ -14,601 +15,11 @@ import { initReactI18next, useTranslation } from 'react-i18next';
14
15
  export { I18nextProvider, useTranslation } from 'react-i18next';
15
16
  import { IoChevronDown } from 'react-icons/io5';
16
17
 
17
- function _extends() {
18
- _extends = Object.assign ? Object.assign.bind() : function (target) {
19
- for (var i = 1; i < arguments.length; i++) {
20
- var source = arguments[i];
21
- for (var key in source) {
22
- if (Object.prototype.hasOwnProperty.call(source, key)) {
23
- target[key] = source[key];
24
- }
25
- }
26
- }
27
- return target;
28
- };
29
- return _extends.apply(this, arguments);
30
- }
31
-
32
- function isAbsolute(pathname) {
33
- return pathname.charAt(0) === '/';
34
- }
35
-
36
- // About 1.5x faster than the two-arg version of Array#splice()
37
- function spliceOne(list, index) {
38
- for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) {
39
- list[i] = list[k];
40
- }
41
-
42
- list.pop();
43
- }
44
-
45
- // This implementation is based heavily on node's url.parse
46
- function resolvePathname(to, from) {
47
- if (from === undefined) from = '';
48
-
49
- var toParts = (to && to.split('/')) || [];
50
- var fromParts = (from && from.split('/')) || [];
51
-
52
- var isToAbs = to && isAbsolute(to);
53
- var isFromAbs = from && isAbsolute(from);
54
- var mustEndAbs = isToAbs || isFromAbs;
55
-
56
- if (to && isAbsolute(to)) {
57
- // to is absolute
58
- fromParts = toParts;
59
- } else if (toParts.length) {
60
- // to is relative, drop the filename
61
- fromParts.pop();
62
- fromParts = fromParts.concat(toParts);
63
- }
64
-
65
- if (!fromParts.length) return '/';
66
-
67
- var hasTrailingSlash;
68
- if (fromParts.length) {
69
- var last = fromParts[fromParts.length - 1];
70
- hasTrailingSlash = last === '.' || last === '..' || last === '';
71
- } else {
72
- hasTrailingSlash = false;
73
- }
74
-
75
- var up = 0;
76
- for (var i = fromParts.length; i >= 0; i--) {
77
- var part = fromParts[i];
78
-
79
- if (part === '.') {
80
- spliceOne(fromParts, i);
81
- } else if (part === '..') {
82
- spliceOne(fromParts, i);
83
- up++;
84
- } else if (up) {
85
- spliceOne(fromParts, i);
86
- up--;
87
- }
88
- }
89
-
90
- if (!mustEndAbs) for (; up--; up) fromParts.unshift('..');
91
-
92
- if (
93
- mustEndAbs &&
94
- fromParts[0] !== '' &&
95
- (!fromParts[0] || !isAbsolute(fromParts[0]))
96
- )
97
- fromParts.unshift('');
98
-
99
- var result = fromParts.join('/');
100
-
101
- if (hasTrailingSlash && result.substr(-1) !== '/') result += '/';
102
-
103
- return result;
104
- }
105
-
106
- var isProduction = process.env.NODE_ENV === 'production';
107
- function warning(condition, message) {
108
- if (!isProduction) {
109
- if (condition) {
110
- return;
111
- }
112
-
113
- var text = "Warning: " + message;
114
-
115
- if (typeof console !== 'undefined') {
116
- console.warn(text);
117
- }
118
-
119
- try {
120
- throw Error(text);
121
- } catch (x) {}
122
- }
123
- }
124
-
125
- var isProduction$1 = process.env.NODE_ENV === 'production';
126
- var prefix = 'Invariant failed';
127
- function invariant(condition, message) {
128
- if (condition) {
129
- return;
130
- }
131
- if (isProduction$1) {
132
- throw new Error(prefix);
133
- }
134
- var provided = typeof message === 'function' ? message() : message;
135
- var value = provided ? "".concat(prefix, ": ").concat(provided) : prefix;
136
- throw new Error(value);
137
- }
138
-
139
- function addLeadingSlash(path) {
140
- return path.charAt(0) === '/' ? path : '/' + path;
141
- }
142
- function hasBasename(path, prefix) {
143
- return path.toLowerCase().indexOf(prefix.toLowerCase()) === 0 && '/?#'.indexOf(path.charAt(prefix.length)) !== -1;
144
- }
145
- function stripBasename(path, prefix) {
146
- return hasBasename(path, prefix) ? path.substr(prefix.length) : path;
147
- }
148
- function stripTrailingSlash(path) {
149
- return path.charAt(path.length - 1) === '/' ? path.slice(0, -1) : path;
150
- }
151
- function parsePath(path) {
152
- var pathname = path || '/';
153
- var search = '';
154
- var hash = '';
155
- var hashIndex = pathname.indexOf('#');
156
-
157
- if (hashIndex !== -1) {
158
- hash = pathname.substr(hashIndex);
159
- pathname = pathname.substr(0, hashIndex);
160
- }
161
-
162
- var searchIndex = pathname.indexOf('?');
163
-
164
- if (searchIndex !== -1) {
165
- search = pathname.substr(searchIndex);
166
- pathname = pathname.substr(0, searchIndex);
167
- }
168
-
169
- return {
170
- pathname: pathname,
171
- search: search === '?' ? '' : search,
172
- hash: hash === '#' ? '' : hash
173
- };
174
- }
175
- function createPath(location) {
176
- var pathname = location.pathname,
177
- search = location.search,
178
- hash = location.hash;
179
- var path = pathname || '/';
180
- if (search && search !== '?') path += search.charAt(0) === '?' ? search : "?" + search;
181
- if (hash && hash !== '#') path += hash.charAt(0) === '#' ? hash : "#" + hash;
182
- return path;
183
- }
184
-
185
- function createLocation(path, state, key, currentLocation) {
186
- var location;
187
-
188
- if (typeof path === 'string') {
189
- // Two-arg form: push(path, state)
190
- location = parsePath(path);
191
- location.state = state;
192
- } else {
193
- // One-arg form: push(location)
194
- location = _extends({}, path);
195
- if (location.pathname === undefined) location.pathname = '';
196
-
197
- if (location.search) {
198
- if (location.search.charAt(0) !== '?') location.search = '?' + location.search;
199
- } else {
200
- location.search = '';
201
- }
202
-
203
- if (location.hash) {
204
- if (location.hash.charAt(0) !== '#') location.hash = '#' + location.hash;
205
- } else {
206
- location.hash = '';
207
- }
208
-
209
- if (state !== undefined && location.state === undefined) location.state = state;
210
- }
211
-
212
- try {
213
- location.pathname = decodeURI(location.pathname);
214
- } catch (e) {
215
- if (e instanceof URIError) {
216
- throw new URIError('Pathname "' + location.pathname + '" could not be decoded. ' + 'This is likely caused by an invalid percent-encoding.');
217
- } else {
218
- throw e;
219
- }
220
- }
221
-
222
- if (key) location.key = key;
223
-
224
- if (currentLocation) {
225
- // Resolve incomplete/relative pathname relative to current location.
226
- if (!location.pathname) {
227
- location.pathname = currentLocation.pathname;
228
- } else if (location.pathname.charAt(0) !== '/') {
229
- location.pathname = resolvePathname(location.pathname, currentLocation.pathname);
230
- }
231
- } else {
232
- // When there is no prior location and pathname is empty, set it to /
233
- if (!location.pathname) {
234
- location.pathname = '/';
235
- }
236
- }
237
-
238
- return location;
239
- }
240
-
241
- function createTransitionManager() {
242
- var prompt = null;
243
-
244
- function setPrompt(nextPrompt) {
245
- process.env.NODE_ENV !== "production" ? warning(prompt == null, 'A history supports only one prompt at a time') : void 0;
246
- prompt = nextPrompt;
247
- return function () {
248
- if (prompt === nextPrompt) prompt = null;
249
- };
250
- }
251
-
252
- function confirmTransitionTo(location, action, getUserConfirmation, callback) {
253
- // TODO: If another transition starts while we're still confirming
254
- // the previous one, we may end up in a weird state. Figure out the
255
- // best way to handle this.
256
- if (prompt != null) {
257
- var result = typeof prompt === 'function' ? prompt(location, action) : prompt;
258
-
259
- if (typeof result === 'string') {
260
- if (typeof getUserConfirmation === 'function') {
261
- getUserConfirmation(result, callback);
262
- } else {
263
- process.env.NODE_ENV !== "production" ? warning(false, 'A history needs a getUserConfirmation function in order to use a prompt message') : void 0;
264
- callback(true);
265
- }
266
- } else {
267
- // Return false from a transition hook to cancel the transition.
268
- callback(result !== false);
269
- }
270
- } else {
271
- callback(true);
272
- }
273
- }
274
-
275
- var listeners = [];
276
-
277
- function appendListener(fn) {
278
- var isActive = true;
279
-
280
- function listener() {
281
- if (isActive) fn.apply(void 0, arguments);
282
- }
283
-
284
- listeners.push(listener);
285
- return function () {
286
- isActive = false;
287
- listeners = listeners.filter(function (item) {
288
- return item !== listener;
289
- });
290
- };
291
- }
292
-
293
- function notifyListeners() {
294
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
295
- args[_key] = arguments[_key];
296
- }
297
-
298
- listeners.forEach(function (listener) {
299
- return listener.apply(void 0, args);
300
- });
301
- }
302
-
303
- return {
304
- setPrompt: setPrompt,
305
- confirmTransitionTo: confirmTransitionTo,
306
- appendListener: appendListener,
307
- notifyListeners: notifyListeners
308
- };
309
- }
310
-
311
- var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
312
- function getConfirmation(message, callback) {
313
- callback(window.confirm(message)); // eslint-disable-line no-alert
314
- }
315
- /**
316
- * Returns true if the HTML5 history API is supported. Taken from Modernizr.
317
- *
318
- * https://github.com/Modernizr/Modernizr/blob/master/LICENSE
319
- * https://github.com/Modernizr/Modernizr/blob/master/feature-detects/history.js
320
- * changed to avoid false negatives for Windows Phones: https://github.com/reactjs/react-router/issues/586
321
- */
322
-
323
- function supportsHistory() {
324
- var ua = window.navigator.userAgent;
325
- if ((ua.indexOf('Android 2.') !== -1 || ua.indexOf('Android 4.0') !== -1) && ua.indexOf('Mobile Safari') !== -1 && ua.indexOf('Chrome') === -1 && ua.indexOf('Windows Phone') === -1) return false;
326
- return window.history && 'pushState' in window.history;
327
- }
328
- /**
329
- * Returns true if browser fires popstate on hash change.
330
- * IE10 and IE11 do not.
331
- */
332
-
333
- function supportsPopStateOnHashChange() {
334
- return window.navigator.userAgent.indexOf('Trident') === -1;
335
- }
336
- /**
337
- * Returns true if a given popstate event is an extraneous WebKit event.
338
- * Accounts for the fact that Chrome on iOS fires real popstate events
339
- * containing undefined state when pressing the back button.
340
- */
341
-
342
- function isExtraneousPopstateEvent(event) {
343
- return event.state === undefined && navigator.userAgent.indexOf('CriOS') === -1;
344
- }
345
-
346
- var PopStateEvent = 'popstate';
347
- var HashChangeEvent = 'hashchange';
348
-
349
- function getHistoryState() {
350
- try {
351
- return window.history.state || {};
352
- } catch (e) {
353
- // IE 11 sometimes throws when accessing window.history.state
354
- // See https://github.com/ReactTraining/history/pull/289
355
- return {};
356
- }
357
- }
358
- /**
359
- * Creates a history object that uses the HTML5 history API including
360
- * pushState, replaceState, and the popstate event.
361
- */
362
-
363
-
364
- function createBrowserHistory(props) {
365
- if (props === void 0) {
366
- props = {};
367
- }
368
-
369
- !canUseDOM ? process.env.NODE_ENV !== "production" ? invariant(false, 'Browser history needs a DOM') : invariant(false) : void 0;
370
- var globalHistory = window.history;
371
- var canUseHistory = supportsHistory();
372
- var needsHashChangeListener = !supportsPopStateOnHashChange();
373
- var _props = props,
374
- _props$forceRefresh = _props.forceRefresh,
375
- forceRefresh = _props$forceRefresh === void 0 ? false : _props$forceRefresh,
376
- _props$getUserConfirm = _props.getUserConfirmation,
377
- getUserConfirmation = _props$getUserConfirm === void 0 ? getConfirmation : _props$getUserConfirm,
378
- _props$keyLength = _props.keyLength,
379
- keyLength = _props$keyLength === void 0 ? 6 : _props$keyLength;
380
- var basename = props.basename ? stripTrailingSlash(addLeadingSlash(props.basename)) : '';
381
-
382
- function getDOMLocation(historyState) {
383
- var _ref = historyState || {},
384
- key = _ref.key,
385
- state = _ref.state;
386
-
387
- var _window$location = window.location,
388
- pathname = _window$location.pathname,
389
- search = _window$location.search,
390
- hash = _window$location.hash;
391
- var path = pathname + search + hash;
392
- process.env.NODE_ENV !== "production" ? warning(!basename || hasBasename(path, basename), 'You are attempting to use a basename on a page whose URL path does not begin ' + 'with the basename. Expected path "' + path + '" to begin with "' + basename + '".') : void 0;
393
- if (basename) path = stripBasename(path, basename);
394
- return createLocation(path, state, key);
395
- }
396
-
397
- function createKey() {
398
- return Math.random().toString(36).substr(2, keyLength);
399
- }
400
-
401
- var transitionManager = createTransitionManager();
402
-
403
- function setState(nextState) {
404
- _extends(history, nextState);
405
-
406
- history.length = globalHistory.length;
407
- transitionManager.notifyListeners(history.location, history.action);
408
- }
409
-
410
- function handlePopState(event) {
411
- // Ignore extraneous popstate events in WebKit.
412
- if (isExtraneousPopstateEvent(event)) return;
413
- handlePop(getDOMLocation(event.state));
414
- }
415
-
416
- function handleHashChange() {
417
- handlePop(getDOMLocation(getHistoryState()));
418
- }
419
-
420
- var forceNextPop = false;
421
-
422
- function handlePop(location) {
423
- if (forceNextPop) {
424
- forceNextPop = false;
425
- setState();
426
- } else {
427
- var action = 'POP';
428
- transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {
429
- if (ok) {
430
- setState({
431
- action: action,
432
- location: location
433
- });
434
- } else {
435
- revertPop(location);
436
- }
437
- });
438
- }
439
- }
440
-
441
- function revertPop(fromLocation) {
442
- var toLocation = history.location; // TODO: We could probably make this more reliable by
443
- // keeping a list of keys we've seen in sessionStorage.
444
- // Instead, we just default to 0 for keys we don't know.
445
-
446
- var toIndex = allKeys.indexOf(toLocation.key);
447
- if (toIndex === -1) toIndex = 0;
448
- var fromIndex = allKeys.indexOf(fromLocation.key);
449
- if (fromIndex === -1) fromIndex = 0;
450
- var delta = toIndex - fromIndex;
451
-
452
- if (delta) {
453
- forceNextPop = true;
454
- go(delta);
455
- }
456
- }
457
-
458
- var initialLocation = getDOMLocation(getHistoryState());
459
- var allKeys = [initialLocation.key]; // Public interface
460
-
461
- function createHref(location) {
462
- return basename + createPath(location);
463
- }
464
-
465
- function push(path, state) {
466
- process.env.NODE_ENV !== "production" ? warning(!(typeof path === 'object' && path.state !== undefined && state !== undefined), 'You should avoid providing a 2nd state argument to push when the 1st ' + 'argument is a location-like object that already has state; it is ignored') : void 0;
467
- var action = 'PUSH';
468
- var location = createLocation(path, state, createKey(), history.location);
469
- transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {
470
- if (!ok) return;
471
- var href = createHref(location);
472
- var key = location.key,
473
- state = location.state;
474
-
475
- if (canUseHistory) {
476
- globalHistory.pushState({
477
- key: key,
478
- state: state
479
- }, null, href);
480
-
481
- if (forceRefresh) {
482
- window.location.href = href;
483
- } else {
484
- var prevIndex = allKeys.indexOf(history.location.key);
485
- var nextKeys = allKeys.slice(0, prevIndex + 1);
486
- nextKeys.push(location.key);
487
- allKeys = nextKeys;
488
- setState({
489
- action: action,
490
- location: location
491
- });
492
- }
493
- } else {
494
- process.env.NODE_ENV !== "production" ? warning(state === undefined, 'Browser history cannot push state in browsers that do not support HTML5 history') : void 0;
495
- window.location.href = href;
496
- }
497
- });
498
- }
499
-
500
- function replace(path, state) {
501
- process.env.NODE_ENV !== "production" ? warning(!(typeof path === 'object' && path.state !== undefined && state !== undefined), 'You should avoid providing a 2nd state argument to replace when the 1st ' + 'argument is a location-like object that already has state; it is ignored') : void 0;
502
- var action = 'REPLACE';
503
- var location = createLocation(path, state, createKey(), history.location);
504
- transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {
505
- if (!ok) return;
506
- var href = createHref(location);
507
- var key = location.key,
508
- state = location.state;
509
-
510
- if (canUseHistory) {
511
- globalHistory.replaceState({
512
- key: key,
513
- state: state
514
- }, null, href);
515
-
516
- if (forceRefresh) {
517
- window.location.replace(href);
518
- } else {
519
- var prevIndex = allKeys.indexOf(history.location.key);
520
- if (prevIndex !== -1) allKeys[prevIndex] = location.key;
521
- setState({
522
- action: action,
523
- location: location
524
- });
525
- }
526
- } else {
527
- process.env.NODE_ENV !== "production" ? warning(state === undefined, 'Browser history cannot replace state in browsers that do not support HTML5 history') : void 0;
528
- window.location.replace(href);
529
- }
530
- });
531
- }
532
-
533
- function go(n) {
534
- globalHistory.go(n);
535
- }
536
-
537
- function goBack() {
538
- go(-1);
539
- }
540
-
541
- function goForward() {
542
- go(1);
543
- }
544
-
545
- var listenerCount = 0;
546
-
547
- function checkDOMListeners(delta) {
548
- listenerCount += delta;
549
-
550
- if (listenerCount === 1 && delta === 1) {
551
- window.addEventListener(PopStateEvent, handlePopState);
552
- if (needsHashChangeListener) window.addEventListener(HashChangeEvent, handleHashChange);
553
- } else if (listenerCount === 0) {
554
- window.removeEventListener(PopStateEvent, handlePopState);
555
- if (needsHashChangeListener) window.removeEventListener(HashChangeEvent, handleHashChange);
556
- }
557
- }
558
-
559
- var isBlocked = false;
560
-
561
- function block(prompt) {
562
- if (prompt === void 0) {
563
- prompt = false;
564
- }
565
-
566
- var unblock = transitionManager.setPrompt(prompt);
567
-
568
- if (!isBlocked) {
569
- checkDOMListeners(1);
570
- isBlocked = true;
571
- }
572
-
573
- return function () {
574
- if (isBlocked) {
575
- isBlocked = false;
576
- checkDOMListeners(-1);
577
- }
578
-
579
- return unblock();
580
- };
581
- }
582
-
583
- function listen(listener) {
584
- var unlisten = transitionManager.appendListener(listener);
585
- checkDOMListeners(1);
586
- return function () {
587
- checkDOMListeners(-1);
588
- unlisten();
589
- };
590
- }
591
-
592
- var history = {
593
- length: globalHistory.length,
594
- action: 'POP',
595
- location: initialLocation,
596
- createHref: createHref,
597
- push: push,
598
- replace: replace,
599
- go: go,
600
- goBack: goBack,
601
- goForward: goForward,
602
- block: block,
603
- listen: listen
604
- };
605
- return history;
606
- }
607
-
608
18
  var setLoading = createAction("common/setLoading");
609
19
  var setAlert = createAction("common/setAlert");
610
20
  var setUser = createAction("common/setUser");
611
21
  var setLanguage = createAction("common/setLanguage");
22
+ var reset = createAction("common/reset");
612
23
 
613
24
  var GOOGLE_CLIENT_ID = "64118819726-0qlur4qjrs9jbuu6rnoa0u91g680lmpg.apps.googleusercontent.com";
614
25
  var GOOGLE_RECAPTCHA_ID = "6LfNtLUaAAAAAL24lbBV11jS-gBtt1mhtxb4NXs0";
@@ -730,17 +141,37 @@ var AuthenticationMessage;
730
141
  })(AuthenticationMessage || (AuthenticationMessage = {}));
731
142
 
732
143
  var useGoogleSignOut = function useGoogleSignOut(props) {
144
+ var dispatch = useDispatch();
733
145
  var onLogoutSuccess = props.onLogoutSuccess,
734
146
  onFailure = props.onFailure;
147
+ var handleLogoutSuccess = function handleLogoutSuccess() {
148
+ onLogoutSuccess === null || onLogoutSuccess === void 0 ? void 0 : onLogoutSuccess();
149
+ };
150
+ var handleLogoutFailure = function handleLogoutFailure() {
151
+ onFailure === null || onFailure === void 0 ? void 0 : onFailure();
152
+ };
735
153
  var _useGoogleLogout = useGoogleLogout({
736
154
  clientId: GOOGLE_CLIENT_ID,
737
- onLogoutSuccess: onLogoutSuccess,
738
- onFailure: onFailure
155
+ onLogoutSuccess: handleLogoutSuccess,
156
+ onFailure: handleLogoutFailure
739
157
  }),
740
158
  signOut = _useGoogleLogout.signOut,
741
159
  loaded = _useGoogleLogout.loaded;
160
+ var handleSignOut = function handleSignOut() {
161
+ localStorage.removeItem("USER_INFORMATION");
162
+ localStorage.removeItem(ACCESS_TOKEN);
163
+ try {
164
+ signOut();
165
+ } catch (error) {
166
+ console.log({
167
+ error: error
168
+ });
169
+ }
170
+ dispatch(reset());
171
+ window.location.href = "/login";
172
+ };
742
173
  return {
743
- signOut: signOut,
174
+ handleSignOut: handleSignOut,
744
175
  loaded: loaded
745
176
  };
746
177
  };
@@ -759,14 +190,23 @@ var BlockLogin = function BlockLogin(_ref) {
759
190
  var _useGoogleReCaptcha = useGoogleReCaptcha(),
760
191
  executeRecaptcha = _useGoogleReCaptcha.executeRecaptcha;
761
192
  var _useGoogleSignOut = useGoogleSignOut({}),
762
- signOut = _useGoogleSignOut.signOut;
193
+ handleSignOut = _useGoogleSignOut.handleSignOut;
763
194
  var clickHandler = useCallback(function () {
764
195
  try {
196
+ var _exit = false;
765
197
  if (!executeRecaptcha) {
766
- console.log("execute recaptcha undefined");
767
198
  return Promise.resolve();
768
199
  }
769
- return Promise.resolve(executeRecaptcha("login"));
200
+ return Promise.resolve(_catch(function () {
201
+ return Promise.resolve(executeRecaptcha("login")).then(function (result) {
202
+ _exit = true;
203
+ return result;
204
+ });
205
+ }, function (error) {
206
+ console.log({
207
+ error: error
208
+ });
209
+ }));
770
210
  } catch (e) {
771
211
  return Promise.reject(e);
772
212
  }
@@ -774,65 +214,59 @@ var BlockLogin = function BlockLogin(_ref) {
774
214
  var handleVerify = useCallback(function () {}, []);
775
215
  var onSuccessGoogle = function onSuccessGoogle(res) {
776
216
  try {
777
- var _exit = false;
778
217
  return Promise.resolve(function () {
779
218
  if (!!(res !== null && res !== void 0 && res.accessToken)) {
780
- var _temp2 = function _temp2(_result) {
781
- if (_exit) return _result;
782
- dispatch(setLoading(false));
783
- };
784
219
  var _res$profileObj = res.profileObj,
785
220
  email = _res$profileObj.email,
786
221
  imageUrl = _res$profileObj.imageUrl,
787
222
  name = _res$profileObj.name;
788
223
  var accessToken = res.tokenObj.id_token;
789
224
  var googleId = res.googleId;
790
- var infoLogin = {
791
- imageUrl: imageUrl,
792
- fullName: name,
793
- email: email,
794
- token: accessToken,
795
- googleId: googleId
796
- };
797
- var role = isTeacher ? "Teacher" : "Student";
798
- dispatch(setLoading(true));
799
- var _temp = _catch(function () {
800
- return Promise.resolve(apiLoginGoogle(infoLogin, role)).then(function (res1) {
801
- var isFirstLogin = res1.data.isFirstLogin;
802
- var tokenJWT = res1.data.token;
803
- localStorage.setItem("USER_INFORMATION", JSON.stringify(infoLogin));
804
- localStorage.setItem(ACCESS_TOKEN, tokenJWT);
805
- if (isTeacher) {
806
- onNavigate("/teacher/overall-status/main");
807
- _exit = true;
808
- return;
809
- }
810
- if (isFirstLogin) {
811
- onNavigate("/register/info");
225
+ return Promise.resolve(clickHandler()).then(function (clickHandlerRes) {
226
+ function _temp2() {
227
+ dispatch(setLoading(false));
228
+ }
229
+ if (!clickHandlerRes) return;
230
+ var infoLogin = {
231
+ imageUrl: imageUrl,
232
+ fullName: name,
233
+ email: email,
234
+ token: accessToken,
235
+ googleId: googleId,
236
+ captcha: clickHandlerRes
237
+ };
238
+ var role = isTeacher ? "Teacher" : "Student";
239
+ dispatch(setLoading(true));
240
+ var _temp = _catch(function () {
241
+ return Promise.resolve(apiLoginGoogle(infoLogin, role)).then(function (res1) {
242
+ var isFirstLogin = res1.data.isFirstLogin;
243
+ var tokenJWT = res1.data.token;
244
+ localStorage.setItem("USER_INFORMATION", JSON.stringify(infoLogin));
245
+ localStorage.setItem(ACCESS_TOKEN, tokenJWT);
246
+ if (!isTeacher && isFirstLogin) {
247
+ onNavigate("/register/info");
248
+ } else {
249
+ onNavigate("/");
250
+ }
251
+ });
252
+ }, function (error) {
253
+ var _error$response, _error$response$data;
254
+ var message = undefined;
255
+ var type = error === null || error === void 0 ? void 0 : (_error$response = error.response) === null || _error$response === void 0 ? void 0 : (_error$response$data = _error$response.data) === null || _error$response$data === void 0 ? void 0 : _error$response$data.type;
256
+ if (type === AuthenticationMessage.NotAllowedToRegister) {
257
+ alert("가입 권한이 없는 계정입니다. 관리자에게 문의하세요.");
258
+ } else if (type) {
259
+ var _error$response2, _error$response2$data;
260
+ message = (error === null || error === void 0 ? void 0 : (_error$response2 = error.response) === null || _error$response2 === void 0 ? void 0 : (_error$response2$data = _error$response2.data) === null || _error$response2$data === void 0 ? void 0 : _error$response2$data.message) || ERROR_MESSAGE;
812
261
  } else {
813
- onNavigate("/student/check/main");
262
+ var _error$response3;
263
+ message = (error === null || error === void 0 ? void 0 : (_error$response3 = error.response) === null || _error$response3 === void 0 ? void 0 : _error$response3.data) || ERROR_MESSAGE;
814
264
  }
265
+ message && alert(message);
266
+ handleSignOut();
815
267
  });
816
- }, function (error) {
817
- var _error$response, _error$response$data;
818
- var message = undefined;
819
- var type = error === null || error === void 0 ? void 0 : (_error$response = error.response) === null || _error$response === void 0 ? void 0 : (_error$response$data = _error$response.data) === null || _error$response$data === void 0 ? void 0 : _error$response$data.type;
820
- if (type === AuthenticationMessage.NotAllowedToRegister) {
821
- alert("가입 권한이 없는 계정입니다. 관리자에게 문의하세요.");
822
- } else if (type) {
823
- var _error$response2, _error$response2$data;
824
- message = (error === null || error === void 0 ? void 0 : (_error$response2 = error.response) === null || _error$response2 === void 0 ? void 0 : (_error$response2$data = _error$response2.data) === null || _error$response2$data === void 0 ? void 0 : _error$response2$data.message) || ERROR_MESSAGE;
825
- } else {
826
- var _error$response3;
827
- message = (error === null || error === void 0 ? void 0 : (_error$response3 = error.response) === null || _error$response3 === void 0 ? void 0 : _error$response3.data) || ERROR_MESSAGE;
828
- }
829
- signOut();
830
- !!message && dispatch(setAlert({
831
- type: "danger",
832
- message: message
833
- }));
268
+ return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp);
834
269
  });
835
- return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp);
836
270
  }
837
271
  }());
838
272
  } catch (e) {
@@ -848,14 +282,10 @@ var BlockLogin = function BlockLogin(_ref) {
848
282
  validationSchema: schema,
849
283
  onSubmit: function (values) {
850
284
  try {
851
- return Promise.resolve(_catch(function () {
852
- return Promise.resolve(clickHandler()).then(function (clickHandlerRes) {
853
- if (!clickHandlerRes) return;
854
- values.captcha = clickHandlerRes;
855
- });
856
- }, function (err) {
857
- console.error(err);
858
- }));
285
+ return Promise.resolve(clickHandler()).then(function (clickHandlerRes) {
286
+ if (!clickHandlerRes) return;
287
+ values.captcha = clickHandlerRes;
288
+ });
859
289
  } catch (e) {
860
290
  return Promise.reject(e);
861
291
  }
@@ -891,13 +321,21 @@ var BlockLogin = function BlockLogin(_ref) {
891
321
  });
892
322
  };
893
323
 
324
+ var getAccessToken$1 = (function () {
325
+ try {
326
+ return localStorage.getItem(ACCESS_TOKEN);
327
+ } catch (err) {
328
+ return null;
329
+ }
330
+ });
331
+
894
332
  var defaultInfo = {
895
333
  email: "",
896
334
  password: "",
897
335
  captcha: "",
898
336
  rememberMe: false
899
337
  };
900
- var useLogin = function useLogin() {
338
+ var useLogin = function useLogin(onNavigate) {
901
339
  var _useState = useState(false),
902
340
  openLogin = _useState[0],
903
341
  setOpenLogin = _useState[1];
@@ -917,7 +355,11 @@ var useLogin = function useLogin() {
917
355
  scope: 'email'
918
356
  });
919
357
  };
920
- gapi.load('client:auth2', start);
358
+ !!gapi && gapi.load('client:auth2', start);
359
+ }, [gapi]);
360
+ useEffect(function () {
361
+ var token = getAccessToken$1();
362
+ if (!!token) onNavigate("/");
921
363
  }, []);
922
364
  return {
923
365
  defaultInfo: defaultInfo,
@@ -933,7 +375,7 @@ var useLogin = function useLogin() {
933
375
  var Login = function Login(_ref) {
934
376
  var onNavigate = _ref.onNavigate,
935
377
  isTeacher = _ref.isTeacher;
936
- var _useLogin = useLogin(),
378
+ var _useLogin = useLogin(onNavigate),
937
379
  defaultInfo = _useLogin.defaultInfo;
938
380
  return React.createElement("div", {
939
381
  className: styles["login"] + " container-fluid font-family-lato"
@@ -1054,7 +496,7 @@ function kindOf(val) {
1054
496
  }
1055
497
 
1056
498
  // src/utils/warning.ts
1057
- function warning$1(message) {
499
+ function warning(message) {
1058
500
  if (typeof console !== "undefined" && typeof console.error === "function") {
1059
501
  console.error(message);
1060
502
  }
@@ -1107,7 +549,7 @@ function combineReducers(reducers) {
1107
549
  const key = reducerKeys[i];
1108
550
  if (process.env.NODE_ENV !== "production") {
1109
551
  if (typeof reducers[key] === "undefined") {
1110
- warning$1(`No reducer provided for key "${key}"`);
552
+ warning(`No reducer provided for key "${key}"`);
1111
553
  }
1112
554
  }
1113
555
  if (typeof reducers[key] === "function") {
@@ -1132,7 +574,7 @@ function combineReducers(reducers) {
1132
574
  if (process.env.NODE_ENV !== "production") {
1133
575
  const warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache);
1134
576
  if (warningMessage) {
1135
- warning$1(warningMessage);
577
+ warning(warningMessage);
1136
578
  }
1137
579
  }
1138
580
  let hasChanged = false;
@@ -1172,6 +614,8 @@ var commonReducer = createReducer(initialState, function (builder) {
1172
614
  state.user = action.payload;
1173
615
  }).addCase(setLanguage, function (state, action) {
1174
616
  state.language = action.payload;
617
+ }).addCase(reset, function (_state, _action) {
618
+ return initialState;
1175
619
  });
1176
620
  });
1177
621
 
@@ -1248,14 +692,6 @@ var encodeParams$1 = (function (params) {
1248
692
  }).join('&');
1249
693
  });
1250
694
 
1251
- var getAccessToken$1 = (function () {
1252
- try {
1253
- return localStorage.getItem(ACCESS_TOKEN);
1254
- } catch (err) {
1255
- return null;
1256
- }
1257
- });
1258
-
1259
695
  var api$1 = axios.create({
1260
696
  baseURL: BASE_URL,
1261
697
  timeout: 0,
@@ -1307,15 +743,28 @@ var getInfo = function getInfo() {
1307
743
 
1308
744
  var LayoutContext = function LayoutContext(_ref) {
1309
745
  var children = _ref.children,
1310
- onNavigate = _ref.onNavigate;
746
+ role = _ref.role;
1311
747
  var _useGoogleSignOut = useGoogleSignOut({}),
1312
- signOut = _useGoogleSignOut.signOut;
748
+ handleSignOut = _useGoogleSignOut.handleSignOut;
1313
749
  var dispatch = useDispatch();
750
+ var user = useSelector(function (state) {
751
+ var _state$common;
752
+ return state === null || state === void 0 ? void 0 : (_state$common = state.common) === null || _state$common === void 0 ? void 0 : _state$common.user;
753
+ });
1314
754
  var resetAuth = function resetAuth() {
1315
- localStorage.removeItem(ACCESS_TOKEN);
1316
- signOut();
1317
- onNavigate("/login");
755
+ handleSignOut();
1318
756
  };
757
+ var checkRoleUser = useCallback(function () {
758
+ var _user$roles, _user$roles2;
759
+ if (!user) return;
760
+ var isAdmin = (_user$roles = user.roles) === null || _user$roles === void 0 ? void 0 : _user$roles.includes("Admin");
761
+ if (isAdmin && role !== "Teacher") alert(user.email + " not allow to register " + role);
762
+ if (isAdmin) return;
763
+ if (!((_user$roles2 = user.roles) !== null && _user$roles2 !== void 0 && _user$roles2.includes(role))) {
764
+ alert(user.email + " not allow to register " + role);
765
+ resetAuth();
766
+ }
767
+ }, [role, JSON.stringify(user)]);
1319
768
  var loadInfo = function loadInfo() {
1320
769
  try {
1321
770
  var _temp2 = function _temp2() {
@@ -1334,7 +783,11 @@ var LayoutContext = function LayoutContext(_ref) {
1334
783
  }
1335
784
  dispatch(setUser(info.data));
1336
785
  });
1337
- }, function () {
786
+ }, function (err) {
787
+ console.log({
788
+ err: err
789
+ });
790
+ role === "Student" ? alert("학생, 다시 로그인해주세요.") : alert("선생님, 다시 로그인해주세요.");
1338
791
  resetAuth();
1339
792
  });
1340
793
  return Promise.resolve(_temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp));
@@ -1343,8 +796,9 @@ var LayoutContext = function LayoutContext(_ref) {
1343
796
  }
1344
797
  };
1345
798
  useEffect(function () {
1346
- loadInfo();
1347
- }, []);
799
+ !user && loadInfo();
800
+ !!user && checkRoleUser();
801
+ }, [JSON.stringify(user)]);
1348
802
  return React.createElement(Fragment, null, children);
1349
803
  };
1350
804
 
@@ -1561,6 +1015,7 @@ var description_success = "스터디 터치는 엄태욱 선생님의 수업에
1561
1015
  var logout = "로그 아웃";
1562
1016
  var overall_status = "전체 현황";
1563
1017
  var exam_status = "시험별 현";
1018
+ var student_status = "학생 신분";
1564
1019
  var user_manager = "사용자 목록";
1565
1020
  var recent_exam_results = "최근 시험 결과";
1566
1021
  var instructor_name = "강사이름";
@@ -1605,6 +1060,7 @@ var no_data = "데이터 없음";
1605
1060
  var internet_connection_was_lost = "인터넷 연결이 끊어졌습니다";
1606
1061
  var problem = "문제";
1607
1062
  var problem_solving_time = "문제풀이 시간";
1063
+ var minutes = "분";
1608
1064
  var lang_ko = {
1609
1065
  problem_solving: problem_solving,
1610
1066
  my_story: my_story,
@@ -1616,6 +1072,7 @@ var lang_ko = {
1616
1072
  logout: logout,
1617
1073
  overall_status: overall_status,
1618
1074
  exam_status: exam_status,
1075
+ student_status: student_status,
1619
1076
  user_manager: user_manager,
1620
1077
  recent_exam_results: recent_exam_results,
1621
1078
  instructor_name: instructor_name,
@@ -1659,7 +1116,8 @@ var lang_ko = {
1659
1116
  no_data: no_data,
1660
1117
  internet_connection_was_lost: internet_connection_was_lost,
1661
1118
  problem: problem,
1662
- problem_solving_time: problem_solving_time
1119
+ problem_solving_time: problem_solving_time,
1120
+ minutes: minutes
1663
1121
  };
1664
1122
 
1665
1123
  var problem_solving$1 = "Problem Solving";
@@ -1672,6 +1130,7 @@ var description_success$1 = "Study Touch is a learning tool used in teacher Taew
1672
1130
  var logout$1 = "Logout";
1673
1131
  var overall_status$1 = "Overall Status";
1674
1132
  var exam_status$1 = "Exam Status";
1133
+ var student_status$1 = "Student Status";
1675
1134
  var user_manager$1 = "User Manager";
1676
1135
  var recent_exam_results$1 = "Recent exam";
1677
1136
  var instructor_name$1 = "Instructor name";
@@ -1716,6 +1175,7 @@ var no_data$1 = "No data";
1716
1175
  var internet_connection_was_lost$1 = "Internet connection was lost";
1717
1176
  var problem$1 = "Problem ";
1718
1177
  var problem_solving_time$1 = "Problem solving time";
1178
+ var minutes$1 = "m";
1719
1179
  var lang_en = {
1720
1180
  problem_solving: problem_solving$1,
1721
1181
  my_story: my_story$1,
@@ -1727,6 +1187,7 @@ var lang_en = {
1727
1187
  logout: logout$1,
1728
1188
  overall_status: overall_status$1,
1729
1189
  exam_status: exam_status$1,
1190
+ student_status: student_status$1,
1730
1191
  user_manager: user_manager$1,
1731
1192
  recent_exam_results: recent_exam_results$1,
1732
1193
  instructor_name: instructor_name$1,
@@ -1770,7 +1231,8 @@ var lang_en = {
1770
1231
  no_data: no_data$1,
1771
1232
  internet_connection_was_lost: internet_connection_was_lost$1,
1772
1233
  problem: problem$1,
1773
- problem_solving_time: problem_solving_time$1
1234
+ problem_solving_time: problem_solving_time$1,
1235
+ minutes: minutes$1
1774
1236
  };
1775
1237
 
1776
1238
  i18n.use(initReactI18next).init({
@@ -1902,7 +1364,20 @@ var toISOString = (function (time) {
1902
1364
  }
1903
1365
  });
1904
1366
 
1367
+ var canAccess = function canAccess(userRoles, componentRoles) {
1368
+ if (!Array.isArray(userRoles)) {
1369
+ return false;
1370
+ }
1371
+ if (Array.isArray(componentRoles)) {
1372
+ var intersects = userRoles.filter(function (i) {
1373
+ return componentRoles.includes(i);
1374
+ });
1375
+ return intersects.length > 0;
1376
+ }
1377
+ return true;
1378
+ };
1379
+
1905
1380
  var historyCore = createBrowserHistory();
1906
1381
 
1907
- export { ACCESS_TOKEN, BASE_URL, CommonAlert, CommonDialog, ConfirmDialog, CustomPagination, DATE_MIN_VALUE, EXAM_CHANNEL, ExamEvent, LayoutContext, Loading, Login, NotFound, PUSHER_CONFIG, TheLanguageDropdown, api$1 as api, diffFromNow, formatTime, historyCore, i18n, minutesToTimeSpan, setAlert, setLanguage, setLoading, setUser, store, toISOString, useGoogleSignOut, utcToLocalTime };
1382
+ export { ACCESS_TOKEN, BASE_URL, CommonAlert, CommonDialog, ConfirmDialog, CustomPagination, DATE_MIN_VALUE, EXAM_CHANNEL, ExamEvent, LayoutContext, Loading, Login, NotFound, PUSHER_CONFIG, TheLanguageDropdown, api$1 as api, canAccess as canAccessRoute, diffFromNow, formatTime, historyCore, i18n, minutesToTimeSpan, setAlert, setLanguage, setLoading, setUser, store, toISOString, useGoogleSignOut, utcToLocalTime };
1908
1383
  //# sourceMappingURL=index.modern.js.map