-
Notifications
You must be signed in to change notification settings - Fork 38
/
user.store.js
317 lines (287 loc) · 10.8 KB
/
user.store.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
// dependencies ----------------------------------------------------------------------
import React from 'react';
import Reflux from 'reflux';
import hello from 'hellojs';
import async from 'async';
import Actions from './user.actions.js';
import config from '../../../config';
import router from '../utils/router-container';
import scitran from '../utils/scitran';
import crn from '../utils/crn';
import upload from '../upload/upload.actions';
import dashboardActions from '../dashboard/datasets.actions';
import datasetActions from '../dataset/dataset.actions';
import notifications from '../notification/notification.actions';
hello.init({google: config.auth.google.clientID});
let UserStore = Reflux.createStore({
// store setup -----------------------------------------------------------------------
listenables: Actions,
init() {
this.setInitialState();
},
getInitialState() {
return this.data;
},
// data ------------------------------------------------------------------------------
data: {},
update(data) {
for (let prop in data) {this.data[prop] = data[prop];}
this.trigger(this.data);
},
/**
* Set Initial State
*
* Sets the state to the data object defined
* inside the function. Also takes a diffs object
* which will set the state to the initial state
* with any differences passed.
*/
setInitialState(diffs) {
let data = {
token: window.localStorage.hello ? JSON.parse(window.localStorage.hello).google.access_token : null,
google: null,
scitran: window.localStorage.scitranUser ? JSON.parse(window.localStorage.scitranUser) : null,
loading: false,
signinError: '',
showUploadModal: false
};
for (let prop in diffs) {data[prop] = diffs[prop];}
this.update(data);
},
// Actions ---------------------------------------------------------------------------
/**
* Toggle Modal
*/
toggleModal(name) {
let updates = {};
updates['show' + name + 'Modal'] = !this.data['show' + name + 'Modal'];
this.update(updates);
},
/**
* Initialize OAuth
*
* Initializes the OAuth libarary (hello.js) and checks
* if a user is currently logged in.
*/
initOAuth() {
hello.init({google: config.auth.google.clientID}, {redirect_uri: '/'});
this.checkUser();
},
/**
* Check User
*
* Checks if the user has an active sessions and
* if they do instatiates their session data.
*/
checkUser() {
var googleAuth = hello('google').getAuthResponse();
var token = googleAuth && googleAuth.access_token ? googleAuth.access_token : null;
if (token) {
this.checkAuth((token) => {
this.update({token: token});
hello('google').api('/me').then((profile) => {
this.update({google: profile});
crn.verifyUser((err, res) => {
if (res.body.code === 403) {
this.signOut();
} else {
window.localStorage.scitranUser = JSON.stringify(res.body);
this.update({scitran: res.body});
}
});
}, () => {
this.setInitialState();
});
}, this.clearAuth);
} else {
this.setInitialState();
}
},
/**
* Signin
*
* Initiates the google OAuth2 sign in flow. Creates a new
* user if the user doesn't already exist.
*/
signIn(options) {
let transition = options.hasOwnProperty('transition') ? options.transition : true;
this.update({loading: true});
hello('google').login({scope: 'email,openid'}, (res) => {
if (res.error) {
this.update({loading: false});
return;
}
this.update({token: res.authResponse.access_token});
hello(res.network).api('/me').then((profile) => {
crn.verifyUser((err, res) => {
if (res.body.code === 403) {
let user = {
_id: profile.email,
firstname: profile.first_name,
lastname: profile.last_name
};
crn.createUser(user, (err, res) => {
if (res.body.status === 403) {
this.clearAuth();
let message = <span>This user account has been blocked. If you believe this is by mistake please contact the <a href="mailto:openfmri@gmail.com?subject=Center%20for%20Reproducible%20Neuroscience%20Blocked%20User" target="_blank">site adminstrator</a>.</span>;
if (!transition) {
notifications.createAlert({type: 'Error', message: message});
} else {
this.update({
loading: false,
signinError: message
});
}
return;
}
crn.verifyUser((err, res) => {
this.handleSignIn(transition, res.body, profile);
});
});
} else if (!res.body._id) {
this.clearAuth();
let message = 'We are currently experiencing issues. Please try again later.';
if (!transition) {
notifications.createAlert({type: 'Error', message: message});
} else {
this.update({
loading: false,
signinError: message
});
}
} else {
this.handleSignIn(transition, res.body, profile);
}
});
});
}, () => {
// signin failure
});
},
/**
* Handle Sign In
*
* Handles necessary action after a signin has been completed.
*/
handleSignIn(transition, scitranUser, googleProfile) {
window.localStorage.scitranUser = JSON.stringify(scitranUser);
this.update({scitran: scitranUser, google: googleProfile, loading: false});
if (transition) {
router.transitionTo('dashboard');
} else {
datasetActions.reloadDataset();
dashboardActions.getDatasets(true);
}
},
/**
* Sign Out
*
* Signs the user out by destroying the current
* OAuth2 session.
*/
signOut(uploadStatus) {
let signout = true;
if (uploadStatus === 'uploading') {
signout = confirm('You are currently uploading files. Signing out of this site will cancel the upload process. Are you sure you want to sign out?');
}
if (signout) {
hello('google').logout().then(() => {
upload.setInitialState();
this.clearAuth();
router.transitionTo('signIn');
}, () => {
// signout failure
});
}
},
/**
* Get Preferences
*
* Calls back with the current user's preferences.
*/
getPreferences(callback) {
callback(this.data.scitran.preferences);
},
/**
* Update Preferences
*/
updatePreferences(preferences, callback) {
let scitranUser = this.data.scitran;
scitranUser.preferences = scitranUser.preferences ? scitranUser.preferences : {};
for (let key in preferences) {
scitranUser.preferences[key] = preferences[key];
}
scitran.updateUser(this.data.scitran._id, {preferences: preferences}, (err, res) => {
this.update({scitran: scitranUser});
if (callback) {callback(err, res);}
});
},
// helper methods --------------------------------------------------------------------
/**
* Clear Authentication
*
* Clears all user related data from memory and
* browser storage.
*/
clearAuth() {
delete window.localStorage.hello;
delete window.localStorage.scitranUser;
this.setInitialState({
token: null,
google: null,
scitran: null
});
},
/**
* Has Token
*
* Returns a boolean representing whether or not
* the current session has an access token present
* regardless of whether or not is is expired/valid.
*/
hasToken() {
if (!window.localStorage.hello) {return false;}
let credentials = JSON.parse(window.localStorage.hello);
return credentials.hasOwnProperty('google') && credentials.google.hasOwnProperty('access_token') && credentials.google.access_token;
},
/**
* Is Token Valid
*
* Returns a boolean representing whether or not the
* current access token in valid.
*/
isTokenValid() {
var session = hello('google').getAuthResponse();
var currentTime = (new Date()).getTime() / 1000;
return session && session.access_token && session.expires > currentTime;
},
// request queue ---------------------------------------------------------------------
/**
* Authentication Request Queuing
*
* Before any request we verify the status of the OAuth token.
* To avoid multiple signin dialogues in the event the token
* is expired all auth checking is queued to be performed
* synchronously. The 'checkAuth' method is the primary method
* to start the token check process.
*/
queue: async.queue((authReq, callback) => {
let currentAccount = window.localStorage.hasOwnProperty('scitranUser') ? JSON.parse(window.localStorage.scitranUser).email : '';
hello('google').login({scope: 'email,openid', force: false, login_hint: currentAccount}).then((res) => {
authReq.successCallback(res.authResponse.access_token);
callback();
}, () => {
if (authReq.errorCallback) {
authReq.errorCallback();
} else {
this.clearAuth();
}
callback();
});
}, 1),
checkAuth(successCallback, errorCallback) {
let authReq = {successCallback, errorCallback};
this.queue.push(authReq);
}
});
export default UserStore;