blob: 33ff3045425640f679f512709d1988faef0282f0 [file] [log] [blame]
/********************************************************************************
* 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 {concat, EMPTY, Observable, of} from "rxjs";
import {catchError, endWith, map, switchMap, take} from "rxjs/operators";
import {AuthInterceptorService, AuthService, CoreApiService} from "../../../core";
import {EHttpStatusCodes, isHttpErrorWithStatus} from "../../../util";
import {clearUserAction, completeInitializationAction, logOutAction, openExitPageAction, toggleLoadingPageAction} from "../actions";
import {EExitCode} from "../model";
@Injectable({providedIn: "root"})
export class UserEffect {
public readonly automaticLogOut$ = createEffect(() => this.actions.pipe(
ofType(completeInitializationAction),
switchMap(() => this.automaticLogOut())
));
public readonly logout$ = createEffect(() => this.actions.pipe(
ofType(logOutAction),
switchMap(() => this.logOut())
));
public constructor(
public actions: Actions,
private readonly coreApiService: CoreApiService,
private readonly authService: AuthService,
private readonly authInterceptorService: AuthInterceptorService
) {
}
public automaticLogOut(): Observable<Action> {
return this.authInterceptorService.unauthorized$.pipe(
take(1),
map(() => openExitPageAction({code: EExitCode.UNAUTHORIZED})),
endWith(clearUserAction())
);
}
public logOut(): Observable<Action> {
return concat(
of(toggleLoadingPageAction({isLoading: true})),
of(clearUserAction()),
this.coreApiService.logOut().pipe(
map(() => {
this.authService.clear();
return openExitPageAction({code: EExitCode.LOGOUT});
}),
catchError((err) => {
return isHttpErrorWithStatus(err, EHttpStatusCodes.UNAUTHORIZED) ?
EMPTY : // This case is handled by the automaticLogout$-Effect
of(openExitPageAction({code: EExitCode.LOGOUT_WITH_ERROR}));
}),
),
of(toggleLoadingPageAction({isLoading: false})),
);
}
}