GithubHelp home page GithubHelp logo

rombru / ngx-security Goto Github PK

View Code? Open in Web Editor NEW

This project forked from mselerin/ngx-security

0.0 0.0 0.0 9.6 MB

Security directives for your Angular application to show/hide elements based on a user roles / permissions.

License: MIT License

JavaScript 2.87% TypeScript 93.90% CSS 0.15% HTML 3.08%

ngx-security's Introduction

Ngx-Security

License: MIT npm CI codecov

๐Ÿ” Security directives for your Angular application to show/hide elements based on a user roles / permissions.

View changelog

View migration guide

Installation

Install the library with:

npm install ngx-security --save

Then import it in your AppModule:

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

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

// Import your library
import { NgxSecurityModule } from 'ngx-security';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    
    // Importing ngx-security module
    NgxSecurityModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Usage

The security directives use a security state controlled by the NgxSecurityService.
You need to set/change this state to use the directives:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { NgxSecurityService } from 'ngx-security';

@Component({
  selector: 'app-sample',
  templateUrl: './sample.component.html'
})
export class SampleComponent
{
  constructor(
    private http: HttpClient,
    private security: NgxSecurityService
  ) {}

  login() {
    this.security.setAuthenticationChecker(() => {
      return of(true);
    });
    
    this.security.setPermissionChecker((perm: string) => {
      return this.http.get(`/api/auth/permissions/has/${perm}`).pipe(
        map(() => true)
      );
    });
  }
  
  logout() {
    // Reset the security state to it's initial value
    this.security.reset();
  }
}

Of course, you can change the security state wherever and whenever you want !

You can now use the differents directives and the guard.

Directives

IsAuthenticated

<div *secuIsAuthenticated>I'm authenticated !</div>

IsAnonymous

<div *secuIsAnonymous>I'm an anonymous user (not authenticated)</div>

HasRoles / HasPermissions / IsMemberOf

<div *secuHasRoles="'ADMIN'">I have the role 'ADMIN'</div>
<div *secuHasRoles="['CREATOR', 'EDITOR']; else roleElse">I have the role 'CREATOR' and 'EDITOR'</div>
<ng-template #roleElse>
  <div>I don't have the roles</div>
</ng-template>

HasAnyRoles / HasAnyPermissions / IsMemberOfAny

<div *secuHasAnyRoles="['CREATOR', 'EDITOR']; else roleElse">I have the role 'CREATOR' or 'EDITOR'</div>
<ng-template #roleElse>
  <div>I don't have the roles</div>
</ng-template>

HasNotRoles / HasNotPermissions / IsNotMemberOf

<div *secuHasNotRoles="'POWERUSER'">I don't have the role 'POWERUSER'</div>

Route Guard

The NgxSecurityGuard can prevent an unauthorized user to load / access parts of your application.

import {
  ActivatedRouteSnapshot,
  Route, Routes,
  RouterStateSnapshot
} from '@angular/router';

import { NgxSecurityGuard } from 'ngx-security';

export const ROUTES: Routes = [
  {
    path: 'secured-page',
    canActivate: [ NgxSecurityGuard ],
    data: {
      security: {
        isAuthenticated: true,
        hasAllRoles: ['ADMIN', 'USER'],
        redirectTo: '/access-denied',
        unauthorizedHandler: (route: Route | ActivatedRouteSnapshot, state?: RouterStateSnapshot) => {
          console.warn('No, no, no, you cannot access this !');
        }
      }
    },
    component: SecuredComponent
  }
];

Tips

Log unauthorized access

You can use the unauthorizedHandler to log unauthorized access to route path :

unauthorizedHandler: (route: Route | ActivatedRouteSnapshot, state?: RouterStateSnapshot) => {
  let path = (state ? state.url : null);
    if (!path && route) {
      path = '/' + (route as Route).path;
    }
  
    console.warn('Unauthorized access', path);
}

Contributing

Feel free to introduce a feature request, an issue or a pull request. ๐Ÿ‘Œ

Changelog

Changelog is available here.

License

MIT

ngx-security's People

Contributors

dependabot[bot] avatar mselerin avatar

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.