AMAN
AMAN

Reputation: 51

How to use ngx permission to protect admin Page in angular?

I have admin page Url and i want to protect it but i don't know how to use ngx-permissions in this case as i am new in angular.so can anyone please tell me how can i protect my admin page using angular. Here is my redirecting code written below:

if(this.userId === this.adminId){
              this.admin=true;
              this.router.navigate(['/admin']); }
            else{
            this.router.navigate(['/']);
            }

I am using AdminId and if it is matched with userId then i am redirecting the router to admin page.I don't know is it the only way to redirecting?So please tell also how can i navigate the router to admin page securely? Any suggestions will be appreciated.

Upvotes: 1

Views: 1868

Answers (1)

Jhonny Martínez
Jhonny Martínez

Reputation: 26

You can use guards with angular router, using the param canActivate in your routes, something like:

const routes: Routes = [      
{ path: 'admin', component: AdminComponent, canActivate: [AdminGuard] },
];

And the AdminGuard file can be:

Important: You just need to pass your params (userId and adminId) in the page url.

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

@Injectable()
export class CanActivateGuard implements CanActivate {

  constructor(
    public router: Router
  ) { }

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot,
  ) {
    const { userId, adminId } = route.queryParams;
    if (userId === adminId) {
      // this.router.navigate(['/admin']);
      return true; // This line allows user access to admin route
    }
    else {
      this.router.navigate(['/']);
      return false;
    }
  }
}

Upvotes: 1

Related Questions