-
Notifications
You must be signed in to change notification settings - Fork 5
/
user.js
65 lines (59 loc) · 1.53 KB
/
user.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
/**
* A simple collection of functionality in regards to the current user.
*
* @class User
*/
import { hasToken } from "./token";
import { store, persistor } from "./store";
import { updateStatus, attemptAuthentication } from "./user.slice";
const selectStatus = state => state.user.status;
class User {
/**
* Used to keep track if we started attempting in this page view.
*
* @static
*/
static #attemptingThisRequest = false;
/**
* Returns whether a user is authenticated of not.
*
* @static
* @returns {boolean}
* @memberof User
*/
static isAuthenticated() {
store.dispatch(
updateStatus({
hasToken: hasToken("user"),
doFail: !User.#attemptingThisRequest
})
);
return selectStatus(store.getState()) === "authenticated";
}
/**
* Redirect to login.
*
* @param {string} loginUrl the URL to redirect to.
*/
static authenticate(loginUrl) {
// Switch state to attempting and flush state to session storage
// before redirecting.
store.dispatch(attemptAuthentication()).then(() => persistor.flush());
User.#attemptingThisRequest = true;
window.location.href = loginUrl;
}
/**
* Whether authentication failed.
*
* Will return true if we just tried authenticating and it failed.
*
* @returns {boolean}
*/
static authenticationFailed() {
// isAuthenticated() will ensure state is up to date.
return (
!this.isAuthenticated() && selectStatus(store.getState()) === "failed"
);
}
}
export default User;