[Library | Trunk]: 1. Community Service refactor. 2. Subscribe service refactor. 3. Add service on role-verification

git-svn-id: https://svn.driver.research-infrastructures.eu/driver/dnet40/modules/uoa-services-library/trunk/ng-openaire-library/src/app@60453 d315682c-612b-4755-9ff5-7f18f6832af3
This commit is contained in:
k.triantafyllou 2021-02-19 17:50:34 +00:00
parent ce59d4e8bf
commit e8774312f5
11 changed files with 105 additions and 338 deletions

View File

@ -3,7 +3,7 @@ import {HttpClient, HttpHeaders} from "@angular/common/http";
import {CommunityInfo} from './communityInfo';
import {EnvProperties} from '../../utils/properties/env-properties';
import {map} from "rxjs/operators";
import {BehaviorSubject, from, Subscriber} from "rxjs";
import {BehaviorSubject, from, Observable, Subscriber} from "rxjs";
import {properties} from "../../../../environments/environment";
import {HelperFunctions} from "../../utils/HelperFunctions.class";
import {Stakeholder} from "../../monitor/entities/stakeholder";
@ -30,30 +30,6 @@ export class CommunityService {
}
}
// TODO Remove these functions
getCommunityByService(properties: EnvProperties, url: string) {
this.promise = new Promise<any>(resolve => {
this.sub = this.getCommunity(properties, url).subscribe(res => {
this.community.next(res);
resolve();
},
error => {
this.community.error(error);
resolve();
})
});
}
async getCommunityByStateAsync(properties: EnvProperties, url: string) {
if (!this.promise) {
this.getCommunityByService(properties, url);
}
await this.promise;
this.clearSubscriptions();
return this.community.getValue();
}
public getCommunityAsObservable() {
return this.community.asObservable();
}
@ -62,15 +38,6 @@ export class CommunityService {
this.community.next(community);
}
getCommunityByState(properties: EnvProperties, url: string) {
return from(this.getCommunityByStateAsync(properties, url));
}
getCommunity(properties: EnvProperties, url: string) {
return this.http.get((properties.useCache) ? (properties.cacheUrl + encodeURIComponent(url)) : url)
.pipe(map(res => this.parseCommunity(res)));
}
// TODO remove NEW from function names
getCommunityNew(communityId: string, refresh = false) {
if(!this.community.value || this.community.value.communityId !== communityId || refresh) {
@ -124,88 +91,6 @@ export class CommunityService {
/*.map(res => res.json())*/
}
async isCommunityManagerByStateAsync(properties: EnvProperties, url: string, manager: string) {
if (!this.promise) {
this.getCommunityByService(properties, url);
}
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)
//.map(res => <any> res.json())
.pipe(map(res => this.parseCommunity(res)))
.pipe(map(community => (community && community.type && community.type === 'community')));
}
/**
* @deprecated
*/
isSubscribedToCommunity(pid: string, email: string, url: string) {
return this.http.get(url + '/' + properties.adminToolsPortalType + '/' + 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;
}));
}
private parseCommunity(data: any): CommunityInfo {
const resData = Array.isArray(data) ? data[0] : data;
@ -261,4 +146,11 @@ export class CommunityService {
return this.checkIsUpload(community);
}
isRIType(community: string): Observable<boolean> {
return this.getCommunityNew(community).pipe(map(community => community.type === 'ri'));
}
isCommunityType(community: string): Observable<boolean> {
return this.getCommunityNew(community).pipe(map(community => community.type === 'community'));
}
}

View File

