1561187590
Managing User Permissions in an Angular Application - In this story, I want to share an alternative way to implement permission management by using a neat library which is called CASL…
Modern applications usually displays only what is visible to the user based on their role. For example, a guest user may read stories but can’t write comments on Medium. Or another example, an authorized user can write and remove drafts. But that user is not allowed to see or remove somebody’s else drafts. And that’s pretty reasonable, isn’t it? :)
It all sounds cool but sometimes managing such accessibility may become a nightmare. You probably have written or seen code like this before:
<div *ngIf="loggedInUser.role === ADMIN || user.auth && post.author === loggedInUser.id">
<button (click)="deletePost()">Delete</button>
</div>
Later, this code is spread over the application and becomes a big problem when you need to add a new role in the app or change permissions of existing role. Eventually you need to change some of *ngIf
checks or in the worst case, change them all.
In this story, I want to share an alternative way to implement permission management by using a neat library which is called CASL*.*It makes managing user permissions much simpler, and allows to rewrite the previous example to:
<div *ngIf="post | can: 'delete'">
<button (click)="deletePost()">Delete</button>
</div>
First time you’ve heard about CASL? You may want to read “What is CASL?”.
Demo application
To illustrate how to use CASL, I decided to use well known Todo appication with small additions:
There are two roles in application:
This logic is defined by using AbilityBuilder
class which allows to define user permissions by using declarative function calls:
export function defineAbilitiesFor(role) {
const { can, rules } = AbilityBuilder.extract()
if (role === 'admin') {
can('manage', 'all')
} else {
can('read', 'all')
can('manage', 'Todo', { assignee: 'me' })
}
return rules
}
In order to understand this function, we need to dive a bit deeper into CASL details. To do this, let’s go through each line of defineAbilitiesFor(role)
function.
AbilityBuilder.extract()
creates an instance of AbilityBuilder
and extracts rules
array and its can
, cannot
methods. With help of can
(or cannot
which is not used here), it’s possible to define user permissions. can
(and cannot
) both accepts 4 arguments, 2 of which are required: action name and subject name. Action name represents a user’s action in application (in most cases it will be standard CRUD) and subject name represents model name which this rule is defined for.
Let’s take a look a the code again.
If role
argument of defineAbilitiesFor(role)
equals admin
, then user can do anything in the system (i.e., super admin rights). This is specified by can('manage', 'all')
statement. As I said before the first argument is an action name, manage
is a special keyword which represents any action in the system. And the second argument is a subject name, in this case it’s all
, which is a reserved alias for any subject name. So, if user has role admin
he can perform any action on any model.
In case user is not an admin, he can read
any model (this is specified by can('read', 'all')
) and can do any action on instances of Todo
model where model’s assignee
property equals to me
(i.e., can('manage', 'Todo', { assignee: 'me' })
).
As you can see, the last permission declaration has 3 arguments. The third arguments represents conditions
object. In this case, it clarifies which instances of Todo
user is allowed to manage.
To understand it clearly, let’s look at this example:
class Todo {
constructor({ title, assignee }) {
this.title = title;
this.assignee = assignee;
}
}
const myTodo = new Todo({
title: "buy food",
assignee: "me"
});
const johnTodo = new Todo({
title: "read the book",
assignee: "John"
});
const ability = new Ability(defineAbilitiesFor("member"));
console.log("can read my todo?", ability.can("read", myTodo)); // true
console.log("can close my todo?", ability.can("close", myTodo)); // true
console.log("can read John's todo", ability.can("read", johnTodo)); // true
console.log("can close John's todo?", ability.can("close", johnTodo)); // false
Here I created a separate class Todo
which represents a task to be done. This class accepts an object which must contain 2 fields: task’s title and who should work on this task. Later, I create 2 instances of Todo
class: 1 that represent task assigned to me
(remember conditions object?) and another one which is assigned to John
. I also create an Ability
instance with permissions for user with member
role.
Finally, I check permissions on these 2 todos. As you can see ability.can("read", myTodo)
and ability.can("close", myTodo)
returns true
, this is because early we defined that users who are not admins can do anything with tasks assigned to them (i.e., can('manage', 'Todo', { assignee: 'me' })
). Due to exactly the same reason, ability.can("close", johnTodo)
returns false
because we can only read his todo not close (i.e., can('read', 'all')
).
Do you see how closely explanation in console.log
reflects the actual check? They are almost identical (except that first one just a string and the last one do a complex permission check :)):
console.log(
"can read my todo?",
ability.can("read", myTodo)
)
Of course, now some of you may have questions like these:
conditions
object? You can learn about this in documentation here.ability.can(action, subject)
. You can learn about this here.CASL is shipped together with complementary package for Angular 2+. So, you can quickly add it into your Angular app.
Let’s start from installation
npm i @casl/ability @casl/angular
# or
yarn add @casl/ability @casl/angular
Later, include AbilityModule
in your AppModule
(use
AbilityModule.forRoot()
if you include it in root AppModule
):
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AbilityModule } from '@casl/angular';
import { Ability } from '@casl/ability';
import { defineAbilitiesFor, createAbility } from '../services/ability';
import { AppRoutingModule } from './routing.module';
@NgModule({
declarations: [
...
],
imports: [
...,
BrowserModule,
AppRoutingModule,
AbilityModule.forRoot(),
],
providers: [
{ provide: Ability, useFactory: createAbility }
],
bootstrap: [App]
})
export class AppModule { }
@casl/angular
provides the empty instance of Ability
by default. Here I specified own provider which defines Ability
based on provided rules (i.e., permissions). Alternatevely it’s possible to update rules of provided by default instance
Afterwards, you can inject Ability
instance in your component to check permissions or update them:
import { Component, Input } from '@angular/core';
import { Ability } from '@casl/ability';
import { defineAbilitiesFor } from '../../services/ability';
@Component({
selector: 'todo-footer',
template: `
...
<ul class="filters">
<li class="help">Switch roles</li>
<li><a href="#" [class.selected]="role == 'admin'" (click)="setRole('admin')">Admin</a></li>
<li><a href="#" [class.selected]="role == 'member'" (click)="setRole('member')">Member</a></li>
</ul>
...
`,
})
export default class TodoFooter {
@Input() items = [];
role = 'member';
constructor(private ability: Ability) {}
setRole(name) {
if (this.role !== name) {
this.role = name;
this.ability.update(defineAbilitiesFor(name))
}
}
}
Alternatevely you can use can
pipe in templates for simple checks (more details here). So, you can write code like this in Angular’s templates:
<header class="header">
<h1>{{ title }}</h1>
<todo-form (newTodo)="addTodo($event)" *ngIf="'Todo' | can: 'create'"></todo-form>
</header>
With that, we have a really nice way to manage permissions in Angular app. The full example of the Angular based app with CASL can be found on github or codesandbox:
If you like CASL, please star it on github and share the article with your friends :)
#angular
1595344320
Corona Virus Pandemic has brought the world to a standstill.
Countries are on a major lockdown. Schools, colleges, theatres, gym, clubs, and all other public places are shut down, the country’s economy is suffering, human health is on stake, people are losing their jobs and nobody knows how worse it can get.
Since most of the places are on lockdown, and you are working from home or have enough time to nourish your skills, then you should use this time wisely! We always complain that we want some ‘time’ to learn and upgrade our knowledge but don’t get it due to our ‘busy schedules’. So, now is the time to make a ‘list of skills’ and learn and upgrade your skills at home!
And for the technology-loving people like us, Knoldus Techhub has already helped us a lot in doing it in a short span of time!
If you are still not aware of it, don’t worry as Georgia Byng has well said,
“No time is better than the present”
– Georgia Byng, a British children’s writer, illustrator, actress and film producer.
No matter if you are a developer (be it front-end or back-end) or a data scientist, tester, or a DevOps person, or, a learner who has a keen interest in technology, Knoldus Techhub has brought it all for you under one common roof.
From technologies like Scala, spark, elastic-search to angular, go, machine learning, it has a total of 20 technologies with some recently added ones i.e. DAML, test automation, snowflake, and ionic.
Every technology in Tech-hub has n number of templates. Once you click on any specific technology you’ll be able to see all the templates of that technology. Since these templates are downloadable, you need to provide your email to get the template downloadable link in your mail.
These templates helps you learn the practical implementation of a topic with so much of ease. Using these templates you can learn and kick-start your development in no time.
Apart from your learning, there are some out of the box templates, that can help provide the solution to your business problem that has all the basic dependencies/ implementations already plugged in. Tech hub names these templates as xlr8rs (pronounced as accelerators).
xlr8rs make your development real fast by just adding your core business logic to the template.
If you are looking for a template that’s not available, you can also request a template may be for learning or requesting for a solution to your business problem and tech-hub will connect with you to provide you the solution. Isn’t this helpful 🙂
To keep you updated, the Knoldus tech hub provides you with the information on the most trending technology and the most downloaded templates at present. This you’ll be informed and learn the one that’s most trending.
Since we believe:
“There’s always a scope of improvement“
If you still feel like it isn’t helping you in learning and development, you can provide your feedback in the feedback section in the bottom right corner of the website.
#ai #akka #akka-http #akka-streams #amazon ec2 #angular 6 #angular 9 #angular material #apache flink #apache kafka #apache spark #api testing #artificial intelligence #aws #aws services #big data and fast data #blockchain #css #daml #devops #elasticsearch #flink #functional programming #future #grpc #html #hybrid application development #ionic framework #java #java11 #kubernetes #lagom #microservices #ml # ai and data engineering #mlflow #mlops #mobile development #mongodb #non-blocking #nosql #play #play 2.4.x #play framework #python #react #reactive application #reactive architecture #reactive programming #rust #scala #scalatest #slick #software #spark #spring boot #sql #streaming #tech blogs #testing #user interface (ui) #web #web application #web designing #angular #coronavirus #daml #development #devops #elasticsearch #golang #ionic #java #kafka #knoldus #lagom #learn #machine learning #ml #pandemic #play framework #scala #skills #snowflake #spark streaming #techhub #technology #test automation #time management #upgrade
1598940617
Angular is a TypeScript based framework that works in synchronization with HTML, CSS, and JavaScript. To work with angular, domain knowledge of these 3 is required.
In this article, you will get to know about the Angular Environment setup process. After reading this article, you will be able to install, setup, create, and launch your own application in Angular. So let’s start!!!
For Installing Angular on your Machine, there are 2 prerequisites:
First you need to have Node.js installed as Angular require current, active LTS or maintenance LTS version of Node.js
Download and Install Node.js version suitable for your machine’s operating system.
Angular, Angular CLI and Angular applications are dependent on npm packages. By installing Node.js, you have automatically installed the npm Package manager which will be the base for installing angular in your system. To check the presence of npm client and Angular version check of npm client, run this command:
· After executing the command, Angular CLI will get installed within some time. You can check it using the following command
Now as your Angular CLI is installed, you need to create a workspace to work upon your application. Methods for it are:
To create a workspace:
#angular tutorials #angular cli install #angular environment setup #angular version check #download angular #install angular #install angular cli
1593184320
What is Angular? What it does? How we implement it in a project? So, here are some basics of angular to let you learn more about angular.
Angular is a Typescript-based open-source front-end web application platform. The Angular Team at Google and a community of individuals and corporations lead it. Angular lets you extend HTML’s syntax to express your apps’ components clearly. The angular resolves challenges while developing a single page and cross-platform applications. So, here the meaning of the single-page applications in angular is that the index.html file serves the app. And, the index.html file links other files to it.
We build angular applications with basic concepts which are NgModules. It provides a compilation context for components. At the beginning of an angular project, the command-line interface provides a built-in component which is the root component. But, NgModule can add a number of additional components. These can be created through a template or loaded from a router. This is what a compilation context about.
Components are key features in Angular. It controls a patch of the screen called a view. A couple of components that we create on our own helps to build a whole application. In the end, the root component or the app component holds our entire application. The component has its business logic that it does to support the view inside the class. The class interacts with the view through an API of properties and methods. All the components added by us in the application are not linked to the index.html. But, they link to the app.component.html through the selectors. A component can be a component and not only a typescript class by adding a decorator @Component. Then, for further access, a class can import it. The decorator contains some metadata like selector, template, and style. Here’s an example of how a component decorator looks like:
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss']
})
Modules are the package of functionalities of our app. It gives Angular the information about which features does my app has and what feature it uses. It is an empty Typescript class, but we transform it by adding a decorator @NgModule. So, we have four properties that we set up on the object pass to @NgModule. The four properties are declarations, imports, providers, and bootstrap. All the built-in new components add up to the declarations array in @NgModule.
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
HttpClientModule,
AppRoutingModule,
FormsModule
],
bootstrap: [AppComponent]
})
Data Binding is the communication between the Typescript code of the component and the template. So, we have different kinds of data binding given below:
#angular #javascript #tech blogs #user interface (ui) #angular #angular fundamentals #angular tutorial #basics of angular
1625142062
AngularJS was introduced in the year 2009, by Google. AngularJS is a software framework used worldwide by developers. The entire base of this framework is open source. AngularJS has gained popularity among developers because of how it has become for them to create web applications. AngularJS helps in building apps that require less work and reduces the use of unnecessary codes. AngularJS application development is a javascript framework. AngularJS has a clear goal to make the entire process simpler, it also helps app development process and operations as much as it could. AngularJS is used for building applications that support MVC (model view controller) and SPAs (single page web apps) coding and programming structures. AngularJS has been used by some of the top companies in the world to simplify their app development process, like, Google, Paypal, Udemy, mobile site in iPad for HBO, etc. To read more click on the link.
#hire angular js developer #hire dedicated angular js developer #angular js application development #hire dedicated angular js team #hire best angular js application developer
1592667240
Learn how to boost your Angular application speed by selectively reacting to performance sensitive events. To do that we’ll implement a few event plugins and simplify them with decorators.
#angular #angular-zone #change-detection #event-manager #event-plugin-manager