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 {map} from "rxjs/operators"; import {NavigationEnd, Router} from "@angular/router"; import {properties} from "../../../environments/environment"; @Injectable({ providedIn: 'root' }) export class UserManagementService{ private getUserInfoSubject: BehaviorSubject = new BehaviorSubject(null); private readonly promise: Promise; sub; routeSub; constructor(private http: HttpClient, private router: Router) { this.promise = new Promise((resolve => { this.updateUserInfo(resolve); })); this.routeSub = this.router.events.subscribe(event => { if (event instanceof NavigationEnd) { const token = COOKIE.getCookie('AccessToken'); if (!token && this.getUserInfoSubject.getValue() !== null) { this.getUserInfoSubject.next(null); } } }); } clearSubscriptions() { if(this.routeSub){ this.routeSub.unsubscribe(); } if(this.sub){ this.sub.unsubscribe(); } } public getUserInfo(subject: boolean = true): Observable { if (subject) { return this.getUserInfoSubject.asObservable(); } else { return from(this.getUserInfoAsync()); } } public updateUserInfo(resolve: Function = null) { const token = COOKIE.getCookie('AccessToken'); if (!token) { this.getUserInfoSubject.next(null); if(resolve) { resolve(); } } else { this.sub = this.http.get(properties.userInfoUrl + token).pipe(map(userInfo => { return this.parseUserInfo(userInfo); })).subscribe(user => { this.getUserInfoSubject.next(user); if(resolve) { resolve(); } }); } } private async getUserInfoAsync(): Promise { await this.promise; if(this.sub){ this.sub.unsubscribe(); } return this.getUserInfoSubject.getValue(); } private parseUserInfo(info: any) { const user: User = new User(); user.id = (info.subscriptions && info.subscriptions.indexOf('@')) ? info.subscriptions.substring(0, info.subscriptions.indexOf('@')) : info.subscriptions; 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"; } } user.role = []; if (info.roles) { info.roles.forEach(role => { user.role.push(role); }); }else{ if (info.edu_person_entitlements) { user.role = info.edu_person_entitlements; } } user.expirationDate = info.exp_date; return user; } }