[Trunk | Library]:

1. community.service.ts: 
	a. Add BehaviorSubject for community.
	b. Method "isCommunityManager" replaced by "isCommunityManagerByState" (filtering applied in community stored in BehaviorSubject).
        c. Method "isRIType" replaced by "isRITypeByState" (filtering applied in community stored in BehaviorSubject).
        d. Method "isCommunityType" replaced by "isCommunityTypeByState" (filtering applied in community stored in BehaviorSubject).
2. connectAdminLoginGuard.guard.ts: 
	a. Get properties from environment (no service needed).
	b. Call method "isCommunityManagerByState" of CommunityService.
	c. Add "canDeactivate" method to unsubscribe (TODO: call method from routing modules).
3. connectCommunityGuard.guard.ts: 
        a. Get properties from environment (no service needed).
        b. Call method "isCommunityTypeByState" of CommunityService.
        c. Add "canDeactivate" method to unsubscribe (TODO: call method from routing modules).
4. connectRIGuard.guard.ts:
        a. Get properties from environment (no service needed).
        b. Call method "isRITypeByState" of CommunityService.
        c. Add "canDeactivate" method to unsubscribe (TODO: call method from routing modules).
5. isRouteEnabled.guard.ts: Add "canDeactivate" method to unsubscribe (TODO: call method from routing modules).
6. curator.service.ts: [Undo change of r59073] Use "useCache" property, not "useLongCache" for curators.


git-svn-id: https://svn.driver.research-infrastructures.eu/driver/dnet40/modules/uoa-services-library/trunk/ng-openaire-library/src/app@59140 d315682c-612b-4755-9ff5-7f18f6832af3
This commit is contained in:
konstantina.galouni 2020-07-16 23:08:10 +00:00
parent 04badde256
commit 0a1576d618
6 changed files with 226 additions and 116 deletions

View File

