Ways to dynamically authenticate in AuthGuard and return a true value

I am working on an auth guard that has multiple conditions, and I am looking for a way to dynamically return a true value. Here is the relevant code snippet:

auth.guard.ts

canLoad(route: Route, segments: UrlSegment[]): Observable<boolean>|Promise<boolean>|boolean {
    const isSuperAdmin = this.authService.getAuth().role === 'SUPERADMIN';
    const isAdmin = this.authService.getAuth().role === 'ADMIN';
    if (!isAdmin || !isSuperAdmin) {
      this.router.navigate(['/notifications']);
    }
    return true;  //I need assistance in returning true dynamically
}

Answer №1

To make a dynamic return based on certain conditions, you can define a boolean variable and update it as needed :

Here's an example :

    canLoad(route: Route, segments: UrlSegment[]): Observable<boolean>|Promise<boolean>|boolean {

        let dynamicReturn = false;

          const isSuperAdmin = this.authService.getAuth().role === 'SUPERADMIN';
            const isAdmin = this.authService.getAuth().role === 'ADMIN';
            if (!isAdmin || !isSuperAdmin) {

              //Update dynamicReturn value based on conditions
              dynamicReturn = true
              this.router.navigate(['/notifications']);
            }
            return dynamicReturn ;  //Returning dynamically updated value
        }

Answer №2

Instead of using [AuthGuard], I recommend renaming it to [AuthorizeGuard] as you are working with application user roles.

You can implement something similar to the following code snippet:

import { Injectable } from '@angular/core';
import { CanActivateChild, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthorizationService } from './authorization.service';
@Injectable({
    providedIn: 'root'
})
export class AuthorizeGuard implements CanActivateChild {


    constructor(private authorizeService: AuthorizationService, private router: Router) {
    }
    canActivateChild(
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): boolean {

        if (this.hasPermissions(route.data.roles)) {
            return true;
        } else {
            this.router.navigate(['/']);
        }
    }

    private hasPermissions(allowedRoles: string[]): boolean {
        const idxArray: number[] = [];
        allowedRoles.forEach((role: string) => {
            const idx: number = this.authorizeService.permissions.indexOf(role);
            if (idx !== -1) {
                idxArray.push(idx);
            }
        });
        if (idxArray.length > 0) {
            return true;
        } else {
            return false;
        }
    }


}

AuthorizationService is used to retrieve the login user permissions from an API in my case, it's an array list.

If the login user does not have the required permission from the array, it will return false.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering an issue with Angular where downloading a zip archive using the HttpClient API results in

Within our Angular5 web application, we are utilizing an API to retrieve a zip archive (Back-end is ASP.NET Core 2.1 using SharpZipLib). Previously, everything functioned correctly when using the old HTTP API provided by Angular :) However, after upgradin ...

The extensive magnetic scrolling functionality in Ionic 2 sets it apart from other frameworks

Hi everyone, I could really use some assistance! I've been working on developing an Ionic 2 App and my navigation setup is not too complex. I have a main menu where clicking on an item opens another menu with a submenu. From there, if I click on an i ...

The class function in the exported typescript logs that "this" is not defined

I am currently facing an issue with my TypeScript class where I am setting class values in a constructor and referencing them using "this" in a class method. While the .ts file compiles without any warnings, when I import the compiled .js file into another ...

Arranging Angular 5 elements by date

I'm seeking assistance with ordering a table of lessons by date in Angular 5. Unfortunately, the orderBy pipe is not available and existing solutions only work for numbers and strings. Here's the structure of my table: <tbody> <tr *ng ...

Exploring Angular's APP_INITIALIZER: Comparing Promises and Observables

