Angular Protectors: Stop unauthorized access to a URL while allowing authorized refresh

I've developed a Protection feature that blocks users from directly accessing a specific URL, and it's functioning correctly.

However, the issue arises when I try to refresh the page as the Protection feature ends up redirecting me.

Below is the code snippet:

export class NavigationGuard implements CanActivate {

  constructor(private router: Router) { }

  canActivate(): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    if (this.router.navigated) {
      return true
    } else {
      this.router.navigate(['/'])
      return false
    }
  }
  
}

I have discovered a method to capture a refresh event using the given code, but it conflicts with this.router.navigated, rendering it ineffective.

this.subscription = router.events.subscribe((event) => {
        if (event instanceof NavigationStart) {
          browserRefresh = !router.navigated;
        }
    });

Is there a way to reconcile these two behaviors in my Protection feature?

Answer №1

One way to ensure that a page can be accessed within an Angular app is by checking if the page has been refreshed. By using the logic of "is this page refreshed" in conjunction with this.router.navigated, you can verify the accessibility of the page.

Here is an example of how this can be implemented:

const isPageAccessedWithReload = (
      (window.performance.navigation && window.performance.navigation.type === 1) ||
        window.performance
          .getEntriesByType('navigation')
          .map((nav: any) => nav.type)
          .includes('reload')
    );
    return this.router.navigated || isPageAccessedWithReload

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

Cookies are not being sent by Angular 2

Currently, I am working on a project that involves frontend development using angular 2 and backend with symfony as the API. However, I am facing an issue where I need to send the PHPSESSID when making a request to symfony, but it is not happening as expec ...

Adding images to your SVG using Bobril is a simple process that can add visual

I have been attempting to insert an image into an SVG using Bobril, but the following code is not functioning as expected: { tag: 'svg', children: { tag: 'image', attrs: { 'xlink:href': &ap ...

Issue with Angular 2 Custom Pipe not Refreshing Unless Object is Saved

I recently created a custom Angular 2 pipe that formats a phone number from a 10-digit string to 'XXX-XXX-XXXX'. The pipe is functioning perfectly, but the issue arises when it fails to update in real-time during keypress; instead, it updates onl ...

Show specific elements on the navbar in Angular 2 based on user login status

Currently, I am working on my initial project in Angular 2 which involves user authentication and its related features. The process has been smooth and the documentation/examples have proved to be very helpful thus far. My current focus is on incorporatin ...

Exploring the communication between two components in Angular 2

My Angular components include: Create-Articles: used for creating articles. List Articles: utilized for listing all articles. The parent component is the Home Component. import { Component, OnInit } from '@angular/core'; @Component({ ...

Display embedded ng-template in Angular 6

I've got a template set up like this <ng-template #parent> <ng-template #child1> child 1 </ng-template> <ng-template #child2> child 2 </ng-template> </ng-template> Anyone know how t ...

TypeScript requires that when explicitly specifying the return type of a generator, the `Generator.prototype.return` function must accept

I am utilizing a generator function to serve as a consumer for accumulating strings: function *concatStrings(): Generator<void, string, string> { let result = ''; try { while (true) { const data = yield; result += data; ...

Changing the names of properties within a intricate JSON structure

I have a JSON data structure that is quite complex, like the one shown below: const json = '{"desc":"zzz", "details": { "id": 1, "name": "abc", "categoryDetails": { "cid": ...

Is there a way to end my session in nextAuth on NextJS 14?

Recently, I've started using Typscript with a NextJS14 project that utilizes NextAuth for authentication. While there weren't any errors in the JavaScript version of my code, I encountered an error when working with TypeScript. This is a snippet ...

The metadata for Company#companyTypesLinks could not be located. Please verify that the entity object has been correctly specified

I am facing an issue with the relationship between my entities. I have tried everything, but I still encounter the same problem. Here are my scripts: Company.entity.ts export class Company extends AppBaseEntity { @Column('text', { name: ' ...

A deep dive into TypeScript: enhancing a type by adding mandatory and optional fields

In this scenario, we encounter a simple case that functions well individually but encounters issues when integrated into a larger structure. The rule is that if scrollToItem is specified, then getRowId becomes mandatory. Otherwise, getRowId remains option ...

Reorganize code in JavaScript and TypeScript files using VSCode

Is there a way to efficiently organize the code within a .js / .ts file using Vscode? Specifically, when working inside a Class, my goal is to have static variables at the top, followed by variables, then methods, and so on automatically. I did some resea ...

What is the best way to arrange items by utilizing the Array index in JavaScript?

Currently, I am attempting to make the elements within this angular component cascade upon loading. The goal is to have them appear in a specific layout as shown in the accompanying image. I'm seeking guidance on how to write a function in the TypeSc ...

Guide to automatically opening a webview upon launching an ionic application

After encountering difficulties opening a login page from the desktop site with webview when my ionic app launches, I decided to create a separate page named login-check.page. On this page, I included a button that successfully opens the desktop login page ...

Unable to transfer variable from a function to the test in Protractor

Currently, I am working on a test to verify the amount of gold in my possession. The test is being conducted using TypeScript and Protractor. Within this testing scenario, I have a method named GetAmountOfChips: public static GetAmountOfChips(): PromiseL ...

Data not being retrieved by HTTP GET request

I encountered an issue with my API where I made three Get requests using the same function but different URLs to differentiate between them. However, even though the provider returns the data in steps, the page response function does not receive it and sho ...

The incorrect starting points for nested for loops

I'm facing an issue while utilizing a nested for loop to generate x and y coordinates for a method call. Strangely, the loop variables seem to be starting off at incorrect values when I check using console.log. What could be the reason behind this une ...

Generating an Observable that connects with a pre-existing function

Currently, I've been attempting to connect the onCompleteItem array function from the ng2-file-upload package with an RxJS Observable method that can be subscribed to. The function in question looks like this: onCompleteItem(item: FileItem, response ...

Is there a way to simulate the BeforeInstallPromptEvent for testing in Jasmine/Angular?

I'm currently working on testing a dialog component that manages the PWA install event triggered manually when a specific function is invoked. The goal is to handle the promise returned by the BeforeInstallPromptEvent.userChoice property. However, wh ...

Describing the implementation of UNO out parameters within definitions

The UNO API offers support for inout and out parameters. In this scenario, a variable is passed into a function, the function modifies the variable, and the updated value of the variable can be accessed outside the function. Javascript lacks native suppor ...