| /******************************************************************************** |
| * Copyright (c) 2020 Contributors to the Eclipse Foundation |
| * |
| * See the NOTICE file(s) distributed with this work for additional |
| * information regarding copyright ownership. |
| * |
| * This program and the accompanying materials are made available under the |
| * terms of the Eclipse Public License 2.0 which is available at |
| * http://www.eclipse.org/legal/epl-2.0 |
| * |
| * SPDX-License-Identifier: EPL-2.0 |
| ********************************************************************************/ |
| |
| import {Injectable} from "@angular/core"; |
| import {Actions, createEffect, ofType} from "@ngrx/effects"; |
| import {Action} from "@ngrx/store"; |
| import {Observable, of} from "rxjs"; |
| import {catchError, endWith, startWith, switchMap, take} from "rxjs/operators"; |
| import {CoreApiService} from "../../../core/api"; |
| import {AuthService} from "../../../core/auth"; |
| import {EHttpStatusCodes, isHttpErrorWithStatus} from "../../../util"; |
| import { |
| completeInitializationAction, |
| fetchVersionAction, |
| intializeAction, |
| keepSessionAliveAction, |
| openExitPageAction, |
| setUserAction, |
| toggleLoadingPageAction |
| } from "../actions"; |
| import {EExitCode} from "../model"; |
| |
| @Injectable({providedIn: "root"}) |
| export class InitializationEffect { |
| |
| public readonly initialize$ = createEffect(() => this.actions$.pipe( |
| ofType(intializeAction), |
| take(1), |
| switchMap(() => this.initialize()) |
| )); |
| |
| public constructor( |
| private readonly actions$: Actions, |
| private readonly authService: AuthService, |
| private readonly coreApiService: CoreApiService |
| ) { |
| |
| } |
| |
| public initialize(): Observable<Action> { |
| return this.initializeAuthStatus().pipe( |
| startWith(fetchVersionAction()), |
| catchError(() => of(openExitPageAction({code: EExitCode.UNKNOWN}))), |
| endWith(completeInitializationAction()), |
| endWith(toggleLoadingPageAction({isLoading: false})) |
| ); |
| } |
| |
| public initializeAuthStatus(): Observable<Action> { |
| const hasToken = this.authService.initialize(); |
| |
| if (!hasToken) { |
| return of(openExitPageAction({code: EExitCode.NO_TOKEN})); |
| } |
| |
| return this.coreApiService.getUserInfo().pipe( |
| switchMap((user) => of(setUserAction({user}), keepSessionAliveAction())), |
| catchError((err) => { |
| if (isHttpErrorWithStatus(err, EHttpStatusCodes.UNAUTHORIZED)) { |
| return of(openExitPageAction({code: EExitCode.UNAUTHORIZED})); |
| } |
| |
| if (isHttpErrorWithStatus(err, EHttpStatusCodes.FORBIDDEN)) { |
| return of(openExitPageAction({code: EExitCode.FORBIDDEN})); |
| } |
| |
| return of(openExitPageAction({code: EExitCode.UNKNOWN})); |
| }) |
| ); |
| } |
| |
| } |