@ngx-security/roles
TypeScript icon, indicating that this package has built-in type declarations

17.0.0 • Public • Published

ngx-security/roles

Installation

npm install --save @ngx-security/core @ngx-security/roles

Setup

Import SecurityCoreModule and SecurityRolesModule in app module.

@NgModule({
  imports: [
    BrowserModule,
    SecurityCoreModule.forRoot(),
    SecurityRolesModule.forRoot()
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}

Now you are ready to use it. See SecurityCoreModule for SubjectService implementation which provide authorities as roles.

Usage

Structural directives

<p *hasRole="'ROLE_1'">This should see users with ROLE_1</p>
<p *hasAnyRole="['ROLE_1','ROLE_2']">This should see users with ROLE_1 or ROLE_2</p>
<p *hasRoles="['ROLE_1','ROLE_2']">This should see users with ROLE_1 and ROLE_2</p>

Pipes

<p *ngIf="'ROLE_1' | hasRole">This should see users with ROLE_1</p>
<p *ngIf="['ROLE_1','ROLE_2'] | hasAnyRole">This should see users with ROLE_1 or ROLE_2</p>
<p *ngIf="['ROLE_1','ROLE_2'] | hasRoles">This should see users with ROLE_1 and ROLE_2</p>

Pipes with poetry

<p *ngIf="'user' | hasRole:'ROLE_1'">This should see users with ROLE_1</p>`
<p *ngIf="'user' | hasAnyRole:['ROLE_1','ROLE_2']">This should see users with ROLE_1 or ROLE_2</p>`
<p *ngIf="'user' | hasRoles:['ROLE_1','ROLE_2']">This should see users with ROLE_1 and ROLE_2</p>`

Advance setup

Implement custom custom SubjectRolesProvider class:

import { Injectable, OnDestroy } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { SubjectRolesProvider } from '@ngx-security/roles';

@Injectable()
export class MyRolesProvider extends SubjectRolesProvider implements OnDestroy {
                                   
    private roles: BehaviorSubject<string[]> = new BehaviorSubject(['ROLE_1', 'ROLE_2']);

    roles$: Observable<string[]> = this.roles.asObservable();

    constructor() {
        super();
    }
   
    ngOnDestroy(): void {
        this.roles.complete(); 
    }

    getRoles(): string[] {
        return this.roles.getValue();
    }
}

Import SecurityRolesModule in app module and set your custom SubjectRolesProvider.

@NgModule({
  imports: [
    BrowserModule,
    SecurityCoreModule.forRoot(),
    SecurityRolesModule.forRoot({
        subjectRoles: { provide: SubjectRolesProvider, useClass: MyRolesProvider }
    })
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}

Dependencies (1)

Dev Dependencies (0)

    Package Sidebar

    Install

    npm i @ngx-security/roles

    Weekly Downloads

    7

    Version

    17.0.0

    License

    MIT

    Unpacked Size

    100 kB

    Total Files

    24

    Last publish

    Collaborators

    • xbrancher