Chore: Auth Guard converted to CanActivateFn

This commit is contained in:
tanshu committed 2024-05-31 12:38:17 +05:30
1 parent a095ede3de
commit b6bb3dbcfd
43 files changed
+231 -398

No files matched your search

@@ -1,15 +1,17 @@
import { inject, TestBed } from '@angular/core/testing';
import { TestBed } from '@angular/core/testing';
import { CanActivateFn } from '@angular/router';
import { AuthGuard } from './auth-guard.service';
import { authGuard } from './auth-guard.service';
describe('authGuard', () => {
const executeGuard: CanActivateFn = (...guardParameters) =>
TestBed.runInInjectionContext(() => authGuard(...guardParameters));
describe('AuthGuard', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [AuthGuard],
});
TestBed.configureTestingModule({});
});
it('should be created', inject([AuthGuard], (service: AuthGuard) => {
expect(service).toBeTruthy();
}));
it('should be created', () => {
expect(executeGuard).toBeTruthy();
});
});
+20 -28
View File
@@ -1,34 +1,26 @@
import { Injectable } from '@angular/core';
import { Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { inject } from '@angular/core';
import { CanActivateFn } from '@angular/router';
import { Router } from '@angular/router';
import { ToasterService } from '../core/toaster.service';
import { AuthService } from './auth.service';
@Injectable({ providedIn: 'root' })
export class AuthGuard {
constructor(
private router: Router,
private authService: AuthService,
private toaster: ToasterService,
) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const { user } = this.authService;
const permission =
route.data['permission'] === undefined
? route.data['permission']
: route.data['permission'].replace(/ /g, '-').toLowerCase();
if (!user) {
// not logged in so redirect to login page with the return url
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
return false;
}
if (permission !== undefined && user.perms.indexOf(permission) === -1) {
this.toaster.show('Danger', 'You do not have the permission to access this area.');
return false;
}
// logged in so return true
return true;
export const authGuard: CanActivateFn = (route, state) => {
const user = inject(AuthService).user;
const permission =
route.data['permission'] === undefined
? route.data['permission']
: route.data['permission'].replace(/ /g, '-').toLowerCase();
if (!user) {
// not logged in so redirect to login page with the return url
inject(Router).navigate(['/login'], { queryParams: { returnUrl: state.url } });
return false;
}
}
if (permission !== undefined && user.perms.indexOf(permission) === -1) {
inject(ToasterService).show('Danger', 'You do not have the permission to access this area.');
return false;
}
// logged in so return true
return true;
};