Permission Service

The PermissionService is a core service in an Angular application designed to manage user permissions. It provides methods to retrieve, set, and validate permissions, as well as an observable stream to reactively monitor permission changes. This service plays a critical role in implementing role-based access control (RBAC) and securing the application’s UI and functionality.

Features

  1. Permission Storage and Management:

    • Stores the user's permissions and provides methods to update them.

  2. Observable Permissions:

    • Exposes permissions as an Observable stream (permissions$), enabling reactive updates in components.

  3. Validation:

    • Provides a method to check if a user has a specific permission (hasPermission).

  4. Integration with HTTP:

    • Extends CommonHttpService, allowing for potential integration with APIs for fetching permissions.

Methods

1. getPermissions(): Observable<[ { permissions: string[] } ]>

  • Description:

    • Fetches the current permissions from an API or other sources.

    • Returns an observable containing an array of objects, each with a permissions property.

2. setPermissions(permissions: string[]): void

  • Description:

    • Updates the permissions stored in the service.

    • Also updates the permissions$ observable stream, ensuring that components react to changes.

  • Parameters:

    • permissions: An array of permission strings to set.

3. hasPermission(permission: string): boolean

  • Description:

    • Checks if the user has a specific permission.

  • Parameters:

    • permission: The permission string to check.

  • Returns: true if the permission exists, otherwise false.

Route Guards with canActivate

Angular Router provides several guard methods to control route navigation and access. These guards can be used with PermissionService to implement permission-based route protection. The four main guard methods are:

1. canActivate

Description:

Controls whether a route can be activated. This guard is executed before navigating to a route and can be used to check user permissions.

When to Use:

  • To protect routes that require specific permissions

  • To check authentication before allowing access

  • To redirect users based on their permissions

Implementation Example:

Usage in Routes:

Example from Codebase:

File: src/app/dashboard/dashboard.routes.ts (line 18)


Last updated