@ -1,132 +1,206 @@
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import {HttpClient, HttpHeaders} from "@angular/common/http"; import {HttpClient, HttpHeaders} from "@angular/common/http";
import { CommunityInfo } from './communityInfo'; import { CommunityInfo } from './communityInfo';
import {EnvProperties} from '../../utils/properties/env-properties'; import {EnvProperties} from '../../utils/properties/env-properties';
import {map} from "rxjs/operators"; import {map} from "rxjs/operators";
import {COOKIE} from "../../login/utils/helper.class"; import {BehaviorSubject, from} from "rxjs";
@Injectable() @Injectable({ providedIn: 'root' })
export class CommunityService { export class CommunityService {
constructor(private http: HttpClient) { public community: BehaviorSubject<CommunityInfo> = null;
} private promise: Promise<boolean> = null;
getCommunity(properties: EnvProperties, url: string) { constructor(private http: HttpClient) {
return this.http.get((properties.useCache) ? (properties.cacheUrl + encodeURIComponent(url)) : url) this.community = new BehaviorSubject(null);
//.map(res => <any> res.json()) }
.pipe(map(res => this.parseCommunity(res)));
getCommunityByService(properties: EnvProperties, url: string) {
console.debug("getCommunityByService");
this.promise = new Promise<any>(resolve => {
this.getCommunity(properties, url).subscribe(res => {
this.community.next(res);
resolve();
},
error => {
this.community.next(null);
resolve();
})
});
}
async getCommunityByStateAsync(properties: EnvProperties, url: string) {
if(!this.promise) {
this.getCommunityByService(properties, url);
} }
updateCommunity(url: string, community: any) { await this.promise;
//const headers = new Headers({'Content-Type': 'application/json'}); return this.community.getValue();
//const options = new RequestOptions({headers: headers}); }
const options = { getCommunityByState(properties: EnvProperties, url: string) {
headers: new HttpHeaders({ return from(this.getCommunityByStateAsync(properties, url));
'Content-Type': 'application/json', }
})
};
const body = JSON.stringify(community); /**
return this.http.post(url, body, options); * @deprecated
/*.map(res => res.json())*/ */
} getCommunity(properties: EnvProperties, url: string) {
isCommunityManager(properties: EnvProperties, url: string, manager: string) {
return this.http.get((properties.useCache) ? (properties.cacheUrl + encodeURIComponent(url)) : url) return this.http.get((properties.useCache) ? (properties.cacheUrl + encodeURIComponent(url)) : url)
//.map(res => <any> res.json()) //.map(res => <any> res.json())
.pipe(map(res => this.parseCommunity(res))) .pipe(map(res => this.parseCommunity(res)));
.pipe(map(community => community.managers.indexOf(manager) !== -1)); }
updateCommunity(url: string, community: any) {
//const headers = new Headers({'Content-Type': 'application/json'});
//const options = new RequestOptions({headers: headers});
const options = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
})
};
const body = JSON.stringify(community);
return this.http.post(url, body, options);
/*.map(res => res.json())*/
}
async isCommunityManagerByStateAsync(properties: EnvProperties, url: string, manager: string) {
if(!this.promise) {
this.getCommunityByService(properties, url);
} }
isRIType(properties: EnvProperties, url: string) { await this.promise;
let community: CommunityInfo = this.community.getValue();
return (community.managers.indexOf(manager) !== -1);
}
isCommunityManagerByState(properties: EnvProperties, url: string, manager: string) {
return from(this.isCommunityManagerByStateAsync(properties, url, manager));
}
/**
* @deprecated
*/
isCommunityManager(properties: EnvProperties, url: string, manager: string) {
return this.http.get((properties.useCache) ? (properties.cacheUrl + encodeURIComponent(url)) : url)
//.map(res => <any> res.json())
.pipe(map(res => this.parseCommunity(res)))
.pipe(map(community => community.managers.indexOf(manager) !== -1));
}
async isTypeByStateAsync(properties: EnvProperties, url: string, type: string) {
if(!this.promise) {
this.getCommunityByService(properties, url);
}
await this.promise;
let community: CommunityInfo = this.community.getValue();
return (community && community.type && community.type === type);
}
isRITypeByState(properties: EnvProperties, url: string) {
return from(this.isTypeByStateAsync(properties, url, "ri"));
}
isCommunityTypeByState(properties: EnvProperties, url: string) {
return from(this.isTypeByStateAsync(properties, url, "community"));
}
/**
* @deprecated
*/
isRIType(properties: EnvProperties, url: string) {
return this.http.get((properties.useCache) ? (properties.cacheUrl + encodeURIComponent(url)) : url)
//.map(res => <any> res.json())
.pipe(map(res => this.parseCommunity(res)))
.pipe(map(community => (community && community.type && community.type === 'ri')));
}
/**
* @deprecated
*/
isCommunityType(properties: EnvProperties, url: string) {
return this.http.get((properties.useCache) ? (properties.cacheUrl + encodeURIComponent(url)) : url) return this.http.get((properties.useCache) ? (properties.cacheUrl + encodeURIComponent(url)) : url)
//.map(res => <any> res.json()) //.map(res => <any> res.json())
.pipe(map(res => this.parseCommunity(res))) .pipe(map(res => this.parseCommunity(res)))
.pipe(map(community => (community && community.type && community.type === 'ri'))); .pipe(map(community => (community && community.type && community.type === 'community')));
} }
isCommunityType(properties: EnvProperties, url: string) { /**
return this.http.get((properties.useCache) ? (properties.cacheUrl + encodeURIComponent(url)) : url) * @deprecated
//.map(res => <any> res.json()) */
.pipe(map(res => this.parseCommunity(res))) isSubscribedToCommunity(pid: string, email: string, url: string) {
.pipe(map(community => (community && community.type && community.type === 'community'))); return this.http.get(url + '/community/' + pid + '/subscribers')
} //.map(res => ((<any>res === '') ? {} : <any> res.json()))
.pipe(map(res => {
if (res['subscribers'] && res['subscribers'] != null) {
/** for (let i = 0; i < res['subscribers'].length; i++ ) {
* @deprecated if (res['subscribers'][i] != null && res['subscribers'][i].email === email) {
*/ return true;
isSubscribedToCommunity(pid: string, email: string, url: string) {
return this.http.get(url + '/community/' + pid + '/subscribers')
//.map(res => ((<any>res === '') ? {} : <any> res.json()))
.pipe(map(res => {
if (res['subscribers'] && res['subscribers'] != null) {
for (let i = 0; i < res['subscribers'].length; i++ ) {
if (res['subscribers'][i] != null && res['subscribers'][i].email === email) {
return true;
}
} }
} }
return false; }
return false;
})); }));
} }
private parseCommunity(data: any): CommunityInfo { private parseCommunity(data: any): CommunityInfo {
const resData = Array.isArray(data) ? data[0] : data; const resData = Array.isArray(data) ? data[0] : data;
const community: CommunityInfo = new CommunityInfo(); const community: CommunityInfo = new CommunityInfo();
community['title'] = resData.name; community['title'] = resData.name;
community['shortTitle'] = resData.shortName; community['shortTitle'] = resData.shortName;
community['communityId'] = resData.id; community['communityId'] = resData.id;
community['queryId'] = resData.queryId; community['queryId'] = resData.queryId;
community['logoUrl'] = resData.logoUrl; community['logoUrl'] = resData.logoUrl;
community['description'] = resData.description; community['description'] = resData.description;
community['date'] = resData.creationDate; community['date'] = resData.creationDate;
community['zenodoCommunity'] = resData.zenodoCommunity; community['zenodoCommunity'] = resData.zenodoCommunity;
community['status'] = 'all'; community['status'] = 'all';
if (resData.hasOwnProperty('status')) { if (resData.hasOwnProperty('status')) {
community['status'] = resData.status; community['status'] = resData.status;
const status = ['all', 'hidden', 'manager']; const status = ['all', 'hidden', 'manager'];
if (status.indexOf(community['status']) === -1) { if (status.indexOf(community['status']) === -1) {
community['status'] = 'hidden'; community['status'] = 'hidden';
}
}
if (resData.type != null) {
community['type'] = resData.type;
}
if (resData.managers != null) {
if (community['managers'] === undefined) {
community['managers'] = new Array<string>();
} }
}
if (resData.type != null) {
community['type'] = resData.type;
}
if (resData.managers != null) { const managers = resData.managers;
if (community['managers'] === undefined) { const length = Array.isArray(managers) ? managers.length : 1;
community['managers'] = new Array<string>();
}
const managers = resData.managers; for (let i = 0; i < length; i++) {
const length = Array.isArray(managers) ? managers.length : 1; const manager = Array.isArray(managers) ? managers[i] : managers;
community.managers[i] = manager;
}
}
for (let i = 0; i < length; i++) { if (resData.subjects != null) {
const manager = Array.isArray(managers) ? managers[i] : managers; if (community['subjects'] === undefined) {
community.managers[i] = manager; community['subjects'] = new Array<string>();
} }
}
if (resData.subjects != null) { const subjects = resData.subjects;
if (community['subjects'] === undefined) { const length = Array.isArray(subjects) ? subjects.length : 1;
community['subjects'] = new Array<string>();
}
const subjects = resData.subjects; for (let i = 0; i < length; i++) {
const length = Array.isArray(subjects) ? subjects.length : 1; const subject = Array.isArray(subjects) ? subjects[i] : subjects;
community.subjects[i] = subject;
for (let i = 0; i < length; i++) { }
const subject = Array.isArray(subjects) ? subjects[i] : subjects; }
community.subjects[i] = subject; return community;
} }
}
return community;
}
} }