@ -18,58 +18,37 @@ import {UserManagementService} from "../../services/user-management.service";
import {properties} from "../../../../environments/environment";
@Injectable()
export class ConnectAdminLoginGuard implements CanActivate, CanLoad {
sub: Subscription = null;
export class ConnectAdminLoginGuard implements CanActivate {
constructor(private router: Router,
private communityService: CommunityService,
private propertiesService: EnvironmentSpecificService,
private userManagementService: UserManagementService) {
}
check(community: string, path: string): Observable<boolean> | boolean {
let errorCode = LoginErrorCodes.NOT_LOGIN;
let email = null;
const authorized = this.userManagementService.getUserInfo(false).pipe(take(1),map(user => {
if (user) {
email = user.email;
if (Session.isPortalAdministrator(user) || Session.isCommunityCurator(user) || Session.isManager('community', community, user)) {
return of(true);
} else {
errorCode = LoginErrorCodes.NOT_ADMIN;
return this.communityService.isCommunityManagerByState(properties, properties['communityAPI'] + community,
email).pipe(take(1));
}
} else {
return of(false);
const authorized = this.userManagementService.getUserInfo(false).pipe(take(1), map(user => {
if (user) {
if (Session.isPortalAdministrator(user) || Session.isCommunityCurator(user) || Session.isManager('community', community, user)) {
return of(true);
}
}), mergeMap( authorized => {
return authorized;
}));
//}));
this.sub = authorized.pipe(filter(authorized => !authorized)).subscribe(() => {
}
return of(false);
}), mergeMap(authorized => {
return authorized;
}));
authorized.pipe(filter(authorized => !authorized)).subscribe(() => {
this.router.navigate(['/user-info'], {
queryParams: {
'errorCode': errorCode,
'redirectUrl': path
}
})});
})
});
return authorized;
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
return this.check(route.queryParams['communityId'], state.url);
}
canLoad(route: Route, segments: UrlSegment[]): Observable<boolean> | Promise<boolean> | boolean {
const path = StringUtils.URLSegmentsToPath(segments) + document.location.search;
return this.check(ConnectHelper.getCommunityFromPath(path), path);
}
canDeactivate() {
if(this.sub) {
this.sub.unsubscribe();
}
return true;
}
}

View File

