generated from scale-tone/react-ts-basic
-
Notifications
You must be signed in to change notification settings - Fork 30
/
LoginState.ts
54 lines (41 loc) · 1.73 KB
/
LoginState.ts
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
import { observable, computed } from 'mobx'
import axios from 'axios';
const BackendUri = process.env.REACT_APP_BACKEND_BASE_URI as string;
// Handles login stuff
export class LoginState {
// Currently logged in user's name
@computed
get userName(): string { return this._userName; }
// Whether there was a login or not
@computed
get isLoggedInAnonymously(): boolean { return !this._userName; };
// Needed to anchor popup menu to
@observable
menuAnchorElement?: Element;
constructor() {
this.initializeAuth();
}
// Redirects user to EasyAuth's logout endpoint (so that they can choose a different login)
logout() {
this.menuAnchorElement = undefined;
window.location.href = `/.auth/logout`
}
@observable
private _userName: string;
private initializeAuth(): void {
// Auth cookies do expire. Here is a primitive way to forcibly re-authenticate the user
// (by refreshing the page), if that ever happens during an API call.
axios.interceptors.response.use(response => response, err => {
// This is what happens when an /api call fails because of expired/non-existend auth cookie
if (err.message === 'Network Error' && !!err.config && (err.config.url as string).startsWith(BackendUri) ) {
window.location.reload(true);
return;
}
return Promise.reject(err);
});
// Trying to obtain user info, as described here: https://docs.microsoft.com/en-us/azure/static-web-apps/user-information?tabs=javascript
axios.get(`/.auth/me`).then(result => {
this._userName = result.data?.clientPrincipal?.userDetails;
});
}
}