View File

@ -7,7 +7,7 @@ import {
RouterStateSnapshot, RouterStateSnapshot,
CanLoad, Route, UrlSegment CanLoad, Route, UrlSegment
} from '@angular/router'; } from '@angular/router';
import {Observable, of} from 'rxjs'; import {Observable, of, Subscription} from 'rxjs';
import {Session} from '../../login/utils/helper.class'; import {Session} from '../../login/utils/helper.class';
import {LoginErrorCodes} from '../../login/utils/guardHelper.class'; import {LoginErrorCodes} from '../../login/utils/guardHelper.class';
import {CommunityService} from '../community/community.service'; import {CommunityService} from '../community/community.service';
@ -15,9 +15,12 @@ import {EnvironmentSpecificService} from '../../utils/properties/environment-spe
import {ConnectHelper} from '../connectHelper'; import {ConnectHelper} from '../connectHelper';
import {StringUtils} from '../../utils/string-utils.class'; import {StringUtils} from '../../utils/string-utils.class';
import {UserManagementService} from "../../services/user-management.service"; import {UserManagementService} from "../../services/user-management.service";
import {properties} from "../../../../environments/environment";
@Injectable() @Injectable()
export class ConnectAdminLoginGuard implements CanActivate, CanLoad { export class ConnectAdminLoginGuard implements CanActivate, CanLoad {
sub: Subscription = null;
constructor(private router: Router, constructor(private router: Router,
private communityService: CommunityService, private communityService: CommunityService,
private propertiesService: EnvironmentSpecificService, private propertiesService: EnvironmentSpecificService,
@ -27,15 +30,17 @@ export class ConnectAdminLoginGuard implements CanActivate, CanLoad {
check(community: string, path: string): Observable<boolean> | boolean { check(community: string, path: string): Observable<boolean> | boolean {
let errorCode = LoginErrorCodes.NOT_LOGIN; let errorCode = LoginErrorCodes.NOT_LOGIN;
let email = null; let email = null;
const authorized = this.propertiesService.subscribeEnvironment().pipe(map(res => res), mergeMap(properties => { const authorized =
return this.userManagementService.getUserInfo(false).pipe(map(user => { //this.propertiesService.subscribeEnvironment().pipe(mergeMap(properties => {
//return
this.userManagementService.getUserInfo(false).pipe(map(user => {
if (user) { if (user) {
email = user.email; email = user.email;
if (Session.isPortalAdministrator(user) || Session.isCommunityCurator(user)) { if (Session.isPortalAdministrator(user) || Session.isCommunityCurator(user)) {
return of(true); return of(true);
} else { } else {
errorCode = LoginErrorCodes.NOT_ADMIN; errorCode = LoginErrorCodes.NOT_ADMIN;
return this.communityService.isCommunityManager(properties, properties['communityAPI'] + community, return this.communityService.isCommunityManagerByState(properties, properties['communityAPI'] + community,
email); email);
} }
} else { } else {
@ -44,8 +49,8 @@ export class ConnectAdminLoginGuard implements CanActivate, CanLoad {
}), mergeMap( authorized => { }), mergeMap( authorized => {
return authorized; return authorized;
})); }));
})); //}));
authorized.pipe(filter(authorized => !authorized)).subscribe(() => { this.sub = authorized.pipe(filter(authorized => !authorized)).subscribe(() => {
this.router.navigate(['/user-info'], { this.router.navigate(['/user-info'], {
queryParams: { queryParams: {
'errorCode': errorCode, 'errorCode': errorCode,
@ -63,4 +68,11 @@ export class ConnectAdminLoginGuard implements CanActivate, CanLoad {
const path = StringUtils.URLSegmentsToPath(segments) + document.location.search; const path = StringUtils.URLSegmentsToPath(segments) + document.location.search;
return this.check(ConnectHelper.getCommunityFromPath(path), path); return this.check(ConnectHelper.getCommunityFromPath(path), path);
} }
canDeactivate() {
if(this.sub) {
this.sub.unsubscribe();
}
return true;
}
} }

View File

@ -9,13 +9,15 @@ import {
CanLoad, CanLoad,
Route Route
} from '@angular/router'; } from '@angular/router';
import {Observable} from 'rxjs'; import {Observable, Subscription} from 'rxjs';
import {CommunityService} from '../community/community.service'; import {CommunityService} from '../community/community.service';
import { EnvironmentSpecificService} from '../../utils/properties/environment-specific.service'; import { EnvironmentSpecificService} from '../../utils/properties/environment-specific.service';
import {ConnectHelper} from '../connectHelper'; import {ConnectHelper} from '../connectHelper';
import {properties} from "../../../../environments/environment";
@Injectable() @Injectable()
export class ConnectCommunityGuard implements CanActivate { export class ConnectCommunityGuard implements CanActivate {
sub: Subscription = null;
constructor(private router: Router, constructor(private router: Router,
private communityService: CommunityService, private communityService: CommunityService,
@ -23,10 +25,9 @@ export class ConnectCommunityGuard implements CanActivate {
} }
check(community: string): Observable<boolean> | boolean { check(community: string): Observable<boolean> | boolean {
const obs = this.propertiesService.subscribeEnvironment().pipe(mergeMap(properties => { const obs = this.communityService.isCommunityTypeByState(properties, properties['communityAPI'] + community);
return this.communityService.isCommunityType(properties, properties['communityAPI'] + community);
})); this.sub = obs.pipe(filter(enabled => !enabled))
obs.pipe(filter(enabled => !enabled))
.subscribe(() => this.router.navigate(['errorcommunity'])); .subscribe(() => this.router.navigate(['errorcommunity']));
return obs; return obs;
} }
@ -34,4 +35,11 @@ export class ConnectCommunityGuard implements CanActivate {
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean { canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
return this.check(route.queryParams['communityId']); return this.check(route.queryParams['communityId']);
} }
canDeactivate() {
if(this.sub) {
this.sub.unsubscribe();
}
return true;
}
} }

View File

@ -9,13 +9,15 @@ import {
CanLoad, CanLoad,
Route, UrlSegment Route, UrlSegment
} from '@angular/router'; } from '@angular/router';
import {Observable} from 'rxjs'; import {Observable, Subscription} from 'rxjs';
import {CommunityService} from '../community/community.service'; import {CommunityService} from '../community/community.service';
import { EnvironmentSpecificService} from '../../utils/properties/environment-specific.service'; import { EnvironmentSpecificService} from '../../utils/properties/environment-specific.service';
import {ConnectHelper} from '../connectHelper'; import {ConnectHelper} from '../connectHelper';
import {properties} from "../../../../environments/environment";
@Injectable() @Injectable()
export class ConnectRIGuard implements CanActivate, CanLoad { export class ConnectRIGuard implements CanActivate, CanLoad {
sub: Subscription = null;
constructor(private router: Router, constructor(private router: Router,
private communityService: CommunityService, private communityService: CommunityService,
@ -23,10 +25,9 @@ export class ConnectRIGuard implements CanActivate, CanLoad {
} }
check(community: string): Observable<boolean> | boolean { check(community: string): Observable<boolean> | boolean {
const obs = this.propertiesService.subscribeEnvironment().pipe(mergeMap(properties => { const obs = this.communityService.isRITypeByState(properties, properties['communityAPI'] + community);
return this.communityService.isRIType(properties, properties['communityAPI'] + community);
})); this.sub = obs.pipe(filter(enabled => !enabled))
obs.pipe(filter(enabled => !enabled))
.subscribe(() => this.router.navigate(['errorcommunity'])); .subscribe(() => this.router.navigate(['errorcommunity']));
return obs; return obs;
} }
@ -39,4 +40,11 @@ export class ConnectRIGuard implements CanActivate, CanLoad {
const path = '/' + route.path + document.location.search; const path = '/' + route.path + document.location.search;
return this.check(ConnectHelper.getCommunityFromPath(path)); return this.check(ConnectHelper.getCommunityFromPath(path));
} }
canDeactivate() {
if(this.sub) {
this.sub.unsubscribe();
}
return true;
}
} }

View File

@ -13,7 +13,7 @@ export class CuratorService {
public getCurators(properties: EnvProperties, emails: string): Observable<Curator[]> { public getCurators(properties: EnvProperties, emails: string): Observable<Curator[]> {
let url: string = properties.adminToolsAPIURL + '/curator?emails='+emails; let url: string = properties.adminToolsAPIURL + '/curator?emails='+emails;
return this.http.get<Curator[]>((properties.useLongCache) ? (properties.cacheUrl + encodeURIComponent(url)) : url); return this.http.get<Curator[]>((properties.useCache) ? (properties.cacheUrl + encodeURIComponent(url)) : url);
} }
public updateCurator(properties: EnvProperties, curator: Curator) { public updateCurator(properties: EnvProperties, curator: Curator) {
@ -23,7 +23,7 @@ export class CuratorService {
public getCurator(properties: EnvProperties, curatorId: string): Observable<Curator> { public getCurator(properties: EnvProperties, curatorId: string): Observable<Curator> {
let url: string = properties.adminToolsAPIURL + 'curator/'+curatorId; let url: string = properties.adminToolsAPIURL + 'curator/'+curatorId;
return this.http.get<Curator>((properties.useLongCache) ? (properties.cacheUrl + encodeURIComponent(url)) : url); return this.http.get<Curator>((properties.useCache) ? (properties.cacheUrl + encodeURIComponent(url)) : url);
} }
} }

View File

@ -1,5 +1,5 @@
import {of as observableOf, Observable, Subject} from 'rxjs'; import {of as observableOf, Observable, Subject, Subscription} from 'rxjs';
import {map, filter, mergeMap, tap} from 'rxjs/operators'; import {map, filter, mergeMap, tap} from 'rxjs/operators';
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
@ -22,6 +22,7 @@ import {Page} from "../utils/entities/adminTool/page";
@Injectable() @Injectable()
export class IsRouteEnabled implements CanActivate { export class IsRouteEnabled implements CanActivate {
sub: Subscription = null;
constructor(private router: Router, constructor(private router: Router,
private config: ConfigurationService, private config: ConfigurationService,
@ -74,7 +75,7 @@ export class IsRouteEnabled implements CanActivate {
const obs = const obs =
//this.config.isPageEnabled(properties, community, '/' + path); //this.config.isPageEnabled(properties, community, '/' + path);
this.config.isPageEnabledByState(properties, community, '/'+path); this.config.isPageEnabledByState(properties, community, '/'+path);
obs this.sub = obs
//.pipe(tap((enabled) => console.log("aaa: "+enabled))) //.pipe(tap((enabled) => console.log("aaa: "+enabled)))
.pipe(filter(enabled => !enabled)) .pipe(filter(enabled => !enabled))
.subscribe(() => { .subscribe(() => {
@ -87,4 +88,11 @@ export class IsRouteEnabled implements CanActivate {
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean { canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
return this.check(route.data, route.queryParams['communityId'], state.url); return this.check(route.data, route.queryParams['communityId'], state.url);
} }
canDeactivate() {
if(this.sub) {
this.sub.unsubscribe();
}
return true;
}
} }