I have implemented an Angular v4 application where I need to retrieve settings from the server before the app starts. This is achieved using the APP_INITIALIZER: { provide: APP_INITIALIZER, useFactory: initializeSettings, deps: [SettingsService], ...

In Angular, additional code blocks are executed following the subscription

I am facing an issue with my file upload function. After the file is uploaded, it returns the uploaded path which I then pass to a TinyURL function this.tinyUrl.shorten(data.url).subscribe(sUrl => { shortUrl=sUrl;});. However, there is a delay in receiv ...

Testing a function that involves multiple HTTP requests through unit testing

I am struggling with writing a unit test for a function that indirectly triggers multiple HTTP requests. The service I am testing has the following structure: /* content.service.ts */ import { Injectable } from "@angular/core" import { ApiService } from ...

Customize the height of individual carousel items in Primeng carousel

Hey there, I'm currently using the primeng carousel component and running into an issue where the carousel height is always based on the tallest item. I am looking to have an automatic height for each individual carousel item instead. Do you think th ...

Detecting changes in an object property that is bound to another object property - a comprehensive guide

In my application, I am facing a challenge with displaying navigation items based on user rules. This is how I have tried to implement it: I define an object with the necessary rules: rules: { canSeeProfile: true, canSeeAdminZone: false, ... ...

Exploring ways to exclude a column in a TypeORM entity while also providing the flexibility to make it optional for retrieval using the Find method

import {Entity, PrimaryGeneratedColumn, Column} from "typeorm"; @Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column() name: string; } i prefer not to include the password here as I want it to be returned to the client: ...

Retrieve the individuals within the delimiter

Looking for a solution to modify the characters within square brackets in a given string. For instance, I have a string that looks like "[A] [B] this is my [C] string". How can I update these bracketed characters by adding or removing brackets? ...

After executing the ng serve command, I encountered the following error message: "There has been an unhandled exception - Module '../dotjs/validate' could not be found."

**Oops! There was an unhandled exception: Module '../dotjs/validate' not found. **Here's a peek at my package.json file "dependencies": { "@angular/animations": "^8.1.1", ... "zone.js": "~0.9.1" }, " ...

Error in unit testing: Trying to access property 'pipe' of an undefined variable results in a TypeError

Recently, I've been faced with the challenge of writing a unit test for one of the functions in my component. The specific function in question is called 'setup', which internally calls another function named 'additionalSetup'. In ...

The 'innerText' property is not found in the 'Element' type

Currently, I am working with Typescript and Puppeteer. My goal is to extract the innerText from an element. const data = await page.$eval(selector, node => node.innerText); However, I encountered an error: The property 'innerText' is not ...

Typescript counterpart of a collection of key-value pairs with string keys and string values

Within the API I'm currently working with, the response utilizes a data type of List<KeyValuePair<string, string>> in C#. The structure appears as shown below: "MetaData": [ { "key": "Name", &q ...

Troubleshooting service unit testing challenges in Angular 2 rc5

@Injectable() export class Service1 { constructor( private s2 : Service2 ) { console.log( s2.name ); } } @Injectable() export class Service2 { public name: string = 'Hi'; } //------------Testing with Mocks------------- l ...

Tips for retrieving and presenting information from a JSON document in a React TypeScript application

I am struggling to display data in a list format using TypeScript. I am able to fetch the data but unable to display it properly. I am currently using map to iterate through an array of JSON objects. //json file [ { "id": "6s", ...

Angular does not display results when using InnerHtml

I'm currently in the process of creating a weather application with Angular, where I need to display different icons based on the weather data received. To achieve this functionality, I have developed a function that determines the appropriate icon to ...

What is the best way to inform TypeScript when my Type has been altered or narrowed down?

In my application, I have a class that contains the API code: export class Api { ... static requestData = async ( abortController: React.MutableRefObject<AbortController | null> ) => { // If previous request exists, cancel it if ...

There is a type error in the dynamic assignment in TypeScript. I have various data that need to be fetched from one another

const obj1 = { a: 1, b: "xx" }; const obj2 = { a: 2, b: "3", d: "hello" }; for (const key in obj1) { const _key = key as keyof typeof obj1; obj1[_key] = obj2[_key]; } x[_key] error Type 'string | number' is no ...