| 8 | const tokenKey = 'gotify-login-key'; |
| 9 | |
| 10 | export class CurrentUser { |
| 11 | private tokenCache: string | null = null; |
| 12 | private reconnectTimeoutId: number | null = null; |
| 13 | private reconnectTime = 7500; |
| 14 | @observable accessor loggedIn = false; |
| 15 | @observable accessor refreshKey = 0; |
| 16 | @observable accessor authenticating = true; |
| 17 | @observable accessor user: IUser = {name: 'unknown', admin: false, id: -1}; |
| 18 | @observable accessor connectionErrorMessage: string | null = null; |
| 19 | |
| 20 | public constructor(private readonly snack: SnackReporter) {} |
| 21 | |
| 22 | public token = (): string => { |
| 23 | if (this.tokenCache !== null) { |
| 24 | return this.tokenCache; |
| 25 | } |
| 26 | |
| 27 | const localStorageToken = window.localStorage.getItem(tokenKey); |
| 28 | if (localStorageToken) { |
| 29 | this.tokenCache = localStorageToken; |
| 30 | return localStorageToken; |
| 31 | } |
| 32 | |
| 33 | return ''; |
| 34 | }; |
| 35 | |
| 36 | private readonly setToken = (token: string) => { |
| 37 | this.tokenCache = token; |
| 38 | window.localStorage.setItem(tokenKey, token); |
| 39 | }; |
| 40 | |
| 41 | public register = async (name: string, pass: string): Promise<boolean> => |
| 42 | axios |
| 43 | .create() |
| 44 | .post(config.get('url') + 'user', {name, pass}) |
| 45 | .then(() => { |
| 46 | this.snack('User Created. Logging in...'); |
| 47 | this.login(name, pass); |
| 48 | return true; |
| 49 | }) |
| 50 | .catch((error: AxiosError<{error?: string; errorDescription?: string}>) => { |
| 51 | if (!error || !error.response) { |
| 52 | this.snack('No network connection or server unavailable.'); |
| 53 | return false; |
| 54 | } |
| 55 | const {data} = error.response; |
| 56 | |
| 57 | this.snack( |
| 58 | `Register failed: ${data?.error ?? 'unknown'}: ${data?.errorDescription ?? ''}` |
| 59 | ); |
| 60 | return false; |
| 61 | }); |
| 62 | |
| 63 | public login = async (username: string, password: string) => { |
| 64 | runInAction(() => { |
| 65 | this.loggedIn = false; |
| 66 | this.authenticating = true; |
| 67 | }); |
nothing calls this directly
no outgoing calls
no test coverage detected
searching dependent graphs…