import { Injectable } from '@angular/core' ; import { Right } from '../../management/models/right' ; import { BehaviorSubject , Observable } from 'rxjs' ; import { GroupService } from '../../management/services/group.service' ; import { Group } from '../../management/models/group' ; import { first , map } from 'rxjs/operators' ; @ Injectable ( { providedIn : 'root' } ) export class PermissionService { private currentUserRightListSubject : BehaviorSubject < Right [ ] > ; public currentUserRightList : Observable < Right [ ] > ; constructor ( private groupService ) { this . currentUserRightListSubject = new BehaviorSubject < Right [ ] > ( JSON . parse ( localStorage . getItem ( 'current-user-rights' ) ) ) ; this . currentUserRightList = this . currentUserRightListSubject . asObservable ( ) ; } public get currentUserRights ( ) : Right [ ] { if ( this . currentUserRightListSubject . value == null ) { return [ ] ; } return this . currentUserRightListSubject . value ; } public storeUserRights ( groupID ) { return this . groupService . getGroup ( groupID ) . pipe ( map ( group => { localStorage . setItem ( 'current-user-rights' , JSON . stringify ( group . rights ) ) ; this . currentUserRightListSubject . next ( group . rights ) ; return group ; } ) ) ; } public clearUserRightStorage ( ) { localStorage . removeItem ( 'current-user-rights' ) ; this . currentUserRightListSubject . next ( null ) ; } public hasRight ( rightName ) { return ! ! this . currentUserRights . find ( right => right . name === rightName ) ; } public hasExtendedRight ( rightName ) { let status = false ; rightName = rightName . substring ( 0 , rightName . lastIndexOf ( '.' ) ) ; if ( this . hasRight ( `${ rightName }.*` ) ) { status = true ; } else { if ( rightName === 'base' ) { return false ; } status = this . hasExtendedRight ( rightName ) ; } return status ; } }