@ -20,7 +20,7 @@ export class ConnectCommunityGuard implements CanActivate {
}
check(community: string): Observable<boolean> | boolean {
return this.communityService.isCommunityTypeByState(properties, properties['communityAPI'] + community).pipe(take(1), tap(isCommunity => {
return this.communityService.isCommunityType(community).pipe(take(1), tap(isCommunity => {
if (!isCommunity) {
this.router.navigate(['errorcommunity']);
}

View File

@ -24,7 +24,7 @@ export class ConnectRIGuard implements CanActivate, CanLoad {
}
check(community: string): Observable<boolean> | boolean {
return this.communityService.isRITypeByState(properties, properties['communityAPI'] + community).pipe(tap(authorized => {
return this.communityService.isRIType(community).pipe(tap(authorized => {
if (!authorized) {
this.router.navigate(['errorcommunity']);
}

View File

@ -1,34 +1,45 @@
import {take, tap} from 'rxjs/operators';
import {filter, map, mergeMap, take} from 'rxjs/operators';
import {Injectable} from '@angular/core';
import {Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router';
import {Observable} from 'rxjs';
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from '@angular/router';
import {Observable, of} from 'rxjs';
import {LoginErrorCodes} from '../../login/utils/guardHelper.class';
import {SubscribeService} from "../../utils/subscribe/subscribe.service";
import {properties} from "../../../../environments/environment";
import {ConnectHelper} from "../connectHelper";
import {Session} from "../../login/utils/helper.class";
import {UserManagementService} from "../../services/user-management.service";
@Injectable()
export class ConnectSubscriberGuard implements CanActivate {
constructor(private router: Router,
private subscribeService: SubscribeService) {
private userManagementService: UserManagementService) {
}
check(community: string, path: string): Observable<boolean> {
let errorCode = LoginErrorCodes.NOT_SUBSCRIBER;
let communityDomain = ConnectHelper.getCommunityFromDomain(properties.domain);
if (communityDomain) {
community = communityDomain;
}
return this.subscribeService.isSubscribedToCommunity(properties, community).pipe(take(1), tap(subscribed =>{
if(!subscribed){
this.router.navigate(['/user-info'], {
queryParams: {
'errorCode': errorCode,
'redirectUrl': path
}
});
const authorized = this.userManagementService.getUserInfo(false).pipe(take(1), map(user => {
if (user) {
if (Session.isSubscribedTo('community', community, user)) {
return of(true);
}
}
return of(false);
}), mergeMap(authorized => {
return authorized;
}));
authorized.pipe(filter(authorized => !authorized)).subscribe(() => {
this.router.navigate(['/user-info'], {
queryParams: {
'errorCode': errorCode,
'redirectUrl': path
}
})
});
return authorized;
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {

View File

@ -86,7 +86,7 @@ export class SearchDataprovidersToDepositComponent {
public oldTotalResults: number = 0;
pagingLimit = 0;
properties:EnvProperties;
properties:EnvProperties = properties;
// @ViewChild (SearchPageComponent) searchPage : SearchPageComponent ;
@ -106,9 +106,6 @@ export class SearchDataprovidersToDepositComponent {
}
public ngOnInit() {
this.properties = properties;
this.depositLearnHowPage = this.properties.depositLearnHowPage;
this.baseUrl = this.properties.depositSearchPage;
this.pagingLimit = this.properties.pagingLimit;

View File

@ -1,67 +0,0 @@
import {Injectable} from '@angular/core';
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from '@angular/router';
import {Observable} from 'rxjs/Observable';
import {Session} from './utils/helper.class';
import {LoginErrorCodes} from './utils/guardHelper.class';
import {catchError, filter, map, mergeMap} from "rxjs/operators";
import {UserManagementService} from "../services/user-management.service";
import {UserRegistryService} from "../services/user-registry.service";
import {of} from "rxjs";
import {properties} from "../../../environments/environment";
import {ConnectHelper} from "../connect/connectHelper";
@Injectable()
export class VerificationGuard implements CanActivate {
constructor(private router: Router,
private userRegistryService: UserRegistryService,
private userManagementService: UserManagementService) {
}
check(path: string, id: string, type: string, entity: string): Observable<boolean> | boolean {
if (Session.isLoggedIn()) {
return this.userManagementService.getUserInfo(false).pipe(map(user => {
if(user) {
if(id) {
return this.userRegistryService.getInvitation(id).pipe(map(invitation => {
if(invitation.type !== type || invitation.entity !== entity) {
this.router.navigate(['/error'], {queryParams: {'page': path}});
return false;
} else {
return true;
}
}), catchError(error => {
if(error.status === 404) {
this.router.navigate(['/error'], {queryParams: {'page': path}});
} else {
this.router.navigate(['/user-info'], {queryParams: {'errorCode': LoginErrorCodes.NOT_AUTHORIZED, 'redirectUrl': path}});
}
return of(false);
}));
} else {
this.router.navigate(['/error'], {queryParams: {'page': path}});
return of(false);
}
} else {
this.router.navigate(['/user-info'], {queryParams: {'errorCode': LoginErrorCodes.NOT_LOGIN, 'redirectUrl': path}});
return of(false);
}
}), mergeMap(authorized => {
return authorized;
}));
} else {
this.router.navigate(['/user-info'], {queryParams: {'errorCode': LoginErrorCodes.NOT_LOGIN,'redirectUrl': path}});
return false;
}
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
if(properties.dashboard === "connect" && properties.environment === 'development') {
let communityId = ConnectHelper.getCommunityFromDomain(properties.domain);
communityId = (communityId)?communityId:route.queryParams['communityId'];
return this.check(state.url, route.params.id, 'community', communityId);
} else {
return false;
}
}
}

View File

@ -7,13 +7,14 @@ import {LoginErrorCodes} from "../login/utils/guardHelper.class";
import {Subscriber} from "rxjs";
import {FormBuilder, FormControl, Validators} from "@angular/forms";
import {AlertModal} from "../utils/modal/alert";
import {properties} from "../../../environments/environment";
@Component({
selector: 'role-verification',
template: `
<modal-alert #managerModal>
<div>
You have been invited to join <span class="uk-text-bold">{{name}}</span> Monitor Dashboard as a manager.
You have been invited to join <span class="uk-text-bold">{{name}}</span> {{(service === 'monitor'?'Monitor':'Research Community')}} Dashboard as a manager.
<span class="portal-color">Fill</span> in the <span class="portal-color">verification code</span>, sent to your
email, to accept the invitation request.
</div>
@ -22,7 +23,7 @@ import {AlertModal} from "../utils/modal/alert";
<div *ngIf="error" class="uk-text-danger uk-margin-remove uk-width-1-1">{{error}}</div>
</div>
</div>
<div *ngIf="loading" class="uk-margin-medium-top">
<div *ngIf="loading" class="uk-margin-medium-top uk-flex uk-flex-center">
<loading></loading>
</div>
<div class="uk-margin-medium-top uk-flex uk-flex-right">
@ -34,7 +35,7 @@ import {AlertModal} from "../utils/modal/alert";
</button>
</div>
</modal-alert>
<modal-alert #memberModal>
<modal-alert *ngIf="service !== 'connect'" #memberModal>
<div *ngIf="!isMember">
<div>
You have been invited to join <span class="uk-text-bold">{{name}}</span> Monitor Dashboard as a member.
@ -86,6 +87,8 @@ export class RoleVerificationComponent implements OnInit, OnDestroy {
public type: string;
@Input()
public name: string;
@Input()
public service: "connect" | "monitor" = "monitor";
public user: User;
public verification: any;
public code: FormControl;
@ -116,8 +119,10 @@ export class RoleVerificationComponent implements OnInit, OnDestroy {
if (this.user.email === this.verification.email && this.id === this.verification.entity && this.type === this.verification.type) {
if (this.verification.verificationType === 'manager') {
this.openManagerModal();
} else if (this.verification.verificationType === 'member') {
} else if (this.verification.verificationType === 'member' && this.service === "monitor") {
this.openMemberModal();
} else {
this.openErrorModal();
}
} else {
this.openErrorModal();
@ -177,7 +182,11 @@ export class RoleVerificationComponent implements OnInit, OnDestroy {
this.managerModal.cancel();
this.error = null;
this.userManagementService.updateUserInfo(() => {
this.router.navigate(['/admin/' + this.verification.entity]);
if(this.service === "monitor") {
this.router.navigate(['/admin/' + this.verification.entity]);
} else {
window.location.href = 'https://' + (properties.environment !== 'production'?'beta.':'') + 'admin.connect.openaire.eu/' + this.verification.entity;
}
});
}, error => {
this.loading = false;

View File

@ -18,8 +18,8 @@ export class UserRegistryService {
CustomOptions.registryOptions()).pipe(map((response: any) => response.response));
}
public getSubscribersCount(type: string, id: string): Observable<any> {
return this.http.get(properties.registryUrl + encodeURIComponent(type) + '/' + encodeURIComponent(id) + '/subscribers/count');
public getMembersCount(type: string, id: string): Observable<any> {
return this.http.get(properties.registryUrl + encodeURIComponent(type) + '/' + encodeURIComponent(id) + '/members/count');
}
public subscribeTo(type: string, id: string): Observable<any> {

View File

@ -1,4 +1,4 @@
import {Component, Input} from "@angular/core";
import {Component, Input, OnInit} from "@angular/core";
@Component({
selector: 'loading',
@ -11,21 +11,33 @@ import {Component, Input} from "@angular/core";
</div>
</ng-template>
<ng-template #loading>
<div [class]="'uk-flex uk-flex-center '+(top_margin ? 'uk-margin-small-top' : '')">
<span class="portal-color uk-icon uk-spinner">
<div [class]="'uk-flex uk-flex-center '+(top_margin ? 'uk-margin-small-top' : '')" [ngStyle]="style">
<span class="uk-icon uk-spinner" [ngClass]="color">
<svg width="60" height="60" viewBox="0 0 30 30" xmlns="http://www.w3.org/2000/svg" data-svg="spinner"><circle
fill="none" stroke="#000" cx="15" cy="15" r="14" style="stroke-width: 2px;"></circle></svg>
</span>
</div>
</ng-template>`
})
export class LoadingComponent {
/**
* Possible values '': blue, 'success': green, 'warning': orange and 'danger': red
*/
@Input() color: 'success' | 'warning' | 'danger' = null;
export class LoadingComponent implements OnInit{
@Input() color: string = 'portal-color';
@Input() full: boolean = false;
@Input() top_margin: boolean = true;
@Input() size: "small" | "medium" | "large" = "large";
public style;
constructor() {
}
ngOnInit() {
let size = 1;
if(this.size === 'medium') {
size = 2;
} else if(this.size === "large") {
size = 3;
}
this.style = {
width: size*20 + 'px',
height: size*20 + 'px'
};
}
}

View File

@ -1,90 +1,24 @@
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {map, tap} from "rxjs/operators";
import {CustomOptions} from "../../services/servicesUtils/customOptions.class";
import {EnvProperties} from "../properties/env-properties";
import {BehaviorSubject, Observable, Subscriber} from "rxjs";
import {BehaviorSubject, Observable} from "rxjs";
@Injectable()
export class SubscribeService {
private isSubscribedSubject: BehaviorSubject<boolean> = new BehaviorSubject(false);
constructor(private http: HttpClient) {}
sub;
ngOnDestroy() {
this.clearSubscriptions();
private loading: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
private members: BehaviorSubject<number> = new BehaviorSubject<number>(0);
public setLoading(loading: boolean) {
this.loading.next(loading);
}
clearSubscriptions(){
if (this.sub instanceof Subscriber) {
this.sub.unsubscribe();
}
public setMembers(members: number) {
this.members.next(members);
}
public initIsSubscribedToCommunity(properties: EnvProperties, pid: string) {
let url = properties.adminToolsAPIURL + "/community/" + pid + "/is-subscriber/";
this.sub = this.http.get<boolean>(url, CustomOptions.getAuthOptionsWithBody()).subscribe((isSubscribed) => {
this.isSubscribedSubject.next(isSubscribed);
}, error => {
this.isSubscribedSubject.error(error);
});
public getLoading(): Observable<any> {
return this.loading.asObservable();
}
public get isSubscribed(): Observable<boolean> {
return this.isSubscribedSubject.asObservable();
}
getCommunitySubscribers(properties: EnvProperties, pid: string) {
let url = properties.adminToolsAPIURL + "/" + properties.adminToolsPortalType + "/" + pid + "/subscribers";
return this.http.get<any>((properties.useCache) ? (properties.cacheUrl + encodeURIComponent(url)) : url);
}
getNumberOfCommunitySubscribers(properties: EnvProperties, pid: string) {
let url = properties.adminToolsAPIURL + "/"+ properties.adminToolsPortalType +"/" + pid + "/subscribers/count";
return this.http.get<any>((properties.useCache) ? (properties.cacheUrl + encodeURIComponent(url)) : url);
}
isSubscribedToCommunity(properties: EnvProperties, pid: string) {
let url = properties.adminToolsAPIURL + "/community/" + pid + "/is-subscriber/";
return this.http.get<boolean>(url, CustomOptions.getAuthOptionsWithBody())
.pipe(map(res => {
// if (res['status'] && res['status'] != 200) {
// return null;
// }
// if (res['subscribers'] && res['subscribers'] != null) {
//
// for (var i = 0; i < res['subscribers'].length; i++) {
// if (res['subscribers'][i] != null && res['subscribers'][i].email == email) {
// return true;
// }
// }
// }
// return false;
return res;
}));
}
subscribeToCommunity(properties: EnvProperties, pid: string) {
return this.http.post<any>(properties.adminToolsAPIURL + "/"+ properties.adminToolsPortalType +"/" + pid + "/subscriber", {}, CustomOptions.getAuthOptionsWithBody())
.pipe(tap(isSubscribed => {
this.isSubscribedSubject.next(isSubscribed);}));
}
unSubscribeToCommunity(properties: EnvProperties, pid: string) {
return this.http.post<any>(properties.adminToolsAPIURL + "/"+ properties.adminToolsPortalType+"/" + pid + "/subscriber/delete", {}, CustomOptions.getAuthOptionsWithBody())
.pipe(tap(unSubscribed => {
this.isSubscribedSubject.next(!unSubscribed);}));
}
subscribeToCommunityByEmail(properties: EnvProperties, pid: string, email: string) {
let subscriber = {"email": email};
return this.http.post<any>(properties.adminToolsAPIURL + "/"+ properties.adminToolsPortalType+"/" + pid + "/subscribers", JSON.stringify(subscriber), CustomOptions.getAuthOptionsWithBody());
}
unSubscribeToCommunityByEmail(properties: EnvProperties, pid: string, email: string) {
return this.http.post<any>(properties.adminToolsAPIURL + "/"+ properties.adminToolsPortalType+"/" + pid + "/subscribers/delete", JSON.stringify([email]), CustomOptions.getAuthOptionsWithBody());
}
getCommunitiesSubscribedTo(properties: EnvProperties/*, email: string*/) {
let url = properties.adminToolsAPIURL + "/subscriber/communities";//?email=" + email;
return this.http.get<any>(url, CustomOptions.getAuthOptionsWithBody());
public getMembers(): Observable<any> {
return this.members.asObservable();
}
}