Code Monkey home page Code Monkey logo

ngx-role-permissions's Introduction

ngx-role-permissions

npm version Build Status

Permission and roles based access control for your angular(angular 6,7,8+) applications

Documentation and examples

v2.0.0 have critical changes

see CHANGELOG.MD

Demo

[Demo ngx-role-permissions] (https://stackblitz.com/edit/ngx-role-permissions)

Installation

To install this library, run:

$ npm install ngx-role-permissions --save

Consuming library

You can import library in any Angular application by running:

$ npm install ngx-role-permissions  --save

and then from your Angular AppModule:

use NgxPermissionModule with withElements in any of your modules use LockTypes.UNLOCKABLE provide roles for which elements will be available LockTypes.UNLOCKABLE tells if current element will be block with specified roles

as anther aproach provide PERMISSION_CONFIG_TOKEN token with doorlock use lockWith declaration to declare blocking keys use unlockWith as an opposite to lockWith

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

// Import your library
import { NgxPermissionModule, LockTypes, PERMISSION_CONFIG_TOKEN, doorlock } from 'ngx-role-permissions';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,

    // Specify your library as an import
     NgxPermissionModule.withElements([
       {name: 'yourElement1', lockType: LockTypes.UNLOCKABLE, keys: ['user', 'admin']},
       {name: 'yourElement2', lockType: LockTypes.LOCKABLE, keys: ['user']},
     ]),
  ],
  {
      provide: PERMISSION_CONFIG_TOKEN,
      multi: true,
      useValue: [
        doorlock(PermElementTypes.PAGE_ELEMENT).lockWith(['admin']),
        doorlock(PermElementTypes.CHILD_ONE).unlockWith(['user', 'admin']),
      ],
    }
  bootstrap: [AppComponent]
})
export class AppModule { }

Providing initial roles: INITIAL_ROLES is multitoken that can provide initial roles

@NgModule({
  ...
  imports: [
    // Specify your library as an import
     NgxPermissionModule.withElements([
       ...
     ]),
  ],
  providers: [
      provide: INITIAL_ROLES,
      multi: true,
      useValue: ['user'], //your roles
  ]
})
export class AppModule { }

SharedModule

If you use a SharedModule that you import in multiple other feature modules, you can export the NgxPermissionModule to make sure you don't have to import it in every module. NgxPermissionModule with or without withElementsnotations provides canPermit and canNotPermit directive so you should import it in every module you use permission directives.

@NgModule({
    exports: [
        CommonModule,
        NgxPermissionModule,
    ]
})
export class SharedModule { }

Once your library is imported, you can use its components, directives and pipes in your Angular application:

Import service to the main application and load permissions

import { Component, OnInit } from '@angular/core';
import { PermissionService } from 'ngx-role-permissions';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'ngx-role-permissions';

  constructor(
    private permissionService: PermissionService,
  ) {}

  public ngOnInit(): void {
    this.permissionService.setRoles([
      'user',
    ]);

    // append role
    this.permissionService.addRole('admin');

    // remove role
    this.permissionService.removeRole('admin');
  }
}

Usage in templates

*canPermit check if element roles includes current user role

<div class="element-two" *canPermit="'yourFeatureElement1'">
    Feature element one directive example
</div>

*canNotPermit check if element roles excludes current user role

<div class="element-two" *canNotPermit="'yourFeatureElement1'">
    Feature element one directive example
</div>

Managing permissions

Usage in routing guards: permissionConfig placed in data declare route configuration. permission element - name of element which defined in module. redirectRoute - router path to redirect page if current route is blocked. If redirectRoute was not defined no redirect will be done

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { PermissionGuard } from 'ngx-role-permissions';

const routes: Routes = [
  {
    path: 'one',
    component: ChildComponent1,
    canActivate: [PermissionGuard],
    data: {
      permissionConfig: {
        permissionElement: 'yourFeatureElement2',
      }
    }
  },
  {
    path: 'two',
    component: ChildComponent2,
    canActivate: [PermissionGuard],
    data: {
      permissionConfig: {
        permissionElement: 'yourFeatureElement2',
        redirectRoute: '/dashboard',
      }
    }
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class ChildTwoRoutingModule { }

Usage in custom directives/guards/components etc.

@Directive({
  selector: '[canAccess]',
})
export class CanPermitDirective implements OnChanges, OnDestroy {
  private permissionSubscription: SubscriptionLike;

  constructor(
    private permissionService: PermissionService,
    private viewContainer: ViewContainerRef,
    private templateRef: TemplateRef<any>,
  ) {}

  @Input() canAccess: string;

  public ngOnChanges(changes: SimpleChanges): void {
    this.initPermissionCheck(changes.canPermit.currentValue);
  }

  public ngOnDestroy(): void {
    this.permissionSubscription.unsubscribe();
    this.permissionSubscription = null;
  }

  private initPermissionCheck(elementName: string): void {
    if (!!this.permissionSubscription) {
      this.permissionSubscription.unsubscribe();
      this.permissionSubscription = null;
    }

    this.permissionSubscription = this.permissionService.canAccess(elementName)
      .subscribe((res: boolean) => {
        if (!!res && !!this.templateRef) {
          this.viewContainer.clear();
          this.viewContainer.createEmbeddedView(this.templateRef, {});
        } else {
          this.viewContainer.clear();
        }
      });
  }
}

For google

angular permissions, angular 6 permissions, angular permissions, angular 6 permissions ng2 permissions ng permissions ng-permissions ng2-permissions angular2 permissions angular4 permissions angular 5 permissions

ngx-role-permissions's People

Contributors

dependabot[bot] avatar grachpower avatar vagrantai-c avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

ngx-role-permissions's Issues

Synchronous snapshot service

Is your feature request related to a problem? Please describe.
It is impossible to use fully reactive service in routes token, since ROUTES does not provide promise/observable return type

Describe the solution you'd like
Implement PermissionSnapshotService that provides same methods but with synchronous return types

Describe alternatives you've considered
Should it be in PermissionService? Probably it would be better for separate service for better tree shaking.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.