Karl Johan Vallner
Karl Johan Vallner

Reputation: 4310

Angular2 showing components based on user permissions

I've a simple question. How can I inject a common function into many components.

I have a component called add-users and I would like for this to be only seen by administrators. For this I have added a set of permissions to all users and I want to inject a common function into many components that checks wheter the user has a right to see them. Do not worry about hackers, because another check is done on the backend and even if people add permissions to themselves, they will still not be able to use the admin functionality.

Example:

<add-users [required-permissions]></add-users>

Upvotes: 0

Views: 2221

Answers (2)

Sergii Stotskyi
Sergii Stotskyi

Reputation: 5390

There is an isomorphic authorization library which is called CASL . You can read about its integration in Aurelia app:

https://medium.com/@sergiy.stotskiy/casl-based-authorization-in-aurelia-app-3e44c0fe1703

And do it in similar way via custom can pipe in Angular2+

Upvotes: 0

Karl Johan Vallner
Karl Johan Vallner

Reputation: 4310

JB Nizet had the closest answer.

I made it so that, whenever an user logs in all his/her permissions are sent over from the backend to the frontend and stored in a localStorage array.

Then I injected a global service class into my angular2 app

import { Injectable, Inject } from '@angular/core';
import { Observable } from "rxjs/Observable";

import globals = require('./../globals');

import { ShoppingCart } from './../Models/ShoppingCart';

@Injectable()
export class PermissionsEngine {
private userPermissions: Array<String> = Array<String>();
private permissionsString = "";

constructor()  {
    this.calcPermissions();
}

calcPermissions() {
    this.permissionsString = localStorage.getItem("permissions");
    if ( this.permissionsString ) {
        this.userPermissions = this.permissionsString.split(",");
    } else {
        this.userPermissions = new Array<String>();
    }
}

hasPermission( _slug: string ) {
    if ( this.userPermissions.indexOf( _slug ) != -1 ) {
        return true;
    }

    return false;
}
}

this can be injected into components and called anywhere from the app as such

<div *ngIf="_permissionsEngine.hasPermission('add_users')"></div>

Hope this helps someone!

Upvotes: 1

Related Questions