This repository has been archived by the owner on Jan 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 28
/
authenticationActions.js
381 lines (341 loc) · 13.8 KB
/
authenticationActions.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
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
import React from 'react'
import environmentService from 'EnvironmentService'
import { hashHistory } from 'react-router'
import axios from 'axios'
import * as constants from '../constants/actions'
import * as appActions from '../actions/appActions'
import * as messengerActions from '../actions/messengerActions'
import * as cms from '../constants/cms'
import * as headerActions from '../actions/headerActions'
import * as cmsUtils from '../utils/cmsUtils'
import ApiError from '../components/ApiError/ApiError'
import ConfirmationBox from '../components/ConfirmationBox/ConfirmationBox'
import * as modalActions from '../actions/modalActions'
import * as manageSDBActions from '../actions/manageSafetyDepositBoxActions'
import * as workerTimers from 'worker-timers'
import { getLogger } from 'logger'
var log = getLogger('authentication-actions')
const AUTH_ACTION_TIMEOUT = 60000 // 60 seconds in milliseconds
/**
* These are the actions for authentication events that will trigger the related reducers to change application state
*/
/**
* This action is dispatched when we have a valid response object from the CMS Auth endpoint
* @param response The json response object from the ldap auth cms endpoint
* @param sessionExpirationCheckIntervalId ID of the interval that checks to see if the user's session has expired
* @returns {{type: string, payload: {tokenData: *}}} The object to dispatch to trigger the reducer to update the auth state
*/
export function loginUserSuccess(response, sessionExpirationCheckIntervalId) {
return {
type: constants.LOGIN_USER_SUCCESS,
payload: {
tokenData: response.data.client_token,
sessionExpirationCheckIntervalId: sessionExpirationCheckIntervalId
}
}
}
/**
* This action is dispatched to let the app state know that the auth request is in progress.
* @returns {{type: string}} The object to dispatch to trigger the reducer to update the auth state
*/
export function loginUserRequest() {
return {
type: constants.LOGIN_USER_REQUEST
}
}
/**
* Updates the state to indicate that MFA is required for the given user to authenticate.
* @returns {{type: string}} The object to dispatch to trigger the reducer to update the auth state
*/
export function loginMfaRequired(response) {
return {
type: constants.LOGIN_MFA_REQUIRED,
payload: {
stateToken: response.data.data.state_token,
mfaDevices: response.data.data.devices,
}
}
}
/**
* Updates the state to indicate that the user is successfully authenticated.
*/
function handleUserLogin(response, dispatch, redirectToWelcome=true) {
let leaseDurationInSeconds = response.data.data.client_token.lease_duration
const millisecondsPerSecond = 1000
const bestGuessOfRequestLatencyInMilliseconds = 120 * millisecondsPerSecond // take 2 minutes off of duration to account for latency
let now = new Date()
let cerberusAuthTokenExpiresDateInMilliseconds = (now.getTime() + ((leaseDurationInSeconds * millisecondsPerSecond) - bestGuessOfRequestLatencyInMilliseconds))
let tokenExpiresDate = new Date()
let token = response.data.data.client_token.client_token
tokenExpiresDate.setTime(cerberusAuthTokenExpiresDateInMilliseconds)
log.debug(`Setting session timeout to ${tokenExpiresDate}`)
let timeToExpireTokenInMillis = tokenExpiresDate.getTime() - now.getTime()
let sessionExpirationCheckIntervalInMillis = 2000
let sessionExpirationCheckIntervalId = workerTimers.setInterval(() => {
let currentTimeInMillis = new Date().getTime()
let sessionExpirationTimeInMillis = tokenExpiresDate.getTime()
if (currentTimeInMillis >= sessionExpirationTimeInMillis) {
dispatch(handleSessionExpiration())
}
}, sessionExpirationCheckIntervalInMillis)
let sessionWarningTimeoutId = workerTimers.setTimeout(() => {
dispatch(warnSessionExpiresSoon(token))
}, timeToExpireTokenInMillis - 120000) // warn two minutes before expiration
dispatch(setSessionWarningTimeoutId(sessionWarningTimeoutId))
sessionStorage.setItem('token', JSON.stringify(response.data))
sessionStorage.setItem('tokenExpiresDate', tokenExpiresDate)
sessionStorage.setItem('userRespondedToSessionWarning', false)
dispatch(messengerActions.clearAllMessages())
dispatch(loginUserSuccess(response.data, sessionExpirationCheckIntervalId))
dispatch(appActions.fetchSideBarData(token))
if (redirectToWelcome) {
hashHistory.push("/")
}
}
/**
* This action will let the state know that we are performing the auth
* It will then perform the authentication and update state after success
* @param username The Username of the user to auth
* @param password The password of the user to auth
* @returns {Function} The object to dispatch
*/
export function loginUser(username, password) {
return function(dispatch) {
dispatch(loginUserRequest())
return axios({
url: environmentService.getDomain() + cms.USER_AUTH_PATH,
auth: {
username: username,
password: password
},
timeout: AUTH_ACTION_TIMEOUT
})
.then(function (response) {
if (response.data.status === cms.MFA_REQUIRED_STATUS) {
dispatch(loginMfaRequired(response))
} else {
handleUserLogin(response, dispatch)
}
})
.catch(function (response) {
log.error('Failed to login user', response)
dispatch(messengerActions.addNewMessage(
<div className="login-error-msg-container">
<div className="login-error-msg-header">Failed to Login</div>
<div className="login-error-msg-content-wrapper">
<div className="login-error-msg-label">Server Message:</div>
<div className="login-error-msg-cms-msg">{cmsUtils.parseCMSError(response)}</div>
</div>
</div>
))
dispatch(resetAuthState())
})
}
}
/**
* This action re-authenticates a user with MFA, if MFA is required
* @param otpToken The security token of the user to auth
* @param mfaDeviceId ID of the MFA security device
* @param stateToken Identifying token for the authentication request
*/
export function finalizeMfaLogin(otpToken, mfaDeviceId, stateToken) {
return function(dispatch) {
dispatch(loginUserRequest())
return axios({
method: 'post',
url: environmentService.getDomain() + cms.USER_AUTH_MFA_PATH,
data: {
state_token: stateToken,
device_id: mfaDeviceId,
otp_token: otpToken
},
timeout: AUTH_ACTION_TIMEOUT
})
.then(function (response) {
handleUserLogin(response, dispatch)
})
.catch(function (response) {
log.error('Failed to finalize MFA login', response)
dispatch(messengerActions.addNewMessage(
<div className="login-error-msg-container">
<div className="login-error-msg-header">Failed to Login</div>
<div className="login-error-msg-content-wrapper">
<div className="login-error-msg-label">Server Message:</div>
<div className="login-error-msg-cms-msg">{cmsUtils.parseCMSError(response)}</div>
</div>
</div>
))
dispatch(resetAuthState())
})
}
}
/**
* This action is dispatched to renew a users session token
*/
export function refreshAuth(token, redirectPath='/', redirect=true) {
return function(dispatch) {
dispatch(loginUserRequest())
return axios({
url: environmentService.getDomain() + cms.USER_AUTH_PATH_REFRESH,
headers: {'X-Cerberus-Token': token},
timeout: AUTH_ACTION_TIMEOUT
})
.then(function (response) {
dispatch(handleRemoveSessionExpirationCheck())
dispatch(removeSessionWarningTimeout())
workerTimers.setTimeout(function(){
handleUserLogin(response, dispatch, false)
if (redirect) {
hashHistory.push(redirectPath)
}
}, 2000);
})
.catch(function (response) {
// Clears View Token Modal upon max refresh token limit to prevent errors
dispatch(modalActions.clearAllModals())
log.error('Failed to login user', response)
dispatch(resetAuthState())
hashHistory.push('dashboard/#/login')
dispatch(messengerActions.addNewMessage(<ApiError message="Failed to refresh user token" response={response} />))
})
}
}
/**
* This action is dispatched to log a user out
*/
export function logoutUser(token) {
return function(dispatch) {
return axios({
method: 'delete',
url: environmentService.getDomain() + cms.TOKEN_DELETE_PATH,
headers: {'X-Cerberus-Token': token},
timeout: AUTH_ACTION_TIMEOUT
})
.then(function () {
sessionStorage.removeItem('token')
sessionStorage.removeItem('tokenExpiresDate')
sessionStorage.removeItem('userRespondedToSessionWarning')
dispatch(handleRemoveSessionExpirationCheck())
dispatch(removeSessionWarningTimeout())
dispatch(resetAuthState())
dispatch(headerActions.mouseOutUsername())
hashHistory.push('/login')
})
.catch(function (response) {
log.error('Failed to logout user', response)
dispatch(messengerActions.addNewMessage(<ApiError message="Failed to Logout User" response={response} />))
})
}
}
/**
* This action is dispatched to log a user out
*/
export function handleSessionExpiration() {
return function(dispatch) {
sessionStorage.removeItem('token')
sessionStorage.removeItem('tokenExpiresDate')
sessionStorage.removeItem('userRespondedToSessionWarning')
dispatch(handleRemoveSessionExpirationCheck())
dispatch(removeSessionWarningTimeout())
dispatch(expireSession())
dispatch(modalActions.clearAllModals())
dispatch(manageSDBActions.resetToInitialState())
dispatch(appActions.resetToInitialState())
}
}
export function resetAuthState() {
return {
type: constants.RESET_USER_AUTH_STATE
}
}
export function expireSession() {
return {
type: constants.SESSION_EXPIRED
}
}
export function removeSessionExpirationCheck() {
return {
type: constants.REMOVE_SESSION_EXPIRATION_CHECK_INTERVAL
}
}
export function removeSessionWarningTimeoutId() {
return {
type: constants.REMOVE_SESSION_WARNING_TIMEOUT
}
}
export function setSessionWarningTimeoutId(id) {
return {
type: constants.SET_SESSION_WARNING_TIMEOUT_ID,
payload: {
sessionWarningTimeoutId: id
}
}
}
export function handleRemoveSessionExpirationCheck() {
return function(dispatch, getState) {
let sessionExpirationCheckIntervalId = getState().auth.sessionExpirationCheckIntervalId
log.debug(`Removing session expiration check interval, id: ${sessionExpirationCheckIntervalId}`)
try {
workerTimers.clearInterval(sessionExpirationCheckIntervalId)
} catch(err) {
console.log(`Failed to clear auth token timeout, id=${sessionExpirationCheckIntervalId}`)
console.log(err)
}
dispatch(removeSessionExpirationCheck())
}
}
export function removeSessionWarningTimeout() {
return function(dispatch, getState) {
let sessionWarningTimeoutId = getState().auth.sessionWarningTimeoutId
log.debug(`Removing warning timeout, id: ${sessionWarningTimeoutId}`)
try {
workerTimers.clearTimeout(getState().auth.sessionWarningTimeoutId)
} catch(err) {
console.log(`Failed to clear session warning timeout, id=${sessionWarningTimeoutId}`)
console.log(err)
}
dispatch(removeSessionWarningTimeoutId())
}
}
export function handleUserRespondedToSessionWarning() {
return function() {
sessionStorage.setItem('userRespondedToSessionWarning', true)
}
}
/**
* Warn the user at specified time that their session is about to expire
* @param timeToWarnInMillis - Time at which to warn user
* @param tokenStr - Token string
*/
export function setSessionWarningTimeout(timeToWarnInMillis, tokenStr) {
return function(dispatch) {
let userHasRespondedToSessionWarning = sessionStorage.getItem('userRespondedToSessionWarning') === "true";
if (! userHasRespondedToSessionWarning) {
let sessionWarningTimeoutId = workerTimers.setTimeout(() => {
dispatch(warnSessionExpiresSoon(tokenStr))
}, timeToWarnInMillis)
dispatch(setSessionWarningTimeoutId(sessionWarningTimeoutId))
}
}
}
/**
* Warn user that session is about to expire, and give the option to refresh session
* @param tokenStr - Token string
*/
export function warnSessionExpiresSoon(tokenStr) {
return function(dispatch) {
let yes = () => {
dispatch(refreshAuth(tokenStr, "/", false))
dispatch(handleUserRespondedToSessionWarning())
dispatch(modalActions.popModal())
}
let no = () => {
dispatch(handleUserRespondedToSessionWarning())
dispatch(modalActions.popModal())
}
let conf = <ConfirmationBox handleYes={yes}
handleNo={no}
message="Your session is about to expire. Would you like to stay logged in?"/>
dispatch(modalActions.pushModal(conf))
}
}