blob: 2a89bb8bb1e49b0501d1f2f9201356f5ff06dc75 [file] [log] [blame]
/********************************************************************************
* Copyright (c) 2015-2018 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 v. 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 { HttpClient } from '@angular/common/http';
import { Router, ResolveStart } from '@angular/router';
import { PropertyService } from '../core/property.service';
import { Observable } from 'rxjs';
import { publishReplay, refCount, map, tap } from 'rxjs/operators';
export class User {
username: string;
roles: string[];
}
export enum Role {
Admin = 'Admin',
User = 'DescriptiveDataAuthor',
Guest = 'Guest',
}
@Injectable({
providedIn: 'root'
})
export class AuthenticationService {
readonly loginURL: string;
readonly logoutURL: string;
readonly currentUserURL: string;
private loginUser: Observable<User>;
constructor(private http: HttpClient,
private _prop: PropertyService) {
this.currentUserURL = _prop.getUrl('mdm/user/current');
}
isLoggedIn() {
return this.getLoginUser().pipe(map(user => user !== null));
}
getLoginUser() {
if (!this.loginUser) {
this.loginUser = this.loadUser().pipe(
publishReplay(1),
refCount()
);
}
return this.loginUser;
}
isUserInRole(roles: string | string[]) {
if (roles === undefined) {
return Observable.of(true);
} else if (typeof roles === 'string') {
roles = [ roles ];
}
return this.getLoginUser().pipe(
map(user => user.roles.filter(x => roles.includes(x)).length > 0)
);
}
private loadUser() {
return this.http.get<User>(this.currentUserURL, {
params: {
roles: Object.values(Role).join(',')
}
});
}
}