blob: 8a27a1fe60397b16d76dc99e0859718d5db38979 [file]
/********************************************************************************
* 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/core/core-api.service";
import {AuthService} from "../../../core/auth/auth.service";
import {EHttpStatusCodes} from "../../../util/EHttpStatusCodes";
import {isHttpErrorWithStatus} from "../../../util/http.util";
import {EExitCode} from "../model/EExitCode";
import {
completeInitializationAction,
fetchVersionAction,
intializeAction,
keepSessionAliveAction,
openExitPageAction,
setUserAction,
toggleLoadingPageAction
} from "../root.actions";
@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((userInfo) => of(setUserAction(userInfo), 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}));
})
);
}
}