From 98c98e662522726f9a1e62c083bbd194ddf893e0 Mon Sep 17 00:00:00 2001 From: "k.triantafyllou" Date: Fri, 13 Sep 2019 07:01:19 +0000 Subject: [PATCH] [Library]: Add user management service and change all session methods with new ones. git-svn-id: https://svn.driver.research-infrastructures.eu/driver/dnet40/modules/uoa-services-library/trunk/ng-openaire-library/src/app@57058 d315682c-612b-4755-9ff5-7f18f6832af3 --- .../claimContextSearchForm.component.ts | 330 ++++----- .../displayClaims/displayClaims.component.ts | 130 ++-- claims/claimsAdmin/claimsAdmin.component.ts | 13 +- .../claimsByToken/claimsByToken.component.ts | 637 ++++++++++-------- .../insertClaim/insertClaim.component.ts | 209 +++--- claims/myClaims/myClaims.component.ts | 14 +- .../connectAdminLoginGuard.guard.ts | 60 +- .../communityGuard/connectSubscriber.guard.ts | 52 +- connect/communityGuard/isCommunityOrAdmin.ts | 40 +- .../mailPrefs.component.ts | 378 ++++++----- login/adminLoginGuard.guard.ts | 32 +- login/claimsCuratorGuard.guard.ts | 34 +- login/loginGuard.guard.ts | 23 +- login/user.component.html | 4 +- login/user.component.ts | 20 +- login/userMini.component.ts | 13 +- login/utils/helper.class.ts | 30 +- sharedComponents/navigationBar.component.html | 4 +- sharedComponents/navigationBar.component.ts | 197 +++--- utils/properties/env-properties.ts | 1 + 20 files changed, 1221 insertions(+), 1000 deletions(-) diff --git a/claims/claim-utils/claimContextSearchForm.component.ts b/claims/claim-utils/claimContextSearchForm.component.ts index 9399fb2e..b3100615 100644 --- a/claims/claim-utils/claimContextSearchForm.component.ts +++ b/claims/claim-utils/claimContextSearchForm.component.ts @@ -1,10 +1,11 @@ import {Component, Input} from '@angular/core'; import {Router} from '@angular/router'; import {ContextsService} from './service/contexts.service'; -import {ClaimContext, ClaimEntity} from './claimHelper.class'; +import {ClaimEntity} from './claimHelper.class'; import {Session} from '../../login/utils/helper.class'; import {LoginErrorCodes} from '../../login/utils/guardHelper.class'; import {EnvProperties} from '../../utils/properties/env-properties'; +import {UserManagementService} from "../../services/user-management.service"; declare var UIkit: any; @@ -14,7 +15,7 @@ declare var UIkit: any; }) export class ClaimContextSearchFormComponent { - @Input() public results:ClaimEntity[]; + @Input() public results: ClaimEntity[]; @Input() public sources; @Input() public properties: EnvProperties; @Input() communityId: string = null; @@ -44,7 +45,9 @@ export class ClaimContextSearchFormComponent { this.getCommunities(); } - constructor(private _contextService: ContextsService, private router: Router) { + constructor(private _contextService: ContextsService, + private router: Router, + private userManagementService: UserManagementService) { } @@ -95,7 +98,7 @@ export class ClaimContextSearchFormComponent { // }); // return; // } - const entity: ClaimEntity = new ClaimEntity() ; + const entity: ClaimEntity = new ClaimEntity(); entity.type = "community"; entity.context = {community: community, category: category, concept: concept}; @@ -109,147 +112,152 @@ export class ClaimContextSearchFormComponent { } getCommunities() { - if (!Session.isLoggedIn()) { - this.saveStateAndRedirectLogin(); + this.userManagementService.isLoggedIn(this.properties.userInfoUrl).subscribe(isLoggedIn => { + if (!isLoggedIn) { + this.saveStateAndRedirectLogin(); - } else { - this.loading = true; - this._contextService.getPublicCommunities(this.properties.contextsAPI).subscribe( - data => { - this.communities = data; - if (this.communities.length > 0) { - this.communities.sort((n1, n2) => n1.label > n2.label); - } - this.loading = false; - if (this.communityId != null) { - //preselect community - this.selectedCommunityId = this.communityId; - for (let i = 0; i < this.communities.length; i++) { - if (this.communities[i].id == this.selectedCommunityId) { - this.selectedCommunityLabel = this.communities[i].label; - break; - } + } else { + this.loading = true; + this._contextService.getPublicCommunities(this.properties.contextsAPI).subscribe( + data => { + this.communities = data; + if (this.communities.length > 0) { + this.communities.sort((n1, n2) => n1.label > n2.label); } - this.addNewContext(this.selectedCommunityLabel, null, { - 'id': this.selectedCommunityId, - 'label': this.selectedCommunityLabel - }, false) + this.loading = false; + if (this.communityId != null) { + //preselect community + this.selectedCommunityId = this.communityId; + for (let i = 0; i < this.communities.length; i++) { + if (this.communities[i].id == this.selectedCommunityId) { + this.selectedCommunityLabel = this.communities[i].label; + break; + } + } + this.addNewContext(this.selectedCommunityLabel, null, { + 'id': this.selectedCommunityId, + 'label': this.selectedCommunityLabel + }, false) + } + }, + err => { + //console.log(err); + ClaimContextSearchFormComponent.handleError("Error getting communities", err); + this.loading = false; + this.error = true; } - }, - err => { - //console.log(err); - ClaimContextSearchFormComponent.handleError("Error getting communities", err); - this.loading = false; - this.error = true; - } - ); - } + ); + } + }); } getCategories() { this.loading = true; // this.categories=[]; if (this.selectedCommunityId != '0') { - if (!Session.isLoggedIn()) { - this.saveStateAndRedirectLogin(); + this.userManagementService.isLoggedIn(this.properties.userInfoUrl).subscribe(isLoggedIn => { + if (!isLoggedIn) { + this.saveStateAndRedirectLogin(); - - } else { - if (this.categories[this.selectedCommunityId]) { - this.loading = false; - return; - } - this._contextService.getCategories(this.selectedCommunityId, this.properties.contextsAPI).subscribe( - data => { - - this.categories[this.selectedCommunityId] = data; - this.concepts = []; - if (this.query !== "") { - const event = {value: ""}; - event.value = this.query; - } - this.loading = false; - }, - err => { - //console.log(err); - ClaimContextSearchFormComponent.handleError("Error getting categories for community with id: " + this.selectedCommunityId, err); + } else { + if (this.categories[this.selectedCommunityId]) { this.loading = false; + return; } - ); - } + this._contextService.getCategories(this.selectedCommunityId, this.properties.contextsAPI).subscribe( + data => { + + this.categories[this.selectedCommunityId] = data; + this.concepts = []; + if (this.query !== "") { + const event = {value: ""}; + event.value = this.query; + } + this.loading = false; + }, + err => { + //console.log(err); + ClaimContextSearchFormComponent.handleError("Error getting categories for community with id: " + this.selectedCommunityId, err); + this.loading = false; + } + ); + } + }); } } -/* - getConcepts() { - this.loading = true; - if (this.selectedCategoryId != '0') { - if (!Session.isLoggedIn()) { - this.saveStateAndRedirectLogin(); + + /* + getConcepts() { + this.loading = true; + if (this.selectedCategoryId != '0') { + if (!Session.isLoggedIn()) { + this.saveStateAndRedirectLogin(); + } else { + this.concepts = []; + + this._contextService.getConcepts(this.selectedCategoryId, "", true, this.properties.contextsAPI).subscribe( + data => { + + this.concepts = data; + for (var i = 0; i < data.length; i++) { + if (data[i].hasSubConcept == true) { + this.getSubConcepts(data[i].id); + } + } + this.addCommunityInConcepts(); + if (this.query !== "") { + var event = {value: ""}; + event.value = this.query; + // this.filter(event); + } + this.loading = false; + }, + err => { + //console.log(err); + this.handleError("Error getting concepts for category with id: " + this.selectedCategoryId, err); + this.loading = false; + } + ); + } } else { this.concepts = []; + this.loading = false; + } + }*/ - this._contextService.getConcepts(this.selectedCategoryId, "", true, this.properties.contextsAPI).subscribe( - data => { - - this.concepts = data; - for (var i = 0; i < data.length; i++) { - if (data[i].hasSubConcept == true) { - this.getSubConcepts(data[i].id); + /* + getSubConcepts(conceptId) { + this.loading = true; + if (this.selectedCategoryId != '0') { + if (!Session.isLoggedIn()) { + this.saveStateAndRedirectLogin(); + } else { + this._contextService.getSubConcepts(conceptId, "", true, this.properties.contextsAPI).subscribe( + data => { + for (var i = 0; i < data.length; i++) { + this.concepts.push(data[i]); } - } - this.addCommunityInConcepts(); - if (this.query !== "") { - var event = {value: ""}; - event.value = this.query; - // this.filter(event); - } - this.loading = false; - }, - err => { - //console.log(err); - this.handleError("Error getting concepts for category with id: " + this.selectedCategoryId, err); - this.loading = false; - } - ); - } - } else { - this.concepts = []; - this.loading = false; - } - }*/ -/* - getSubConcepts(conceptId) { - this.loading = true; - if (this.selectedCategoryId != '0') { - if (!Session.isLoggedIn()) { - this.saveStateAndRedirectLogin(); - } else { - this._contextService.getSubConcepts(conceptId, "", true, this.properties.contextsAPI).subscribe( - data => { - for (var i = 0; i < data.length; i++) { - this.concepts.push(data[i]); - } - if (this.query !== "") { - var event = {value: ""}; - event.value = this.query; - // this.filter(event); + if (this.query !== "") { + var event = {value: ""}; + event.value = this.query; + // this.filter(event); + } + this.loading = false; + }, + err => { + //console.log(err); + this.handleError("Error getting subconcepts for concept with id: " + conceptId, err); + this.loading = false; } - this.loading = false; - }, - err => { - //console.log(err); - this.handleError("Error getting subconcepts for concept with id: " + conceptId, err); - this.loading = false; - } - ); + ); + } + } else { + this.concepts = []; + this.loading = false; } - } else { - this.concepts = []; - this.loading = false; - } - }*/ + }*/ displaySubcategory(id) { if (this.conceptsClassDisplay[id] != null) { @@ -261,38 +269,40 @@ export class ClaimContextSearchFormComponent { } browseConcepts(categoryId) { - if (!Session.isLoggedIn()) { - this.saveStateAndRedirectLogin(); - } else { - if (this.conceptsClass[categoryId] != null) { - this.conceptsClassDisplay[categoryId] = !this.conceptsClassDisplay[categoryId]; - return; - } else { - this.conceptsClassDisplay[categoryId] = true; - } - this.conceptsClass[categoryId] = []; - this.conceptsCategoryLoading[categoryId] = true; - this._contextService.getConcepts(categoryId, "", false, this.properties.contextsAPI).subscribe( - data => { - // var concepts = data; - this.conceptsClass[categoryId] = []; - for (let i = 0; i < data.length; i++) { - if (data[i].hasSubConcept == true) { - this.browseSubConcepts(categoryId, data[i].id); - } else { - this.conceptsClass[categoryId].push(data[i]); - } - } - this.conceptsCategoryLoading[categoryId] = false; - }, - err => { - //console.log(err); - ClaimContextSearchFormComponent.handleError("Error getting concepts for category with id: " + this.selectedCategoryId, err); - this.conceptsCategoryLoading[categoryId] = false; - } - ); - } + this.userManagementService.isLoggedIn(this.properties.userInfoUrl).subscribe(isLoggedIn => { + if (!isLoggedIn) { + this.saveStateAndRedirectLogin(); + } else { + if (this.conceptsClass[categoryId] != null) { + this.conceptsClassDisplay[categoryId] = !this.conceptsClassDisplay[categoryId]; + return; + } else { + this.conceptsClassDisplay[categoryId] = true; + } + this.conceptsClass[categoryId] = []; + this.conceptsCategoryLoading[categoryId] = true; + this._contextService.getConcepts(categoryId, "", false, this.properties.contextsAPI).subscribe( + data => { + // var concepts = data; + this.conceptsClass[categoryId] = []; + for (let i = 0; i < data.length; i++) { + if (data[i].hasSubConcept == true) { + this.browseSubConcepts(categoryId, data[i].id); + } else { + this.conceptsClass[categoryId].push(data[i]); + } + } + this.conceptsCategoryLoading[categoryId] = false; + }, + err => { + //console.log(err); + ClaimContextSearchFormComponent.handleError("Error getting concepts for category with id: " + this.selectedCategoryId, err); + this.conceptsCategoryLoading[categoryId] = false; + } + ); + } + }); } browseSubConcepts(categoryId, conceptId) { @@ -340,12 +350,12 @@ export class ClaimContextSearchFormComponent { // } // this.getConcepts(); // } -/* addCommunityInConcepts() { - this.concepts.push({"id": this.selectedCommunityId, "label": this.selectedCommunityLabel}); - // if(this.autocomplete){ - // this.autocomplete.updateList(this.concepts); - // } - }*/ + /* addCommunityInConcepts() { + this.concepts.push({"id": this.selectedCommunityId, "label": this.selectedCommunityLabel}); + // if(this.autocomplete){ + // this.autocomplete.updateList(this.concepts); + // } + }*/ saveStateAndRedirectLogin() { // if(this.projects != null){ diff --git a/claims/claim-utils/displayClaims/displayClaims.component.ts b/claims/claim-utils/displayClaims/displayClaims.component.ts index 14138343..1dc8c7e0 100644 --- a/claims/claim-utils/displayClaims/displayClaims.component.ts +++ b/claims/claim-utils/displayClaims/displayClaims.component.ts @@ -2,11 +2,11 @@ import {Component, Input, ViewChild} from '@angular/core'; import {Location} from '@angular/common'; import {ActivatedRoute, Router} from '@angular/router'; import {Subject} from 'rxjs'; -import { debounceTime, distinctUntilChanged } from 'rxjs/operators'; +import {debounceTime, distinctUntilChanged} from 'rxjs/operators'; import {ClaimsService} from '../service/claims.service'; import {ModalLoading} from '../../../utils/modal/loading.component'; import {AlertModal} from '../../../utils/modal/alert'; -import {Session} from '../../../login/utils/helper.class'; +import {Session, User} from '../../../login/utils/helper.class'; import {EnvProperties} from '../../../utils/properties/env-properties'; import {LoginErrorCodes} from '../../../login/utils/guardHelper.class'; import {SEOService} from '../../../sharedComponents/SEO/SEO.service'; @@ -16,6 +16,7 @@ import {Dates} from "../../../utils/string-utils.class"; import {HelperService} from "../../../utils/helper/helper.service"; import {Meta, Title} from "@angular/platform-browser"; import {PiwikService} from "../../../utils/piwik/piwik.service"; +import {UserManagementService} from "../../../services/user-management.service"; @Component({ @@ -27,7 +28,7 @@ import {PiwikService} from "../../../utils/piwik/piwik.service"; export class DisplayClaimsComponent { @Input() piwikSiteId = null; @Input() title: string = ""; - piwiksub:any; + piwiksub: any; properties: EnvProperties; public searchTermStream = new Subject(); @@ -37,15 +38,15 @@ export class DisplayClaimsComponent { @Input() showUserEmail: boolean = true; @Input() myClaims: boolean = false; @Input() isAdmin: boolean = false; - page: number=1; - size: number=10; + page: number = 1; + size: number = 10; sizes = [10, 20, 30, 50]; keyword: string; // the keyword string to give to the request as parameter inputkeyword: string; // the string written in the input field (keyword=inputkeyword when its length is bigger than 3 and the user stops typing) types = ["All", "Project", "Context", "Result", "User"]; @Input() fetchBy: string; @Input() fetchId: string; - + @Input() user: User; resultsNum: number; claims: ClaimDBRecord[]; @Input() externalPortalUrl: string = null; @@ -83,8 +84,8 @@ export class DisplayClaimsComponent { public pageContents = null; constructor(private _claimService: ClaimsService, private route: ActivatedRoute, private _router: Router, private location: Location, - private _meta: Meta, private _title: Title, private _piwikService:PiwikService, - private seoService: SEOService, private indexInfoService:IndexInfoService, private helper: HelperService) { + private _meta: Meta, private _title: Title, private _piwikService: PiwikService, + private seoService: SEOService, private indexInfoService: IndexInfoService, private helper: HelperService) { } ngOnInit() { @@ -98,7 +99,7 @@ export class DisplayClaimsComponent { this.updateDescription(description); this.updateUrl(this.url); - if(this.properties.enablePiwikTrack && (typeof document !== 'undefined')){ + if (this.properties.enablePiwikTrack && (typeof document !== 'undefined')) { this.piwiksub = this._piwikService.trackView(this.properties, this.title, this.piwikSiteId).subscribe(); } @@ -113,7 +114,7 @@ export class DisplayClaimsComponent { if (this.myClaims) { this.fetchBy = "User"; - this.fetchId = Session.getUserEmail(); + this.fetchId = this.user.email; } else { this.fetchBy = (this.fetchBy) ? this.fetchBy : params['fetchBy']; @@ -134,7 +135,7 @@ export class DisplayClaimsComponent { this.setSortby(params['sort']); this.getClaims(); this.searchTermStream - .pipe(debounceTime(300),distinctUntilChanged()) + .pipe(debounceTime(300), distinctUntilChanged()) .subscribe((term: string) => { this.keyword = term; this.page = 1; @@ -149,14 +150,14 @@ export class DisplayClaimsComponent { ngOnDestroy() { this.sub.unsubscribe(); - if(this.piwiksub){ + if (this.piwiksub) { this.piwiksub.unsubscribe(); } //this.searchTermStreamSub.unsubscribe(); } getClaims() { - if (!Session.isLoggedIn()) { + if (!this.user) { this.userValidMessage = "User session has expired. Please login again."; this._router.navigate(['/user-info'], { queryParams: { @@ -277,30 +278,31 @@ export class DisplayClaimsComponent { this.location.go(location.pathname, this.getParametersString()); this.getClaims(); } -/* - getParameters() { - var params = {} - if (this.myClaims) { - params = { - page: this.page, - size: this.size, - types: this.entityTypes, - keyword: this.keyword, - sort: this.getSortby() - }; - } else { - params = { - page: this.page, - size: this.size, - types: this.entityTypes, - fetchBy: this.fetchBy, - fetchId: this.fetchId, - keyword: this.keyword, - sort: this.getSortby() - }; - } - return params; - }*/ + + /* + getParameters() { + var params = {} + if (this.myClaims) { + params = { + page: this.page, + size: this.size, + types: this.entityTypes, + keyword: this.keyword, + sort: this.getSortby() + }; + } else { + params = { + page: this.page, + size: this.size, + types: this.entityTypes, + fetchBy: this.fetchBy, + fetchId: this.fetchId, + keyword: this.keyword, + sort: this.getSortby() + }; + } + return params; + }*/ getParametersString() { let params = ''; @@ -330,7 +332,6 @@ export class DisplayClaimsComponent { } - changeOrderby(sortby: string) { if (sortby == this.sortby) { this.descending = !this.descending; @@ -497,7 +498,7 @@ export class DisplayClaimsComponent { } else { this.alert.cancelButton = true; this.alert.okButton = true; - this.alert.alertTitle ="";// "Delete " + this.selected.length + " links(s)"; + this.alert.alertTitle = "";// "Delete " + this.selected.length + " links(s)"; this.alert.okButtonLeft = false; // this.alert.message = this.selected.length + " links will be deleted. Do you want to proceed? "; this.alert.okButtonText = "Delete"; @@ -524,7 +525,7 @@ export class DisplayClaimsComponent { } batchDeleteById(ids: string[]) { - if (!Session.isLoggedIn()) { + if (!this.user) { this.userValidMessage = "User session has expired. Please login again."; this._router.navigate(['/user-info'], { queryParams: { @@ -565,8 +566,8 @@ export class DisplayClaimsComponent { this.deleteMessage = this.deleteMessage + '
' + res.notFoundIds.length + ' link(s) couldn\'t be deleted.
'; } let goToPage = this.page; - if(this.totalPages(this.resultsNum)< this.page && this.page>0){ - goToPage = this.page -1; + if (this.totalPages(this.resultsNum) < this.page && this.page > 0) { + goToPage = this.page - 1; } this.goTo(goToPage); }, err => { @@ -584,44 +585,47 @@ export class DisplayClaimsComponent { this.goTo(page); } - isClaimAvailable(claim:ClaimDBRecord): boolean { - //claim.target.collectedFrom == "infrastruct_::openaire" && - let lastUpdateDate = new Date( (this.lastIndexDate != null)?this.lastIndexDate:this.properties.lastIndexUpdate); + isClaimAvailable(claim: ClaimDBRecord): boolean { + //claim.target.collectedFrom == "infrastruct_::openaire" && + let lastUpdateDate = new Date((this.lastIndexDate != null) ? this.lastIndexDate : this.properties.lastIndexUpdate); let lastUpdateDateStr = Dates.getDateToString(lastUpdateDate); - let claimDate = new Date( claim.date); + let claimDate = new Date(claim.date); let claimDateStr = Dates.getDateToString(claimDate); - if (claimDateStr< lastUpdateDateStr) { + if (claimDateStr < lastUpdateDateStr) { return true; } else { - if(claim.target.collectedFrom != "infrastruct_::openaire" && claim.indexed){ - // check if direct index succeded - return true + if (claim.target.collectedFrom != "infrastruct_::openaire" && claim.indexed) { + // check if direct index succeded + return true } } return false; } + totalPages(totalResults: number): number { - let totalPages:any = totalResults/(this.size); - if(!(Number.isInteger(totalPages))) { + let totalPages: any = totalResults / (this.size); + if (!(Number.isInteger(totalPages))) { totalPages = (parseInt(totalPages, 10) + 1); } return totalPages; } - private updateDescription(description:string) { - this._meta.updateTag({content:description},"name='description'"); - this._meta.updateTag({content:description},"property='og:description'"); + private updateDescription(description: string) { + this._meta.updateTag({content: description}, "name='description'"); + this._meta.updateTag({content: description}, "property='og:description'"); } - private updateTitle(title:string) { - var _prefix =""; - if(!this.communityId) { - _prefix ="OpenAIRE | "; + + private updateTitle(title: string) { + var _prefix = ""; + if (!this.communityId) { + _prefix = "OpenAIRE | "; } - var _title = _prefix + ((title.length> 50 ) ?title.substring(0,50):title); + var _title = _prefix + ((title.length > 50) ? title.substring(0, 50) : title); this._title.setTitle(_title); - this._meta.updateTag({content:_title},"property='og:title'"); + this._meta.updateTag({content: _title}, "property='og:title'"); } - private updateUrl(url:string) { - this._meta.updateTag({content:url},"property='og:url'"); + + private updateUrl(url: string) { + this._meta.updateTag({content: url}, "property='og:url'"); } } diff --git a/claims/claimsAdmin/claimsAdmin.component.ts b/claims/claimsAdmin/claimsAdmin.component.ts index 1a95397f..b521212e 100644 --- a/claims/claimsAdmin/claimsAdmin.component.ts +++ b/claims/claimsAdmin/claimsAdmin.component.ts @@ -1,5 +1,7 @@ import {Component, Input} from '@angular/core'; import {Title, Meta} from '@angular/platform-browser'; +import {User} from "../../login/utils/helper.class"; +import {UserManagementService} from "../../services/user-management.service"; @Component({ @@ -18,7 +20,7 @@ import {Title, Meta} from '@angular/platform-browser'; Claim more links? Claim more links? - @@ -35,7 +37,11 @@ export class ClaimsAdminComponent { @Input() isConnect:boolean = false; @Input() externalPortalUrl:string; @Input() claimsInfoURL:string; - constructor ( private _meta: Meta, private _title: Title) { + @Input() userInfoURL: string; + public user: User = null; + + constructor ( private _meta: Meta, private _title: Title, + private userManagementService: UserManagementService) { var titleConnect = "OpenAIRE Connect | Manage links "; var title = "OpenAIRE | Manage links "; @@ -48,5 +54,8 @@ export class ClaimsAdminComponent { } ngOnInit() { + this.userManagementService.getUserInfo(this.userInfoURL).subscribe(user => { + this.user = user; + }); } } diff --git a/claims/claimsByToken/claimsByToken.component.ts b/claims/claimsByToken/claimsByToken.component.ts index 9c477d6b..3768f8f1 100644 --- a/claims/claimsByToken/claimsByToken.component.ts +++ b/claims/claimsByToken/claimsByToken.component.ts @@ -1,46 +1,44 @@ -import {Component, ViewChild, ViewChildren, QueryList, Input, ViewEncapsulation} from '@angular/core'; -import {Location} from '@angular/common'; -import {ActivatedRoute, Params, Router} from '@angular/router'; -import {Title, Meta} from '@angular/platform-browser'; +import {Component, QueryList, ViewChild, ViewChildren, ViewEncapsulation} from '@angular/core'; +import {ActivatedRoute, Router} from '@angular/router'; +import {Meta, Title} from '@angular/platform-browser'; -import {DataTableDirective} from 'angular-datatables'; -import {Observable, Subject } from 'rxjs'; +import {DataTableDirective} from 'angular-datatables'; +import {Subject} from 'rxjs'; -import{EnvProperties} from '../../utils/properties/env-properties'; -import {ErrorCodes} from '../../utils/properties/errorCodes'; -import {ErrorMessagesComponent} from '../../utils/errorMessages.component'; +import {EnvProperties} from '../../utils/properties/env-properties'; +import {ErrorCodes} from '../../utils/properties/errorCodes'; +import {ErrorMessagesComponent} from '../../utils/errorMessages.component'; -import {ClaimsDatatablePipe} from '../../utils/pipes/claimsDatatable.pipe'; +import {RouterHelper} from '../../utils/routerHelper.class'; -import {RouterHelper} from '../../utils/routerHelper.class'; +import {ModalSelect} from '../../utils/modal/selectModal.component'; +import {ModalLoading} from '../../utils/modal/loading.component'; -import {ModalSelect} from '../../utils/modal/selectModal.component'; -import {ModalLoading} from '../../utils/modal/loading.component'; +import {ClaimsByTokenService} from './claimsByToken.service'; -import {ClaimsByTokenService} from './claimsByToken.service'; - -import {Session} from '../../login/utils/helper.class'; -import {LoginErrorCodes} from '../../login/utils/guardHelper.class'; +import {Session} from '../../login/utils/helper.class'; +import {LoginErrorCodes} from '../../login/utils/guardHelper.class'; +import {UserManagementService} from "../../services/user-management.service"; @Component({ - selector: 'claims-project-manager', - templateUrl: 'claimsByToken.component.html', - styles: [` - #table1_info, #table1_paginate, #table1_length, #table1_filter, - #table2_info, #table2_paginate, #table2_length, #table2_filter{ - display: none; - } + selector: 'claims-project-manager', + templateUrl: 'claimsByToken.component.html', + styles: [` + #table1_info, #table1_paginate, #table1_length, #table1_filter, + #table2_info, #table2_paginate, #table2_length, #table2_filter { + display: none; + } - `], - encapsulation: ViewEncapsulation.None // this used in order styles to work + `], + encapsulation: ViewEncapsulation.None // this used in order styles to work }) export class ClaimsByTokenComponent { public openaireId: string = ""; public sub: any; public project: any; - private claims:any = []; + private claims: any = []; public pending_claims: any = []; public curated_claims: any = []; public selectedRight_PendingMode: Set; @@ -62,13 +60,13 @@ export class ClaimsByTokenComponent { public showTables: boolean = true; public rowsOnPage = 5; public sortOrder = "asc"; - public keyword1:string = ""; - public keyword2:string = ""; + public keyword1: string = ""; + public keyword2: string = ""; - public activePendingPage:any = {page: 1}; - public totalPendingResults:any = {count: 0}; - public activeCuratedPage:any = {page: 1}; - public totalCuratedResults:any = {count: 0}; + public activePendingPage: any = {page: 1}; + public totalPendingResults: any = {count: 0}; + public activeCuratedPage: any = {page: 1}; + public totalCuratedResults: any = {count: 0}; dtTrigger: Subject[] = []; private triggered: boolean = false; @@ -79,29 +77,31 @@ export class ClaimsByTokenComponent { //@ViewChild("table1") table1: DataTableDirective; //@ViewChild("table2") table2: DataTableDirective; - @ViewChild (ModalSelect) selectModal : ModalSelect; - @ViewChild (ModalLoading) loading : ModalLoading ; + @ViewChild(ModalSelect) selectModal: ModalSelect; + @ViewChild(ModalLoading) loading: ModalLoading; - properties:EnvProperties; + properties: EnvProperties; - public routerHelper:RouterHelper = new RouterHelper(); + public routerHelper: RouterHelper = new RouterHelper(); - constructor (private route: ActivatedRoute, - private _router: Router, - private claimsByTokenService: ClaimsByTokenService, - private _meta: Meta, private _title: Title) { - this.errorCodes = new ErrorCodes(); - this.errorMessages = new ErrorMessagesComponent(); - this.pending_status = this.errorCodes.LOADING; - this.curated_status = this.errorCodes.LOADING; + constructor(private route: ActivatedRoute, + private _router: Router, + private claimsByTokenService: ClaimsByTokenService, + private _meta: Meta, private _title: Title, + private userManagementService: UserManagementService) { + this.errorCodes = new ErrorCodes(); + this.errorMessages = new ErrorMessagesComponent(); + this.pending_status = this.errorCodes.LOADING; + this.curated_status = this.errorCodes.LOADING; } + ngOnInit() { this.route.data .subscribe((data: { envSpecific: EnvProperties }) => { - this.properties = data.envSpecific; + this.properties = data.envSpecific; }); - this.sub = this.route.queryParams.subscribe(params => { + this.sub = this.route.queryParams.subscribe(params => { this.mode = "pending"; this.openaireId = params['openaireId']; this.selectedRight_PendingMode = new Set(); @@ -119,11 +119,11 @@ export class ClaimsByTokenComponent { //"searching": false, //"lengthChange": false, "pageLength": this.rowsOnPage, - "columnDefs": [ { - "type": "date", - "targets": 2 - } ], - "order": [[ 2, 'desc' ]] + "columnDefs": [{ + "type": "date", + "targets": 2 + }], + "order": [[2, 'desc']] //"pagingType": 'full_numbers', /*"language": { "search": "", @@ -133,11 +133,11 @@ export class ClaimsByTokenComponent { this.dtOptions[1] = { "pageLength": this.rowsOnPage, - "columnDefs": [ { - "type": "date", - "targets": [2,4] - } ], - "order": [[ 4, 'desc' ]] + "columnDefs": [{ + "type": "date", + "targets": [2, 4] + }], + "order": [[4, 'desc']] }; @@ -146,19 +146,26 @@ export class ClaimsByTokenComponent { } ngAfterViewInit(): void { - $.fn['dataTable'].ext.search.push((settings, data, dataIndex) => { - if(settings.sTableId == 'table1') { - if (this.filterData(data, this.keyword1)) { - return true; + this.userManagementService.isLoggedIn(this.properties.userInfoUrl).subscribe(isLoggedIn => { + if (isLoggedIn) { + $.fn['dataTable'].ext.search.push((settings, data, dataIndex) => { + if (settings.sTableId == 'table1') { + return !!this.filterData(data, this.keyword1); + + } else if (settings.sTableId == 'table2') { + return !!this.filterData(data, this.keyword2); + } - return false; - } else if(settings.sTableId == 'table2') { - if (this.filterData(data, this.keyword2)) { - return true; + }); + } else { + this._router.navigate(['/user-info'], { + queryParams: { + "errorCode": LoginErrorCodes.NOT_VALID, + "redirectUrl": this._router.url } - return false; - } - }); + }); + } + }); } ngOnDestroy(): void { @@ -171,20 +178,20 @@ export class ClaimsByTokenComponent { /* Trigger a table draw in order to get the initial filtering */ - triggerInitialLoad(){ - this.triggered = true; - //console.info("triggerInitialLoad"); - setTimeout(function(){ - /*var table1 = $('#table1').DataTable(); - table1.page( 0 ).draw( false ); + triggerInitialLoad() { + this.triggered = true; + //console.info("triggerInitialLoad"); + setTimeout(function () { + /*var table1 = $('#table1').DataTable(); + table1.page( 0 ).draw( false ); - var table2 = $('#table2').DataTable(); - table2.page( 0 ).draw( false );*/ - }, 500); - setTimeout(() => { - this.dtTrigger[0].next(); - this.dtTrigger[1].next(); - }); + var table2 = $('#table2').DataTable(); + table2.page( 0 ).draw( false );*/ + }, 500); + setTimeout(() => { + this.dtTrigger[0].next(); + this.dtTrigger[1].next(); + }); } @@ -201,127 +208,134 @@ export class ClaimsByTokenComponent { }); } - filterData(row: any, query: string) { - if(!Session.isLoggedIn()){ - this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl": this._router.url} }); - } else { - let returnValue: boolean = false; - - if(query) { - for(var i=0; i <3; i++){ - var r= this.filterQuery(row[i], query); - if(r) { - returnValue = true; - break; - } - } - - if(!returnValue) { - return false; + filterData(row: any, query: string): boolean { + let returnValue: boolean = false; + if (query) { + for (var i = 0; i < 3; i++) { + var r = this.filterQuery(row[i], query); + if (r) { + returnValue = true; + break; } } - return true; + if (!returnValue) { + return false; + } } + return true; } - filterQuery(data, query){ - if(data.toLowerCase().indexOf(query.toLowerCase()) > -1){ + filterQuery(data, query) { + if (data.toLowerCase().indexOf(query.toLowerCase()) > -1) { return true; - }else{ + } else { return false; } } -refreshTable(page:number, whichTable: string) { - if(!Session.isLoggedIn()){ - this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl": this._router.url} }); - } else { - if(whichTable == "pending") { - var table = $('#table1').DataTable(); - table.page( page - 1 ).draw( false ); + refreshTable(page: number, whichTable: string) { + this.userManagementService.isLoggedIn(this.properties.userInfoUrl).subscribe(isLoggedIn => { + if (!isLoggedIn) { + this._router.navigate(['/user-info'], { + queryParams: { + "errorCode": LoginErrorCodes.NOT_VALID, + "redirectUrl": this._router.url + } + }); + } else { + if (whichTable == "pending") { + var table = $('#table1').DataTable(); + table.page(page - 1).draw(false); - var info = table.page.info(); + var info = table.page.info(); - this.activePendingPage.page = page;//$event.value; - this.totalPendingResults.count = info.recordsDisplay; - } else if(whichTable == 'curated') { - var table = $('#table2').DataTable(); - table.page( page - 1 ).draw( false ); + this.activePendingPage.page = page;//$event.value; + this.totalPendingResults.count = info.recordsDisplay; + } else if (whichTable == 'curated') { + var table = $('#table2').DataTable(); + table.page(page - 1).draw(false); - var info = table.page.info(); + var info = table.page.info(); - this.activeCuratedPage.page = page;//$event.value; - this.totalCuratedResults.count = info.recordsDisplay; - } + this.activeCuratedPage.page = page;//$event.value; + this.totalCuratedResults.count = info.recordsDisplay; + } + } + }); + + //table.mfActivePage=$event.value; + //table.setPage(table.mfActivePage, this.rowsOnPage); } - //table.mfActivePage=$event.value; - //table.setPage(table.mfActivePage, this.rowsOnPage); -} - validateJWTandToken() { - if(!Session.isLoggedIn()){ - this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl": this._router.url} }); - } else { - if(this.openaireId) { - this.pending_status = this.errorCodes.LOADING; - this.curated_status = this.errorCodes.LOADING; + this.userManagementService.isLoggedIn(this.properties.userInfoUrl).subscribe(isLoggedIn => { + if (!isLoggedIn) { + this._router.navigate(['/user-info'], { + queryParams: { + "errorCode": LoginErrorCodes.NOT_VALID, + "redirectUrl": this._router.url + } + }); + } else { + if (this.openaireId) { + this.pending_status = this.errorCodes.LOADING; + this.curated_status = this.errorCodes.LOADING; - this.showTables = false; - this.pending_claims = []; - this.curated_claims = []; + this.showTables = false; + this.pending_claims = []; + this.curated_claims = []; - this.activePendingPage.page = 1; - this.totalPendingResults.count = 0; - this.activeCuratedPage.page = 1; - this.totalCuratedResults.count = 0; + this.activePendingPage.page = 1; + this.totalPendingResults.count = 0; + this.activeCuratedPage.page = 1; + this.totalCuratedResults.count = 0; - this.claimsByTokenService.getClaims(this.openaireId, this.properties.claimsAPIURL).subscribe( + this.claimsByTokenService.getClaims(this.openaireId, this.properties.claimsAPIURL).subscribe( data => { //this.closeLoading(); this.accessStatus = "valid"; - this.claims = data.data; - for(let claim of this.claims) { - if(claim.targetType == "project") { - this.project = claim.target; - } else { - this.project = claim.source; - } - if(claim.curatedBy) { - this.curated_claims.push(claim); - } else { - this.pending_claims.push(claim); - } - } - - this.totalPendingResults.count = this.pending_claims.length; - this.totalCuratedResults.count = this.curated_claims.length; - - if(this.project) { - this.updateTitle("Claims For Project Managers - "+this.project.name); - } - this.showTables = true; - - if(!this.triggered) { - //console.info("initial load"); - this.triggerInitialLoad(); + this.claims = data.data; + for (let claim of this.claims) { + if (claim.targetType == "project") { + this.project = claim.target; } else { - //console.info("rerender"); - var table1 = $('#table1').DataTable(); - table1.clear(); - - var table2 = $('#table2').DataTable(); - table2.clear(); - - this.rerender(); + this.project = claim.source; } + if (claim.curatedBy) { + this.curated_claims.push(claim); + } else { + this.pending_claims.push(claim); + } + } - this.pending_status = this.errorCodes.DONE; - this.curated_status = this.errorCodes.DONE; + this.totalPendingResults.count = this.pending_claims.length; + this.totalCuratedResults.count = this.curated_claims.length; + + if (this.project) { + this.updateTitle("Claims For Project Managers - " + this.project.name); + } + this.showTables = true; + + if (!this.triggered) { + //console.info("initial load"); + this.triggerInitialLoad(); + } else { + //console.info("rerender"); + var table1 = $('#table1').DataTable(); + table1.clear(); + + var table2 = $('#table2').DataTable(); + table2.clear(); + + this.rerender(); + } + + this.pending_status = this.errorCodes.DONE; + this.curated_status = this.errorCodes.DONE; }, err => { - this.handleError("Error getting claims for openaire id: "+this.openaireId, err); + this.handleError("Error getting claims for openaire id: " + this.openaireId, err); this.pending_status = this.errorMessages.getErrorCode(err.status); this.curated_status = this.pending_status; @@ -337,7 +351,7 @@ refreshTable(page:number, whichTable: string) { }*/ this.showTables = true; - if(!this.triggered) { + if (!this.triggered) { this.triggerInitialLoad(); } else { var table1 = $('#table1').DataTable(); @@ -353,74 +367,90 @@ refreshTable(page:number, whichTable: string) { //console.log(err); } ); - } else { + } else { this.accessStatus = "invalid"; + } } - } + }); } - selectApprove(id:string, event, mode: string) { - if(!Session.isLoggedIn()){ - this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl": this._router.url} }); - } else { - var value = event.currentTarget.checked; - if(value){ - if(mode == "pending") { - this.selectedRight_PendingMode.add(id); - this.selectedWrong_PendingMode.delete(id); + selectApprove(id: string, event, mode: string) { + this.userManagementService.isLoggedIn(this.properties.userInfoUrl).subscribe(isLoggedIn => { + if (!isLoggedIn) { + this._router.navigate(['/user-info'], { + queryParams: { + "errorCode": LoginErrorCodes.NOT_VALID, + "redirectUrl": this._router.url + } + }); + } else { + var value = event.currentTarget.checked; + if (value) { + if (mode == "pending") { + this.selectedRight_PendingMode.add(id); + this.selectedWrong_PendingMode.delete(id); + } else { + this.selectedRight_CuratedMode.add(id); + this.selectedWrong_CuratedMode.delete(id); + } } else { - this.selectedRight_CuratedMode.add(id); - this.selectedWrong_CuratedMode.delete(id); + if (mode == "pending") { + this.selectedRight_PendingMode.delete(id); + } + // } else { + // this.selectedRight_CuratedMode.delete(id); + // this.selectedWrong_CuratedMode.add(id); + // } } - }else{ - if(mode == "pending") { - this.selectedRight_PendingMode.delete(id); - } - // } else { - // this.selectedRight_CuratedMode.delete(id); - // this.selectedWrong_CuratedMode.add(id); - // } } - } + }); } - selectDisapprove(id:string, event, mode: string) { - if(!Session.isLoggedIn()){ - this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl": this._router.url} }); - } else { - var value = event.currentTarget.checked; - if(value){ - if(mode == "pending") { - this.selectedWrong_PendingMode.add(id); - this.selectedRight_PendingMode.delete(id); + selectDisapprove(id: string, event, mode: string) { + this.userManagementService.isLoggedIn(this.properties.userInfoUrl).subscribe(isLoggedIn => { + if (!isLoggedIn) { + this._router.navigate(['/user-info'], { + queryParams: { + "errorCode": LoginErrorCodes.NOT_VALID, + "redirectUrl": this._router.url + } + }); + } else { + var value = event.currentTarget.checked; + if (value) { + if (mode == "pending") { + this.selectedWrong_PendingMode.add(id); + this.selectedRight_PendingMode.delete(id); + } else { + this.selectedWrong_CuratedMode.add(id); + this.selectedRight_CuratedMode.delete(id); + } } else { - this.selectedWrong_CuratedMode.add(id); - this.selectedRight_CuratedMode.delete(id); + if (mode == "pending") { + this.selectedWrong_PendingMode.delete(id); + } + // } else { + // this.selectedWrong_CuratedMode.delete(id); + // this.selectedRight_CuratedMode.add(id); + // } } - }else{ - if(mode == "pending") { - this.selectedWrong_PendingMode.delete(id); - } - // } else { - // this.selectedWrong_CuratedMode.delete(id); - // this.selectedRight_CuratedMode.add(id); - // } } - } + }); } - isSelected(id:string, set:Set) { + isSelected(id: string, set: Set) { return set.has(id); } -/* - isSelectedWrong(id:string) { - return this.selectedWrong.has(id); - } -*/ + + /* + isSelectedWrong(id:string) { + return this.selectedWrong.has(id); + } + */ isRight_CuratedMode(claim: any) { - if(this.isSelected(claim.id, this.selectedRight_CuratedMode)) { + if (this.isSelected(claim.id, this.selectedRight_CuratedMode)) { return true; - } else if(claim.approved == true && !this.isSelected(claim.id, this.selectedWrong_CuratedMode)) { + } else if (claim.approved == true && !this.isSelected(claim.id, this.selectedWrong_CuratedMode)) { return true; } @@ -428,9 +458,9 @@ refreshTable(page:number, whichTable: string) { } isWrong_CuratedMode(claim: any) { - if(this.isSelected(claim.id, this.selectedWrong_CuratedMode)) { + if (this.isSelected(claim.id, this.selectedWrong_CuratedMode)) { return true; - } else if(claim.approved == false && !this.isSelected(claim.id, this.selectedRight_CuratedMode)) { + } else if (claim.approved == false && !this.isSelected(claim.id, this.selectedRight_CuratedMode)) { return true; } @@ -438,37 +468,50 @@ refreshTable(page:number, whichTable: string) { } cancelEditOfCuration(claim: any) { - if(!Session.isLoggedIn()){ - this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl": this._router.url} }); - } else { - if(claim.approved) { - //this.selectedRight_CuratedMode.add(claim.id); - this.selectedWrong_CuratedMode.delete(claim.id); + this.userManagementService.isLoggedIn(this.properties.userInfoUrl).subscribe(isLoggedIn => { + if (!isLoggedIn) { + this._router.navigate(['/user-info'], { + queryParams: { + "errorCode": LoginErrorCodes.NOT_VALID, + "redirectUrl": this._router.url + } + }); } else { - this.selectedRight_CuratedMode.delete(claim.id); - //this.selectedWrong_CuratedMode.add(claim.id); + if (claim.approved) { + //this.selectedRight_CuratedMode.add(claim.id); + this.selectedWrong_CuratedMode.delete(claim.id); + } else { + this.selectedRight_CuratedMode.delete(claim.id); + //this.selectedWrong_CuratedMode.add(claim.id); + } } - } + }); } saveEdited(claim: any, editable_index: number) { - if(!Session.isLoggedIn()){ - this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl": this._router.url} }); - } else { - this.curated_status = this.errorCodes.LOADING; - - let approved: boolean = this.isRight_CuratedMode(claim); - - if(approved == claim.approved) { - this.selectedRight_CuratedMode.delete(claim.id); - this.selectedWrong_CuratedMode.delete(claim.id); - this.editable.delete(editable_index); - - this.curated_status = this.errorCodes.DONE; + this.userManagementService.isLoggedIn(this.properties.userInfoUrl).subscribe(isLoggedIn => { + if (!isLoggedIn) { + this._router.navigate(['/user-info'], { + queryParams: { + "errorCode": LoginErrorCodes.NOT_VALID, + "redirectUrl": this._router.url + } + }); } else { - let claimCurationInfo: {"id": string, "approved": boolean} = {"id": claim.id, "approved": approved}; + this.curated_status = this.errorCodes.LOADING; - this.claimsByTokenService.updateClaimCuration(claimCurationInfo, this.properties.claimsAPIURL).subscribe( + let approved: boolean = this.isRight_CuratedMode(claim); + + if (approved == claim.approved) { + this.selectedRight_CuratedMode.delete(claim.id); + this.selectedWrong_CuratedMode.delete(claim.id); + this.editable.delete(editable_index); + + this.curated_status = this.errorCodes.DONE; + } else { + let claimCurationInfo: { "id": string, "approved": boolean } = {"id": claim.id, "approved": approved}; + + this.claimsByTokenService.updateClaimCuration(claimCurationInfo, this.properties.claimsAPIURL).subscribe( data => { this.selectedRight_CuratedMode.delete(claim.id); this.selectedWrong_CuratedMode.delete(claim.id); @@ -478,22 +521,29 @@ refreshTable(page:number, whichTable: string) { }, err => { //console.log(err); - this.handleError("Error updating claim curation: "+JSON.stringify(claimCurationInfo), err); + this.handleError("Error updating claim curation: " + JSON.stringify(claimCurationInfo), err); this.curated_status = this.errorCodes.NOT_SAVED; } ); + } } - } + }); } saveChanges() { - if(!Session.isLoggedIn()){ - this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl": this._router.url} }); - } else { - this.pending_status = this.errorCodes.LOADING; - //this.openLoading(); - //console.info("Changes Saved!, right-wrong", this.selectedRight_PendingMode, this.selectedWrong_PendingMode); - this.claimsByTokenService.updateClaimsCuration(this.selectedRight_PendingMode, this.selectedWrong_PendingMode, this.properties.claimsAPIURL).subscribe( + this.userManagementService.isLoggedIn(this.properties.userInfoUrl).subscribe(isLoggedIn => { + if (!isLoggedIn) { + this._router.navigate(['/user-info'], { + queryParams: { + "errorCode": LoginErrorCodes.NOT_VALID, + "redirectUrl": this._router.url + } + }); + } else { + this.pending_status = this.errorCodes.LOADING; + //this.openLoading(); + //console.info("Changes Saved!, right-wrong", this.selectedRight_PendingMode, this.selectedWrong_PendingMode); + this.claimsByTokenService.updateClaimsCuration(this.selectedRight_PendingMode, this.selectedWrong_PendingMode, this.properties.claimsAPIURL).subscribe( data => { //this.closeLoading(); this.mode = "curated"; @@ -503,31 +553,40 @@ refreshTable(page:number, whichTable: string) { err => { //this.closeLoading(); //console.log(err); - this.handleError("Error updating claims: right: "+JSON.stringify(this.selectedRight_PendingMode)+" and wrong: "+JSON.stringify(this.selectedWrong_PendingMode), err); + this.handleError("Error updating claims: right: " + JSON.stringify(this.selectedRight_PendingMode) + " and wrong: " + JSON.stringify(this.selectedWrong_PendingMode), err); this.pending_status = this.errorCodes.NOT_SAVED; } ); - } + } + }); } clearCheckboxes() { - if(!Session.isLoggedIn()){ - this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl": this._router.url} }); - } else { - this.pending_status = this.errorCodes.LOADING; - this.selectedRight_PendingMode.clear(); - this.selectedWrong_PendingMode.clear(); - this.pending_status = this.errorCodes.DONE; - } + this.userManagementService.isLoggedIn(this.properties.userInfoUrl).subscribe(isLoggedIn => { + if (!isLoggedIn) { + this._router.navigate(['/user-info'], { + queryParams: { + "errorCode": LoginErrorCodes.NOT_VALID, + "redirectUrl": this._router.url + } + }); + } else { + this.pending_status = this.errorCodes.LOADING; + this.selectedRight_PendingMode.clear(); + this.selectedWrong_PendingMode.clear(); + this.pending_status = this.errorCodes.DONE; + } + }); } - public openLoading(){ - if(this.loading){ + public openLoading() { + if (this.loading) { this.loading.open(); } } - public closeLoading(){ - if(this.loading){ + + public closeLoading() { + if (this.loading) { this.loading.close(); } } @@ -536,41 +595,41 @@ refreshTable(page:number, whichTable: string) { //console.info("selected curator: "+selected); } - public openSelect(){ - if(this.selectModal){ + public openSelect() { + if (this.selectModal) { this.selectModal.open(); } } - public setMessageSelect(message: string){ - if(this.selectModal){ + public setMessageSelect(message: string) { + if (this.selectModal) { this.selectModal.message = message; } } - public setOptionsSelect(options: string[]){ - if(this.selectModal){ + public setOptionsSelect(options: string[]) { + if (this.selectModal) { this.selectModal.options = options; } } totalPages(totalResults: number): number { - let totalPages:any = totalResults/(this.rowsOnPage); - if(!(Number.isInteger(totalPages))) { - totalPages = (parseInt(totalPages, 10) + 1); - } - return totalPages; + let totalPages: any = totalResults / (this.rowsOnPage); + if (!(Number.isInteger(totalPages))) { + totalPages = (parseInt(totalPages, 10) + 1); + } + return totalPages; } - updateTitle(title:string){ - var _prefix ="OpenAIRE | "; - var _title = _prefix + ((title.length> 50 ) ?title.substring(0,50):title); - this._meta.updateTag({content:_title},"property='og:title'"); + updateTitle(title: string) { + var _prefix = "OpenAIRE | "; + var _title = _prefix + ((title.length > 50) ? title.substring(0, 50) : title); + this._meta.updateTag({content: _title}, "property='og:title'"); this._title.setTitle(_title); } private handleError(message: string, error) { - console.error("Claims Project Manager Page: "+message, error); + console.error("Claims Project Manager Page: " + message, error); } } diff --git a/claims/linking/insertClaim/insertClaim.component.ts b/claims/linking/insertClaim/insertClaim.component.ts index fa266018..6d387342 100644 --- a/claims/linking/insertClaim/insertClaim.component.ts +++ b/claims/linking/insertClaim/insertClaim.component.ts @@ -14,6 +14,7 @@ import { DirectIndexRecord, Message } from "../../claim-utils/claimHelper.class"; +import {UserManagementService} from "../../../services/user-management.service"; @Component({ selector: 'claim-insert', @@ -51,7 +52,8 @@ import { ` }) export class ClaimInsertComponent { - constructor(private claimService: ClaimsService, private _router: Router, private route: ActivatedRoute,) { + constructor(private claimService: ClaimsService, private _router: Router, private route: ActivatedRoute, + private userManagementService: UserManagementService) { } ngOnInit() { @@ -93,113 +95,116 @@ export class ClaimInsertComponent { this.errorInClaims = []; this.insertedRecords = []; this.errorInRecords = []; - if (!Session.isLoggedIn()) { - localStorage.setItem(this.localStoragePrefix + "results", JSON.stringify(this.results)); - if (this.sources != null) { - localStorage.setItem(this.localStoragePrefix + "sources", JSON.stringify(this.sources)); - } - - this._router.navigate(['/user-info'], { - queryParams: { - "errorCode": LoginErrorCodes.NOT_VALID, - "redirectUrl": this._router.url + this.userManagementService.getUserInfo(this.properties.userInfoUrl).subscribe(user => { + if (!user) { + localStorage.setItem(this.localStoragePrefix + "results", JSON.stringify(this.results)); + if (this.sources != null) { + localStorage.setItem(this.localStoragePrefix + "sources", JSON.stringify(this.sources)); } - }); - } else { - this.claiming = true; - const user = Session.getUserEmail(); - this.loading.open(); - let claims: ClaimRecord2Insert[] = []; - let directclaims: DirectIndexRecord[] = []; - for (let j = 0; j < this.sources.length; j++) { // if an external result -> direct insert in the index - const result: ClaimEntity = this.sources[j]; - if (result.result && ["crossref", "datacite", "orcid"].indexOf(result.result.source) != -1) { - directclaims.push({"id": result.id, "record": ClaimInsertComponent.createDirectClaim(result, this.results)}); - } - } - for (let i = 0; i < this.results.length; i++) { - const entity: ClaimEntity = this.results[i]; // this is a research result, a project or a context - - if (entity.result && ["crossref", "datacite", "orcid"].indexOf(entity.result.source) != -1) { // if an external result -> direct insert in the index - if (this.sources.length > 0) { - directclaims.push({ - "id": entity.id, - "record": ClaimInsertComponent.createDirectClaim(entity, this.sources) - }); - } else if (this.inlineEntity) { - directclaims.push({ - "id": entity.id, - "record": ClaimInsertComponent.createDirectClaim(entity, [this.inlineEntity]) - }); + this._router.navigate(['/user-info'], { + queryParams: { + "errorCode": LoginErrorCodes.NOT_VALID, + "redirectUrl": this._router.url } + }); - } - - for (let j = 0; j < this.sources.length; j++) { - const result: ClaimEntity = this.sources[j]; // this is a research result - if (entity.result) { - claims.push(ClaimInsertComponent.createResultClaim(result, entity, user)); - } else if (entity.context) { - claims.push(ClaimInsertComponent.createContextClaim(result, entity, user)); - } else if (entity.project) { - claims.push(ClaimInsertComponent.createProjectClaim(result, entity, user)); - } - - - } - if (this.inlineEntity) { - if (this.inlineEntity.result) { - if (entity.result) { - claims.push(ClaimInsertComponent.createResultClaim(this.inlineEntity, entity, user)); - } else if (entity.context) { - claims.push(ClaimInsertComponent.createContextClaim(this.inlineEntity, entity, user)); - } else if (entity.project) { - claims.push(ClaimInsertComponent.createProjectClaim(this.inlineEntity, entity, user)); - } - } else if (this.inlineEntity.project) { - if (entity.result) { - claims.push(ClaimInsertComponent.createProjectClaim(entity, this.inlineEntity, user)); - } - } - } - - - } - - //first call direct index service - when call is done (success or error) call isertBulkClaims method to insert claims in DB - console.log("directclaims"); - console.log(directclaims); - if (directclaims.length > 0) { - this.claimService.insertDirectRecords(directclaims, this.properties.claimsAPIURL).subscribe( - data => { - this.insertedRecords = data.insertedIds; - - this.errorInRecords = data.errorInClaims; - this.isertBulkClaims(claims); - }, - err => { - try { - err = err.json(); - } catch (error) { - console.log(error); - } - if (err.insertedIds && err.insertedIds.length > 0) { - this.insertedRecords = err.insertedIds; - } - if (err.errorInClaims && err.errorInClaims.length > 0) { - this.errorInRecords = err.errorInClaims; - } - this.isertBulkClaims(claims); - - ClaimInsertComponent.handleError("Error inserting direct records: " + JSON.stringify(directclaims), err); - } - ); } else { - this.isertBulkClaims(claims); - } - } + this.claiming = true; + this.loading.open(); + let claims: ClaimRecord2Insert[] = []; + let directclaims: DirectIndexRecord[] = []; + for (let j = 0; j < this.sources.length; j++) { // if an external result -> direct insert in the index + const result: ClaimEntity = this.sources[j]; + if (result.result && ["crossref", "datacite", "orcid"].indexOf(result.result.source) != -1) { + directclaims.push({ + "id": result.id, + "record": ClaimInsertComponent.createDirectClaim(result, this.results) + }); + } + } + for (let i = 0; i < this.results.length; i++) { + const entity: ClaimEntity = this.results[i]; // this is a research result, a project or a context + if (entity.result && ["crossref", "datacite", "orcid"].indexOf(entity.result.source) != -1) { // if an external result -> direct insert in the index + if (this.sources.length > 0) { + directclaims.push({ + "id": entity.id, + "record": ClaimInsertComponent.createDirectClaim(entity, this.sources) + }); + } else if (this.inlineEntity) { + directclaims.push({ + "id": entity.id, + "record": ClaimInsertComponent.createDirectClaim(entity, [this.inlineEntity]) + }); + } + + } + + for (let j = 0; j < this.sources.length; j++) { + const result: ClaimEntity = this.sources[j]; // this is a research result + if (entity.result) { + claims.push(ClaimInsertComponent.createResultClaim(result, entity, user.email)); + } else if (entity.context) { + claims.push(ClaimInsertComponent.createContextClaim(result, entity, user.email)); + } else if (entity.project) { + claims.push(ClaimInsertComponent.createProjectClaim(result, entity, user.email)); + } + + + } + if (this.inlineEntity) { + if (this.inlineEntity.result) { + if (entity.result) { + claims.push(ClaimInsertComponent.createResultClaim(this.inlineEntity, entity, user.email)); + } else if (entity.context) { + claims.push(ClaimInsertComponent.createContextClaim(this.inlineEntity, entity, user.email)); + } else if (entity.project) { + claims.push(ClaimInsertComponent.createProjectClaim(this.inlineEntity, entity, user.email)); + } + } else if (this.inlineEntity.project) { + if (entity.result) { + claims.push(ClaimInsertComponent.createProjectClaim(entity, this.inlineEntity, user.email)); + } + } + } + + + } + + //first call direct index service - when call is done (success or error) call isertBulkClaims method to insert claims in DB + console.log("directclaims"); + console.log(directclaims); + if (directclaims.length > 0) { + this.claimService.insertDirectRecords(directclaims, this.properties.claimsAPIURL).subscribe( + data => { + this.insertedRecords = data.insertedIds; + + this.errorInRecords = data.errorInClaims; + this.isertBulkClaims(claims); + }, + err => { + try { + err = err.json(); + } catch (error) { + console.log(error); + } + if (err.insertedIds && err.insertedIds.length > 0) { + this.insertedRecords = err.insertedIds; + } + if (err.errorInClaims && err.errorInClaims.length > 0) { + this.errorInRecords = err.errorInClaims; + } + this.isertBulkClaims(claims); + + ClaimInsertComponent.handleError("Error inserting direct records: " + JSON.stringify(directclaims), err); + } + ); + } else { + this.isertBulkClaims(claims); + } + } + }); } private isertBulkClaims(claims: ClaimRecord2Insert[]) { diff --git a/claims/myClaims/myClaims.component.ts b/claims/myClaims/myClaims.component.ts index ed8b1e32..7158ce6a 100644 --- a/claims/myClaims/myClaims.component.ts +++ b/claims/myClaims/myClaims.component.ts @@ -1,5 +1,7 @@ import {Component, Input} from '@angular/core'; import {Meta, Title} from '@angular/platform-browser'; +import {User} from "../../login/utils/helper.class"; +import {UserManagementService} from "../../services/user-management.service"; @Component({ selector: 'my-claims', @@ -17,7 +19,7 @@ import {Meta, Title} from '@angular/platform-browser'; Manage your links in OpenAIRE
- @@ -33,9 +35,15 @@ export class MyClaimsComponent { @Input() claimsInfoURL: string; @Input() communityId:string; @Input() piwikSiteId = null; + @Input() userInfoURL: string; + public user: User = null; - constructor() {} + constructor(private userManagementService: UserManagementService) {} - ngOnInit() {} + ngOnInit() { + this.userManagementService.getUserInfo(this.userInfoURL).subscribe(user => { + this.user = user; + }); + } } diff --git a/connect/communityGuard/connectAdminLoginGuard.guard.ts b/connect/communityGuard/connectAdminLoginGuard.guard.ts index 0b1ca4c3..467a548a 100644 --- a/connect/communityGuard/connectAdminLoginGuard.guard.ts +++ b/connect/communityGuard/connectAdminLoginGuard.guard.ts @@ -1,6 +1,5 @@ - import {map, filter, mergeMap} from 'rxjs/operators'; -import { Injectable } from '@angular/core'; +import {Injectable} from '@angular/core'; import { Router, CanActivate, @@ -8,44 +7,51 @@ import { RouterStateSnapshot, CanLoad, Route, UrlSegment } from '@angular/router'; -import {Observable} from 'rxjs'; +import {Observable, of} from 'rxjs'; import {Session} from '../../login/utils/helper.class'; import {LoginErrorCodes} from '../../login/utils/guardHelper.class'; 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 {StringUtils} from '../../utils/string-utils.class'; +import {UserManagementService} from "../../services/user-management.service"; @Injectable() export class ConnectAdminLoginGuard implements CanActivate, CanLoad { constructor(private router: Router, private communityService: CommunityService, - private propertiesService: EnvironmentSpecificService) {} + private propertiesService: EnvironmentSpecificService, + private userManagementService: UserManagementService) { + } check(community: string, path: string): Observable | boolean { let errorCode = LoginErrorCodes.NOT_LOGIN; - if (Session.isLoggedIn()) { - if (Session.isPortalAdministrator() || Session.isCommunityCurator()) { - return true; - } else { - const obs = this.propertiesService.subscribeEnvironment().pipe(map(res => res),mergeMap(properties => { - return this.communityService.isCommunityManager(properties, properties['communityAPI'] + community, Session.getUserEmail()); - }),); - obs.pipe(filter(enabled => !enabled)) - .subscribe(() => this.router.navigate(['/user-info'], { - queryParams: { - 'errorCode': errorCode, - 'redirectUrl': path - } - })); - return obs; - } - } else { - errorCode = LoginErrorCodes.NOT_LOGIN; - this.router.navigate(['/user-info'], {queryParams: {'errorCode': errorCode, 'redirectUrl': path}}); - - return false; - } + let email = null; + const authorized = this.propertiesService.subscribeEnvironment().pipe(map(res => res), mergeMap(properties => { + return this.userManagementService.getUserInfo(properties.userInfoUrl).pipe(map(user => { + if (user) { + email = user.email; + if (Session.isPortalAdministrator(user) || Session.isCommunityCurator(user)) { + return of(true); + } else { + return this.communityService.isCommunityManager(properties, properties['communityAPI'] + community, + email); + } + } else { + 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 { diff --git a/connect/communityGuard/connectSubscriber.guard.ts b/connect/communityGuard/connectSubscriber.guard.ts index 1509067f..27624249 100644 --- a/connect/communityGuard/connectSubscriber.guard.ts +++ b/connect/communityGuard/connectSubscriber.guard.ts @@ -1,47 +1,49 @@ -import {filter, mergeMap} from 'rxjs/operators'; +import {filter, map, mergeMap} from 'rxjs/operators'; import { Injectable } from '@angular/core'; import {Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, CanLoad, Route} from '@angular/router'; -import {Observable} from 'rxjs'; +import {Observable, of} from 'rxjs'; import {Session} from '../../login/utils/helper.class'; import {LoginErrorCodes} from '../../login/utils/guardHelper.class'; import {CommunityService} from '../community/community.service'; import { EnvironmentSpecificService} from '../../utils/properties/environment-specific.service'; import {ConnectHelper} from '../connectHelper'; +import {UserManagementService} from "../../services/user-management.service"; @Injectable() export class ConnectSubscriberGuard implements CanActivate { constructor(private router: Router, private communityService: CommunityService, + private userManagementService: UserManagementService, private propertiesService: EnvironmentSpecificService) {} check(community: string, path: string): Observable | boolean { let errorCode = LoginErrorCodes.NOT_SUBSCRIBER; - if (!Session.isLoggedIn()) { - errorCode = LoginErrorCodes.NOT_LOGIN; - this.router.navigate(['/user-info'], {queryParams: {'errorCode': errorCode, 'redirectUrl': path, communityId:community}}); - return false; - } else { - const obs = this.propertiesService.subscribeEnvironment().pipe(mergeMap(properties => { - let communityDomain = null; - //if(!community){ - communityDomain = ConnectHelper.getCommunityFromDomain(properties.domain); - //} - if(communityDomain) { - community = communityDomain; + let email = null; + const subscribed = this.propertiesService.subscribeEnvironment().pipe(map(res => res), mergeMap(properties => { + return this.userManagementService.getUserInfo(properties.userInfoUrl).pipe(map(user => { + if (user) { + email = user.email; + let communityDomain = ConnectHelper.getCommunityFromDomain(properties.domain); + if(communityDomain) { + community = communityDomain; + } + return this.communityService.isSubscribedToCommunity( community, email, properties["adminToolsAPIURL"]) + } else { + return of(false); } - return this.communityService.isSubscribedToCommunity( community, Session.getUserEmail(), properties["adminToolsAPIURL"]) + }), mergeMap( authorized => { + return authorized; })); - obs.pipe(filter(enabled => !enabled)) - .subscribe(() => this.router.navigate(['/user-info'], { - queryParams: { - 'errorCode': errorCode, - 'redirectUrl': path, - communityId:community - } - })); - return obs; - } + })); + subscribed.pipe(filter(subscribed => !subscribed)).subscribe(() => { + this.router.navigate(['/user-info'], { + queryParams: { + 'errorCode': errorCode, + 'redirectUrl': path + } + })}); + return subscribed; } canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable | boolean { diff --git a/connect/communityGuard/isCommunityOrAdmin.ts b/connect/communityGuard/isCommunityOrAdmin.ts index 952a88fd..4589a140 100644 --- a/connect/communityGuard/isCommunityOrAdmin.ts +++ b/connect/communityGuard/isCommunityOrAdmin.ts @@ -1,22 +1,35 @@ -import { Injectable } from '@angular/core'; -import { - Router, - CanActivate, - ActivatedRouteSnapshot, - RouterStateSnapshot, - CanLoad, Route, UrlSegment -} from '@angular/router'; +import {Injectable} from '@angular/core'; +import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from '@angular/router'; import {Observable} from 'rxjs'; - -import {ConnectHelper} from '../connectHelper'; -import {Session} from '../../login/utils/helper.class'; +import {filter, map, mergeMap} from "rxjs/operators"; +import {UserManagementService} from "../../services/user-management.service"; +import {EnvironmentSpecificService} from "../../utils/properties/environment-specific.service"; +import {Session} from "../../login/utils/helper.class"; @Injectable() export class IsCommunityOrAdmin implements CanActivate { - constructor(private router: Router) { + constructor(private router: Router, + private userManagementService: UserManagementService, + private propertiesService: EnvironmentSpecificService) { } + check(community: string): Observable | boolean { + if (community && community !== 'undefined') { + return true; + } else { + const obs = this.propertiesService.subscribeEnvironment().pipe(mergeMap(properties => { + return this.userManagementService.getUserInfo(properties['userInfoUrl']).pipe(map(user => { + return Session.isPortalAdministrator(user); + })); + })); + obs.pipe(filter( isAdmin => !isAdmin)).subscribe( () => { + this.router.navigate(['/errorCommunity']); + }); + return obs; + } + } +/* check(community: string): Observable | boolean { if(Session.isLoggedIn() && Session.isPortalAdministrator()) { return true; @@ -27,10 +40,11 @@ export class IsCommunityOrAdmin implements CanActivate { this.router.navigate(['errorcommunity']); return false; } - } + }*/ canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable | boolean { return this.check(route.queryParams['communityId']); } } + diff --git a/connect/userEmailPreferences/mailPrefs.component.ts b/connect/userEmailPreferences/mailPrefs.component.ts index 6fe21dd5..d1fa1325 100644 --- a/connect/userEmailPreferences/mailPrefs.component.ts +++ b/connect/userEmailPreferences/mailPrefs.component.ts @@ -1,27 +1,25 @@ -import {Component, ViewChild, Input} from '@angular/core'; +import {Component, Input} from '@angular/core'; import {Location} from '@angular/common'; -import {Observable} from 'rxjs'; import {ActivatedRoute, Router} from '@angular/router'; -import {ModalLoading} from '../../utils/modal/loading.component'; -import {AlertModal} from '../../utils/modal/alert'; import {Session} from '../../login/utils/helper.class'; import {EnvProperties} from '../../utils/properties/env-properties'; import {MailPrefsService} from './mailPrefs.service'; import {ConnectHelper} from '../connectHelper'; import {ErrorCodes} from '../../utils/properties/errorCodes'; -import {ErrorMessagesComponent} from '../../utils/errorMessages.component'; +import {ErrorMessagesComponent} from '../../utils/errorMessages.component'; import {LoginErrorCodes} from '../../login/utils/guardHelper.class'; +import {UserManagementService} from "../../services/user-management.service"; declare var UIkit: any; @Component({ selector: 'mailPrefs', templateUrl: 'mailPrefs.component.html', - providers:[MailPrefsService] + providers: [MailPrefsService] }) export class MailPrefsComponent { - properties:EnvProperties; + properties: EnvProperties; sub: any; public communityId: string; public preferencesFor: string = "community"; @@ -32,17 +30,19 @@ export class MailPrefsComponent { public prefsChanged = {}; //public showForbiddenMessage:boolean = false; - public userValidMessage:string = ""; + public userValidMessage: string = ""; public savedMessage: string = ""; - - public fetchId:string; + public fetchId: string; private errorCodes: ErrorCodes; private errorMessages: ErrorMessagesComponent; @Input() showSaveResetButtons: boolean = true; - constructor (private _mailPrefsService: MailPrefsService, private route: ActivatedRoute, private _router:Router, private location: Location) { + constructor(private _mailPrefsService: MailPrefsService, + private route: ActivatedRoute, private _router: Router, + private location: Location, + private userManagementService: UserManagementService) { this.errorCodes = new ErrorCodes(); this.errorMessages = new ErrorMessagesComponent(); this.status = this.errorCodes.LOADING; @@ -53,203 +53,237 @@ export class MailPrefsComponent { .subscribe((data: { envSpecific: EnvProperties }) => { this.properties = data.envSpecific; this.sub = this.route.queryParams.subscribe(params => { - this.communityId = ConnectHelper.getCommunityFromDomain(this.properties.domain); - if(!this.communityId) { + this.communityId = ConnectHelper.getCommunityFromDomain(this.properties.domain); + if (!this.communityId) { this.communityId = params['communityId']; } - - this.fetchId = Session.getUserEmail(); - - this.getEmailPreferences(); - + this.userManagementService.getUserInfo(this.properties.userInfoUrl).subscribe( user => { + this.fetchId = user.email; + this.getEmailPreferences(); + }); }); - }); + }); } getEmailPreferences() { - if(!Session.isLoggedIn()){ - //this.userValidMessage = "User session has expired. Please login again."; - if(this.showSaveResetButtons) { - this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl": this._router.url} }); - } - } else { - this.status = this.errorCodes.LOADING; - this.savedMessage = ""; - - if(this.communityId && this.communityId != "openaire") { - this.preferencesFor = "community"; - this._mailPrefsService.getUserEmailPreferencesForCommunity(this.communityId, this.properties.claimsAPIURL).subscribe( - data => { - if(data.code == "204") { - this.status = this.errorCodes.NONE; - } else { - this.initialNotifications = data.data; - this.notifications = JSON.parse(JSON.stringify( this.initialNotifications )); - - this.status = this.errorCodes.DONE; + this.userManagementService.isLoggedIn(this.properties.userInfoUrl).subscribe(isLoggedIn => { + if (!isLoggedIn) { + //this.userValidMessage = "User session has expired. Please login again."; + if (this.showSaveResetButtons) { + this._router.navigate(['/user-info'], { + queryParams: { + "errorCode": LoginErrorCodes.NOT_VALID, + "redirectUrl": this._router.url } - }, - err => { - this.handleErrors(err); - this.handleError("Error getting user email preferences for community with id: "+this.communityId, err); - } - ); + }); + } } else { - this.preferencesFor = "project"; - this._mailPrefsService.getUserEmailPreferencesForOpenaire(this.properties.claimsAPIURL).subscribe( - data => { + this.status = this.errorCodes.LOADING; + this.savedMessage = ""; - if(data.code == "204") { - this.status = this.errorCodes.NONE; - } else { - - this.initialNotifications = data.data; - this.notifications = JSON.parse(JSON.stringify( this.initialNotifications )); - //this.notifications = this.initialNotifications.map(x => Object.assign({}, x)); - //this.notifications = this.initialNotifications; - - this.status = this.errorCodes.DONE; - } - }, - err => { - //console.info(err); - this.handleErrors(err); - this.handleError("Error getting user email preferences for openaire", err); - } - ); - } - } - } - - changeNotify(notification: any, checked: boolean, index: number) { - if(!Session.isLoggedIn()){ - //this.userValidMessage = "User session has expired. Please login again."; - if(this.showSaveResetButtons) { - this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl": this._router.url} }); - } - } else { - this.savedMessage = ""; - this.status = this.errorCodes.DONE; - notification.notify = checked; - this.prefsChanged[index] = true; - } - } - - changeFrequency(index: number) { - if(!Session.isLoggedIn()){ - //this.userValidMessage = "User session has expired. Please login again."; - if(this.showSaveResetButtons) { - this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl": this._router.url} }); - } - } else { - this.savedMessage = ""; - this.status = this.errorCodes.DONE; - if(this.initialNotifications[index].frequency != this.notifications[index].frequency) { - this.prefsChanged[index] = true; - } - } - } - - saveNotification(index: number) { - if(this.notifications.length > 0 && this.initialNotifications.length > 0) { - if(!Session.isLoggedIn()){ - //this.userValidMessage = "User session has expired. Please login again."; - if(this.showSaveResetButtons) { - this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl": this._router.url} }); - } - } else { - if(JSON.stringify(this.notifications[index]) != JSON.stringify(this.initialNotifications[index])) { - - this.status = this.errorCodes.LOADING; - this.savedMessage = ""; - - this._mailPrefsService.saveUserEmailPreferences(this.notifications[index], this.properties.claimsAPIURL).subscribe( + if (this.communityId && this.communityId != "openaire") { + this.preferencesFor = "community"; + this._mailPrefsService.getUserEmailPreferencesForCommunity(this.communityId, this.properties.claimsAPIURL).subscribe( data => { - this.initialNotifications[index] = JSON.parse(JSON.stringify( this.notifications[index] )); + if (data.code == "204") { + this.status = this.errorCodes.NONE; + } else { + this.initialNotifications = data.data; + this.notifications = JSON.parse(JSON.stringify(this.initialNotifications)); - this.status = this.errorCodes.DONE; - - /*UIkit.notification({ - message : 'Your email preferences for '+this.notifications[index].openaireName+' have been successfully changed', - status : 'success', - timeout : 3000, - pos : 'top-center' - });*/ - this.savedMessage = "Notification settings for claims saved!"; + this.status = this.errorCodes.DONE; + } }, err => { - //console.log(err); - this.handleError("Error saving user email preferences: "+JSON.stringify(this.notifications[index]), err); - this.status = this.errorCodes.NOT_SAVED; + this.handleErrors(err); + this.handleError("Error getting user email preferences for community with id: " + this.communityId, err); + } + ); + } else { + this.preferencesFor = "project"; + this._mailPrefsService.getUserEmailPreferencesForOpenaire(this.properties.claimsAPIURL).subscribe( + data => { + + if (data.code == "204") { + this.status = this.errorCodes.NONE; + } else { + + this.initialNotifications = data.data; + this.notifications = JSON.parse(JSON.stringify(this.initialNotifications)); + //this.notifications = this.initialNotifications.map(x => Object.assign({}, x)); + //this.notifications = this.initialNotifications; + + this.status = this.errorCodes.DONE; + } + }, + err => { + //console.info(err); + this.handleErrors(err); + this.handleError("Error getting user email preferences for openaire", err); } ); } - else { - /*UIkit.notification({ - message : 'No changes selected for '+this.notifications[index].openaireName+' email preferences', - status : 'primary', - timeout : 3000, - pos : 'top-center' - });*/ - this.savedMessage = "Notification settings for claims saved!"; + } + }); + } + + changeNotify(notification: any, checked: boolean, index: number) { + this.userManagementService.isLoggedIn(this.properties.userInfoUrl).subscribe(isLoggedIn => { + if (!isLoggedIn) { + //this.userValidMessage = "User session has expired. Please login again."; + if (this.showSaveResetButtons) { + this._router.navigate(['/user-info'], { + queryParams: { + "errorCode": LoginErrorCodes.NOT_VALID, + "redirectUrl": this._router.url + } + }); + } + } else { + this.savedMessage = ""; + this.status = this.errorCodes.DONE; + notification.notify = checked; + this.prefsChanged[index] = true; + } + }); + } + + changeFrequency(index: number) { + this.userManagementService.isLoggedIn(this.properties.userInfoUrl).subscribe(isLoggedIn => { + if (!isLoggedIn) { + //this.userValidMessage = "User session has expired. Please login again."; + if (this.showSaveResetButtons) { + this._router.navigate(['/user-info'], { + queryParams: { + "errorCode": LoginErrorCodes.NOT_VALID, + "redirectUrl": this._router.url + } + }); + } + } else { + this.savedMessage = ""; + this.status = this.errorCodes.DONE; + if (this.initialNotifications[index].frequency != this.notifications[index].frequency) { + this.prefsChanged[index] = true; } } + }); + } + + saveNotification(index: number) { + if (this.notifications.length > 0 && this.initialNotifications.length > 0) { + this.userManagementService.isLoggedIn(this.properties.userInfoUrl).subscribe(isLoggedIn => { + if (!isLoggedIn) { + //this.userValidMessage = "User session has expired. Please login again."; + if (this.showSaveResetButtons) { + this._router.navigate(['/user-info'], { + queryParams: { + "errorCode": LoginErrorCodes.NOT_VALID, + "redirectUrl": this._router.url + } + }); + } + } else { + if (JSON.stringify(this.notifications[index]) != JSON.stringify(this.initialNotifications[index])) { + + this.status = this.errorCodes.LOADING; + this.savedMessage = ""; + + this._mailPrefsService.saveUserEmailPreferences(this.notifications[index], this.properties.claimsAPIURL).subscribe( + data => { + this.initialNotifications[index] = JSON.parse(JSON.stringify(this.notifications[index])); + + this.status = this.errorCodes.DONE; + + /*UIkit.notification({ + message : 'Your email preferences for '+this.notifications[index].openaireName+' have been successfully changed', + status : 'success', + timeout : 3000, + pos : 'top-center' + });*/ + this.savedMessage = "Notification settings for claims saved!"; + }, + err => { + //console.log(err); + this.handleError("Error saving user email preferences: " + JSON.stringify(this.notifications[index]), err); + this.status = this.errorCodes.NOT_SAVED; + } + ); + } else { + /*UIkit.notification({ + message : 'No changes selected for '+this.notifications[index].openaireName+' email preferences', + status : 'primary', + timeout : 3000, + pos : 'top-center' + });*/ + this.savedMessage = "Notification settings for claims saved!"; + } + } + }); } } restoreNotification(index: number) { - if(!Session.isLoggedIn()){ - //this.userValidMessage = "User session has expired. Please login again."; - if(this.showSaveResetButtons) { - this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl": this._router.url} }); + this.userManagementService.isLoggedIn(this.properties.userInfoUrl).subscribe(isLoggedIn => { + if (!isLoggedIn) { + //this.userValidMessage = "User session has expired. Please login again."; + if (this.showSaveResetButtons) { + this._router.navigate(['/user-info'], { + queryParams: { + "errorCode": LoginErrorCodes.NOT_VALID, + "redirectUrl": this._router.url + } + }); + } + } else { + if (this.notifications.length > 0 && this.initialNotifications.length > 0) { + this.status = this.errorCodes.LOADING; + this.savedMessage = ""; + this.notifications[index] = JSON.parse(JSON.stringify(this.initialNotifications[index])); + this.status = this.errorCodes.DONE; + this.prefsChanged[index] = false; + } } - } else { + }); + } + + /* + prefsChanged(index: number) : boolean { if(this.notifications.length > 0 && this.initialNotifications.length > 0) { - this.status = this.errorCodes.LOADING; - this.savedMessage = ""; - this.notifications[index] = JSON.parse(JSON.stringify( this.initialNotifications[index] )); - this.status = this.errorCodes.DONE; - this.prefsChanged[index] = false; + if(JSON.stringify(this.notifications[index]) != JSON.stringify(this.initialNotifications[index])) { + return true; + } } + return false; } - } -/* - prefsChanged(index: number) : boolean { - if(this.notifications.length > 0 && this.initialNotifications.length > 0) { - if(JSON.stringify(this.notifications[index]) != JSON.stringify(this.initialNotifications[index])) { - return true; - } - } - return false; - } -*/ + */ ngOnDestroy() { - if(this.sub) { + if (this.sub) { this.sub.unsubscribe(); } } - handleErrors(err){ + handleErrors(err) { //this.showErrorMessage = true; //try{ - var code = ""; - if(!err.status) { - var error = err.json(); - code = error.code; - } else { - code = err.status; - } - this.status = this.errorMessages.getErrorCode(code); + var code = ""; + if (!err.status) { + var error = err.json(); + code = error.code; + } else { + code = err.status; } + this.status = this.errorMessages.getErrorCode(code); + } - private handleError(message: string, error) { - console.error("User mail notification preferences Page (for claims): "+message, error); - } + private handleError(message: string, error) { + console.error("User mail notification preferences Page (for claims): " + message, error); + } - //}catch (e) { - //console.log("Couldn't parse answer as json") - //this.showErrorMessage = true; - //} + //}catch (e) { + //console.log("Couldn't parse answer as json") + //this.showErrorMessage = true; + //} } diff --git a/login/adminLoginGuard.guard.ts b/login/adminLoginGuard.guard.ts index 7d3eb219..2118b75c 100644 --- a/login/adminLoginGuard.guard.ts +++ b/login/adminLoginGuard.guard.ts @@ -11,14 +11,40 @@ import { import {Observable} from 'rxjs'; import {Session} from './utils/helper.class'; import {LoginErrorCodes} from './utils/guardHelper.class'; +import {UserManagementService} from "../services/user-management.service"; +import {EnvironmentSpecificService} from "../utils/properties/environment-specific.service"; +import {filter, map, mergeMap} from "rxjs/operators"; @Injectable() export class AdminLoginGuard implements CanActivate{ - constructor(private router: Router) { + constructor(private router: Router, + private userManagementService: UserManagementService, + private propertiesService: EnvironmentSpecificService) { } - check(path: string): boolean { + check(path: string): Observable { + let errorCode = LoginErrorCodes.NOT_LOGIN; + const obs = this.propertiesService.subscribeEnvironment().pipe(mergeMap(properties => { + return this.userManagementService.getUserInfo(properties['userInfoUrl']).pipe(map( user => { + if(user) { + errorCode = LoginErrorCodes.NOT_ADMIN; + } + return Session.isPortalAdministrator(user); + })); + })); + obs.pipe(filter( isAdmin => !isAdmin)).subscribe( () => { + this.router.navigate(['/user-info'], { + queryParams: { + 'errorCode': errorCode, + 'redirectUrl': path + } + }); + }); + return obs; + } + + /* check(path: string): boolean { let loggedIn = false; let isAdmin = false; let errorCode = LoginErrorCodes.NOT_LOGIN; @@ -38,7 +64,7 @@ export class AdminLoginGuard implements CanActivate{ }); } return loggedIn && isAdmin; - } + }*/ canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable | boolean { return this.check(state.url); diff --git a/login/claimsCuratorGuard.guard.ts b/login/claimsCuratorGuard.guard.ts index e4574cfe..c59cf6dd 100644 --- a/login/claimsCuratorGuard.guard.ts +++ b/login/claimsCuratorGuard.guard.ts @@ -11,35 +11,37 @@ import { import {Observable} from 'rxjs'; import {Session} from './utils/helper.class'; import {LoginErrorCodes} from './utils/guardHelper.class'; +import {filter, map, mergeMap} from "rxjs/operators"; +import {EnvironmentSpecificService} from "../utils/properties/environment-specific.service"; +import {UserManagementService} from "../services/user-management.service"; @Injectable() export class ClaimsCuratorGuard implements CanActivate { - constructor(private router: Router) { + constructor(private router: Router, + private userManagementService: UserManagementService, + private propertiesService: EnvironmentSpecificService) { } - check(path: string): boolean { - let loggedIn = false; - let isAuthorized = false; + check(path: string): Observable |boolean { let errorCode = LoginErrorCodes.NOT_LOGIN; - - if (Session.isLoggedIn()) { - loggedIn = true; - if (Session.isClaimsCurator() || Session.isPortalAdministrator()) { - isAuthorized = true; - } else { - errorCode = LoginErrorCodes.NOT_ADMIN; - } - } - if (!loggedIn || !isAuthorized) { + const obs = this.propertiesService.subscribeEnvironment().pipe(mergeMap(properties => { + return this.userManagementService.getUserInfo(properties['userInfoUrl']).pipe(map( user => { + if(user) { + errorCode = LoginErrorCodes.NOT_ADMIN; + } + return Session.isClaimsCurator(user) || Session.isPortalAdministrator(user); + })); + })); + obs.pipe(filter( isAdmin => !isAdmin)).subscribe( () => { this.router.navigate(['/user-info'], { queryParams: { 'errorCode': errorCode, 'redirectUrl': path } }); - } - return loggedIn && isAuthorized; + }); + return obs; } canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable | boolean { diff --git a/login/loginGuard.guard.ts b/login/loginGuard.guard.ts index 0a9d59fa..e2f302e2 100644 --- a/login/loginGuard.guard.ts +++ b/login/loginGuard.guard.ts @@ -11,26 +11,33 @@ import { import {Observable} from 'rxjs'; import {Session} from './utils/helper.class'; import {LoginErrorCodes} from './utils/guardHelper.class'; +import {filter, map, mergeMap} from "rxjs/operators"; +import {CommunityService} from "../connect/community/community.service"; +import {UserManagementService} from "../services/user-management.service"; +import {EnvironmentSpecificService} from "../utils/properties/environment-specific.service"; @Injectable() export class LoginGuard implements CanActivate { - constructor(private router: Router) { + constructor(private router: Router, + private userManagementService: UserManagementService, + private propertiesService: EnvironmentSpecificService) { } - check(path: string): boolean { - let loggedIn = false; - if (Session.isLoggedIn()) { - loggedIn = true; - } - if (!loggedIn) { + check(path: string): Observable |boolean { + const loggedIn = this.propertiesService.subscribeEnvironment().pipe(mergeMap(properties => { + return this.userManagementService.isLoggedIn(properties['userInfoUrl']).pipe(map( isLoggedIn => { + return isLoggedIn; + })); + })); + loggedIn.pipe(filter( isLoggedIn => !isLoggedIn)).subscribe( () => { this.router.navigate(['/user-info'], { queryParams: { 'errorCode': LoginErrorCodes.NOT_LOGIN, 'redirectUrl': path } }); - } + }); return loggedIn; } diff --git a/login/user.component.html b/login/user.component.html index 3fce807c..5f6aa719 100644 --- a/login/user.component.html +++ b/login/user.component.html @@ -18,10 +18,10 @@ diff --git a/login/user.component.ts b/login/user.component.ts index 7748f646..3c0bb726 100644 --- a/login/user.component.ts +++ b/login/user.component.ts @@ -6,6 +6,7 @@ import {User,Session} from './utils/helper.class'; import {RouterHelper} from '../utils/routerHelper.class'; import {EnvProperties} from '../utils/properties/env-properties'; +import {UserManagementService} from "../services/user-management.service"; @Component({ selector: 'user', @@ -30,7 +31,8 @@ export class UserComponent { constructor( private router: Router, private route: ActivatedRoute, private _meta: Meta, - private _title: Title) { + private _title: Title, + private userManagementsService: UserManagementService) { var title = "OpenAIRE | Login"; this._title.setTitle(title); @@ -46,14 +48,18 @@ export class UserComponent { if( typeof document !== 'undefined') { this.server = false; } - this.loggedIn = Session.isLoggedIn(); - this.user = Session.getUser(); + this.userManagementsService.getUserInfo(this.properties.userInfoUrl).subscribe( user => { + this.user = user; + this.loggedIn = !!this.user; + }); this.errorMessage = ""; this.sub = this.route.queryParams.subscribe(params => { this.errorCode = params["errorCode"]; this.redirectUrl = params["redirectUrl"]; - this.loggedIn = Session.isLoggedIn(); - this.user = Session.getUser(); + this.userManagementsService.getUserInfo(this.properties.userInfoUrl).subscribe( user => { + this.user = user; + this.loggedIn = !!this.user; + }); this.errorMessage = ""; if(this.loggedIn && this.errorCode == '1'){ this.redirect(); @@ -124,8 +130,8 @@ export class UserComponent { } return formattedRoles.join(", "); } - isUSerManager(){ - return Session.isUserManager(); + isUserManager(){ + return Session.isUserManager(this.user); } } diff --git a/login/userMini.component.ts b/login/userMini.component.ts index 96130f76..234b131f 100644 --- a/login/userMini.component.ts +++ b/login/userMini.component.ts @@ -71,7 +71,7 @@ import{EnvProperties} from '../utils/properties/env-properties'; }) export class UserMiniComponent { - public user: User; + @Input() user: User; public loggedIn: boolean = false; public isAuthorized: boolean = false; @Input() public mobileView:boolean = false ; @@ -108,14 +108,9 @@ export class UserMiniComponent { if(!this.redirectUrl && location) { this.redirectUrl = location.pathname; } - if(Session.isLoggedIn()){ + if(this.user){ this.loggedIn = true; - this.user = Session.getUser(); - if(Session.isClaimsCurator() || Session.isPortalAdministrator()){ - this.isAuthorized = true; - } else { - this.isAuthorized = false; - } + this.isAuthorized = Session.isClaimsCurator(this.user) || Session.isPortalAdministrator(this.user); }else { this.loggedIn = false; @@ -126,7 +121,7 @@ export class UserMiniComponent { } logOut(){ - if(Session.isLoggedIn()){ + if(this.user){ Session.removeUser(); window.location.href = this.logOutUrl + StringUtils.URIEncode(location.href); diff --git a/login/utils/helper.class.ts b/login/utils/helper.class.ts index 9d978fc0..302cae40 100644 --- a/login/utils/helper.class.ts +++ b/login/utils/helper.class.ts @@ -126,7 +126,8 @@ export class Session{ } //Methods to check roles - public static isClaimsCurator():boolean { + // OLD + /* public static isClaimsCurator():boolean { var isAuthorized = false; if(Session.isLoggedIn()){ var roles = ["urn:geant:openaire.eu:group:Curator+-+Claim#aai.openaire.eu"] @@ -195,6 +196,33 @@ export class Session{ return isAuthorized; } return isAuthorized; + }*/ + + // NEW + + public static isClaimsCurator(user: User): boolean { + return user !== null && + user.role.indexOf('urn:geant:openaire.eu:group:Curator+-+Claim#aai.openaire.eu') !== -1; + } + + public static isCommunityCurator(user: User): boolean { + return user !== null && + user.role.indexOf('urn:geant:openaire.eu:group:Curator+-+Community#aai.openaire.eu') !== -1; + } + + public static isPortalAdministrator(user: User): boolean { + return user !== null && + user.role.indexOf('urn:geant:openaire.eu:group:Portal+Administrator#aai.openaire.eu') !== -1; + } + + public static isUserManager(user: User): boolean { + return user !== null && + user.role.indexOf('urn:geant:openaire.eu:group:User+Manager#aai.openaire.eu') !== -1; + } + + public static isRegisteredUser(user: User): boolean { + return user !== null && + user.role.indexOf('urn:geant:openaire.eu:group:Registered+User#aai.openaire.eu') !== -1; } diff --git a/sharedComponents/navigationBar.component.html b/sharedComponents/navigationBar.component.html index 0ac2c7f2..cf36c011 100644 --- a/sharedComponents/navigationBar.component.html +++ b/sharedComponents/navigationBar.component.html @@ -69,7 +69,7 @@ - +
@@ -196,7 +196,7 @@ - + diff --git a/sharedComponents/navigationBar.component.ts b/sharedComponents/navigationBar.component.ts index 9b9fe0e5..26c5a93b 100644 --- a/sharedComponents/navigationBar.component.ts +++ b/sharedComponents/navigationBar.component.ts @@ -1,6 +1,6 @@ import {Component, Input} from '@angular/core'; import {ActivatedRoute, Router} from '@angular/router'; -import {Session} from '../login/utils/helper.class'; +import {Session, User} from '../login/utils/helper.class'; import {ConfigurationService} from '../utils/configuration/configuration.service'; import {MenuItem, RootMenuItem} from './menu'; import {EnvProperties} from '../utils/properties/env-properties'; @@ -10,133 +10,138 @@ import {EnvProperties} from '../utils/properties/env-properties'; templateUrl: 'navigationBar.component.html' }) export class NavigationBarComponent { - @Input() portal:string = "connect"; - @Input() onlyTop:boolean ; - @Input() logoPath:string = "assets/common-assets/"; - @Input() userMenu:boolean = true; - @Input() showHomeMenuItem:boolean = false; + @Input() portal: string = "connect"; + @Input() onlyTop: boolean; + @Input() logoPath: string = "assets/common-assets/"; + @Input() userMenu: boolean = true; + @Input() showHomeMenuItem: boolean = false; @Input() communityId; - @Input() showCommunityName:boolean = false; - @Input() userMenuItems:MenuItem[] ; - @Input() menuItems:RootMenuItem [] ; - @Input() community: {id:string, name:string, logoUrl:string}; - @Input() showMenu:boolean = true; - @Input() homeurl:boolean = true; - @Input() properties:EnvProperties; - @Input() enableSearch:boolean = false; - @Input() searchRoute:string = "/search/find"; - @Input() searchPlaceHolder:string = "Search for research results"; - keyword:string = ""; + @Input() showCommunityName: boolean = false; + @Input() userMenuItems: MenuItem[]; + @Input() menuItems: RootMenuItem []; + @Input() community: { id: string, name: string, logoUrl: string }; + @Input() showMenu: boolean = true; + @Input() homeurl: boolean = true; + @Input() properties: EnvProperties; + @Input() user: User; + @Input() enableSearch: boolean = false; + @Input() searchRoute: string = "/search/find"; + @Input() searchPlaceHolder: string = "Search for research results"; + keyword: string = ""; public isAuthorized: boolean = false; - sub:any; - isClient:boolean = false; - showEntity ={}; - showPage ={}; - specialAnnouncementContent:string= null; + sub: any; + isClient: boolean = false; + showEntity = {}; + showPage = {}; + specialAnnouncementContent: string = null; activeRouteEnabled = false; - constructor( private router: Router, private route: ActivatedRoute, private config: ConfigurationService) { + constructor(private router: Router, + private route: ActivatedRoute, + private config: ConfigurationService) { } ngOnInit() { //console.log(this.menuItems); if (typeof document !== 'undefined') { - try{ + try { this.isClient = true; - }catch (e) { + } catch (e) { } } this.activeRouteEnabled = false; - this.sub = this.route.queryParams.subscribe(params => { + this.sub = this.route.queryParams.subscribe(params => { this.initialize(); }); } - ngOnDestroy(){ + + ngOnDestroy() { this.sub.unsubscribe(); } - initialize(){ + + initialize() { this.activeRouteEnabled = false; - if(Session.isLoggedIn() && (Session.isClaimsCurator() || Session.isPortalAdministrator())){ - this.isAuthorized = true; - }else { - this.isAuthorized = false; - } + this.isAuthorized = Session.isClaimsCurator(this.user) || Session.isPortalAdministrator(this.user); + if (this.properties.adminToolsAPIURL && this.communityId) { + this.config.getCommunityInformation(this.properties, this.communityId).subscribe(data => { + for (var i = 0; i < data['entities'].length; i++) { -if( this.properties.adminToolsAPIURL && this.communityId ){ - this.config.getCommunityInformation(this.properties, this.communityId ).subscribe(data => { - for(var i=0; i< data['entities'].length; i++){ - - this.showEntity[""+data['entities'][i]["pid"]+""] = data['entities'][i]["isEnabled"]; - } - for(var i=0; i< data['pages'].length; i++){ - this.showPage[data['pages'][i]["route"]] = data['pages'][i]["isEnabled"]; - - } - - }, - error => { - this.handleError("Error getting community information (e.g. pages,entities) for community with id: "+this.communityId, error); - }); - } - - } - onClick(id: string) { - var el: HTMLElement = document.getElementById(id); - el.classList.remove('uk-open'); - } - isEnabled(required, enabled){ - if(!required ){ - return true; - } - - - for(let requiredEntity of required){ - if(typeof enabled[requiredEntity] === "undefined" || enabled[requiredEntity] == false){ - return false; + this.showEntity["" + data['entities'][i]["pid"] + ""] = data['entities'][i]["isEnabled"]; } - } + for (var i = 0; i < data['pages'].length; i++) { + this.showPage[data['pages'][i]["route"]] = data['pages'][i]["isEnabled"]; + + } + + }, + error => { + this.handleError("Error getting community information (e.g. pages,entities) for community with id: " + this.communityId, error); + }); + } + + } + + onClick(id: string) { + var el: HTMLElement = document.getElementById(id); + el.classList.remove('uk-open'); + } + + isEnabled(required, enabled) { + if (!required) { return true; } - isAtleastOneEnabled(required, enabled){ - if(!required ||required.length == 0){ - return true; - } - var count = required.length; - for(let requiredEntity of required){ - if(typeof enabled[requiredEntity] === "undefined" || enabled[requiredEntity] == false){ - count --; - } - } - return (count > 0)?true:false; - } - private handleError(message: string, error) { - console.error("NavigationBar (component): "+message, error); - } - getCurrentRoute(){ - return this.router.url.split('?')[0]; - } - isTheActiveMenu(menu:RootMenuItem):boolean{ - let currentRoute = this.getCurrentRoute(); - if(!menu.rootItem.markAsActive){ + for (let requiredEntity of required) { + if (typeof enabled[requiredEntity] === "undefined" || enabled[requiredEntity] == false) { return false; } - if( currentRoute == menu.rootItem.route){ - this.activeRouteEnabled = true; - return true; - }else if(menu.items.length >0){ - for (let menuItem of menu.items){ - if(menuItem.route == currentRoute){ - this.activeRouteEnabled = true; - return true; - } - } + } + return true; + } + + isAtleastOneEnabled(required, enabled) { + if (!required || required.length == 0) { + return true; + } + + var count = required.length; + for (let requiredEntity of required) { + if (typeof enabled[requiredEntity] === "undefined" || enabled[requiredEntity] == false) { + count--; } + } + return (count > 0) ? true : false; + } + + private handleError(message: string, error) { + console.error("NavigationBar (component): " + message, error); + } + + getCurrentRoute() { + return this.router.url.split('?')[0]; + } + + isTheActiveMenu(menu: RootMenuItem): boolean { + let currentRoute = this.getCurrentRoute(); + if (!menu.rootItem.markAsActive) { return false; } + if (currentRoute == menu.rootItem.route) { + this.activeRouteEnabled = true; + return true; + } else if (menu.items.length > 0) { + for (let menuItem of menu.items) { + if (menuItem.route == currentRoute) { + this.activeRouteEnabled = true; + return true; + } + } + } + return false; + } } diff --git a/utils/properties/env-properties.ts b/utils/properties/env-properties.ts index 719f1483..4c274b9b 100644 --- a/utils/properties/env-properties.ts +++ b/utils/properties/env-properties.ts @@ -61,6 +61,7 @@ export class EnvProperties { logoutUrl; + userInfoUrl; cookieDomain;