aboutsummaryrefslogtreecommitdiff
path: root/cmd/web/js/app.js
blob: 4946dcc8bc72226c29c4fec3d0afa232dec8107a (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
'use strict';

var cookies = require('./cookies.js');
var page    = require('page');

var App = {};
var cookieExpire = 60 * 30;

App.errorCodeToMessage = function(code) {
  switch (code) {
    case 'invalid_email':
      return 'The email is not valid';
    case 'invalid_password':
      return 'The password is not valid';
    case 'email_exists':
      return 'This email is already registered';
    case 'invalid_credentials':
      return 'Invalid credentials';
    case 'invalid_otp':
      return 'Invalid code !';
    case 'user_not_confirmed':
      return 'Your account is being confirmed. Should be very soon !';
  }

  return code;
};

App.isUserSignedIn = function() {
  return cookies.hasItem('jwt');
};

App.getUserToken = function() {
  return cookies.getItem('jwt');
};

App.onUserSignIn = function(token) {
  if (!token || token === '') {
    page('/signin');
    return;
  }

  cookies.setItem('jwt', token, cookieExpire);
  page('/me');
};

App.onUserValidateOtp = function(token) {
  if (!token || token === '') {
    page('/signin');
    return;
  }

  cookies.setItem('jwt', token, cookieExpire);
  page('/me');
};

App.onUserSignUp = function(token) {
  if (!token || token === '') {
    page('/signin');
    return;
  }

  cookies.setItem('jwt', token, cookieExpire);
};

App.getUserJWT = function() {
  return cookies.getItem('jwt');
};

App.page = function(path, needsAuth, fn) {
  page(path, function(context) {
    if (needsAuth && !App.isUserSignedIn()) {
      page('/signin');
      return;
    }

    fn(context);
  });
};

App.go = function(path) {
  page(path);
};

App.start = function() {
  page();
};

App.onInternNavigation = function(href, e) {
  e.preventDefault();
  page(href);
};

App.onUserNotAuthorized = function(httpCode, apiCode) {
  switch (apiCode) {
    case 'not_authorized':
      cookies.removeItem('jwt');
      page('/signin');
      return false;
    case 'otp_not_setup':
      page('/otp/setup');
      return false;
    case 'need_otp_validation':
      page('/otp/validate');
      return false;
    default:
      return true;
  }
};

App.mount = function(app) {
  var root = React.createElement(
      'div',
      {className: 'container'},
      app
  );

  ReactDOM.unmountComponentAtNode(document.getElementById('app'));
  ReactDOM.render(root, document.getElementById('app'));
};

module.exports = App;