88 lines
2.9 KiB
TypeScript
88 lines
2.9 KiB
TypeScript
import {Injectable} from '@angular/core';
|
|
import {HttpClient} from '@angular/common/http';
|
|
import {BehaviorSubject, from, Observable, of} from "rxjs";
|
|
import {COOKIE, User} from "../login/utils/helper.class";
|
|
import {catchError, map, timeout} from "rxjs/operators";
|
|
import {NavigationEnd, Router} from "@angular/router";
|
|
import {EnvironmentSpecificService} from "../utils/properties/environment-specific.service";
|
|
|
|
@Injectable({
|
|
providedIn: 'root'
|
|
})
|
|
export class UserManagementService {
|
|
|
|
private getUserInfoSubject: BehaviorSubject<User> = new BehaviorSubject<User>(null);
|
|
private readonly promise: Promise<User>;
|
|
|
|
constructor(private http: HttpClient,
|
|
private router: Router,
|
|
private environmentSpecificService: EnvironmentSpecificService) {
|
|
this.promise = new Promise<any>((resolve => {
|
|
this.environmentSpecificService.subscribeEnvironment().subscribe(properties => {
|
|
const token = COOKIE.getCookie('AccessToken');
|
|
if (!token) {
|
|
this.getUserInfoSubject.next(null);
|
|
resolve();
|
|
} else {
|
|
this.http.get<User>(properties.userInfoUrl + token).pipe(map(userInfo => {
|
|
return this.parseUserInfo(userInfo);
|
|
})).pipe(timeout(3000), catchError(() => {
|
|
return of(null);
|
|
})).subscribe(user => {
|
|
this.getUserInfoSubject.next(user);
|
|
resolve();
|
|
});
|
|
}
|
|
});
|
|
}));
|
|
this.router.events.subscribe(event => {
|
|
if (event instanceof NavigationEnd) {
|
|
const token = COOKIE.getCookie('AccessToken');
|
|
if (!token && this.getUserInfoSubject.getValue() !== null) {
|
|
this.getUserInfoSubject.next(null);
|
|
}
|
|
}
|
|
})
|
|
}
|
|
|
|
public getUserInfo(subject: boolean = true): Observable<User> {
|
|
if(subject) {
|
|
return this.getUserInfoSubject.asObservable();
|
|
} else {
|
|
return from(this.getUserInfoAsync());
|
|
}
|
|
}
|
|
|
|
private async getUserInfoAsync(): Promise<User> {
|
|
await this.promise;
|
|
return this.getUserInfoSubject.getValue();
|
|
}
|
|
|
|
private parseUserInfo(info: any) {
|
|
const user: User = new User();
|
|
user.id = (info.sub && info.sub.indexOf('@')) ? info.sub.substring(0, info.sub.indexOf('@')) : info.sub;
|
|
user.firstname = (info.given_name) ? info.given_name : "";
|
|
user.lastname = (info.family_name) ? info.family_name : "";
|
|
user.email = info.email.toLowerCase(); // TODO remove, is a quick fix
|
|
user.fullname = (info.name) ? info.name : "";
|
|
if (user.fullname == "") {
|
|
if (user.firstname != "") {
|
|
user.fullname += user.firstname;
|
|
}
|
|
if (user.lastname != "") {
|
|
user.fullname += user.lastname;
|
|
}
|
|
if (user.fullname == "") { //fullname is still empty set a default
|
|
user.fullname = "Anonymous user";
|
|
}
|
|
}
|
|
if (info.edu_person_entitlements) {
|
|
user.role = info.edu_person_entitlements;
|
|
} else {
|
|
user.role = [];
|
|
}
|
|
user.expirationDate = info.exp;
|
|
return user;
|
|
}
|
|
}
|