Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(guard): guards are now fixed and redirect to login and dashboard … #45

Merged
merged 4 commits into from
Sep 9, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions api-config/api-url.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export const environment = {
apiUrl: 'https://localhost:44322',
// apiUrl: 'http://localhost:8085',
// apiUrl: 'https://localhost:44322',
apiUrl: 'http://localhost:8085',
};
22 changes: 8 additions & 14 deletions src/app/app-routing.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { MainPageComponent } from './user/components/dashboard/main-page/main-pa
import { ManageAccountComponent } from './user/components/dashboard/manage-account/manage-account.component';
import { DataAnalysisComponent } from './graph/components/data-analysis/data-analysis.component';
import { ManageUsersComponent } from './user/components/dashboard/manage-users/manage-users.component';
import { AppComponent } from './app.component';
import { AuthGuard } from './guards/auth/auth.guard';
import { PermissionGuard } from './guards/permissions/permission.guard';
import { AddGraphComponent } from './graph/components/add-graph/add-graph.component';
Expand All @@ -15,11 +14,14 @@ import { CategoryComponent } from './graph/components/category/category.componen
import { RecoverPassFormComponent } from './user/components/login/recover-pass-form/recover-pass-form.component';
import { LoginFormComponent } from './user/components/login/login-form/login-form.component';
import { ResetPasswordComponent } from './user/components/login/reset-password/reset-password.component';
import { LoginGuard } from './guards/auth/login.guard';

const routes: Routes = [
{ path: '', redirectTo: '/login', pathMatch: 'full' },
{
path: '',
component: LoginComponent,
canActivate: [LoginGuard],
children: [
{
path: 'recover-password',
Expand All @@ -30,16 +32,9 @@ const routes: Routes = [
path: 'login',
component: LoginFormComponent,
title: 'StarData | Login',
// canActivate: [AuthGuard],
},
],
},
// {
// path: 'login',
// component: LoginComponent,
// title: 'StarData | Login',
// canActivate: [AuthGuard],
// },
{
path: 'dashboard',
component: DashboardComponent,
Expand All @@ -56,7 +51,7 @@ const routes: Routes = [
path: 'manage-users',
component: ManageUsersComponent,
title: 'StarData | Manage Users',
data: { permission: undefined },
data: { permission: 'Register' },
},
{
path: 'manage-account',
Expand All @@ -67,21 +62,25 @@ const routes: Routes = [
path: 'data-analysis',
component: DataAnalysisComponent,
title: 'StarData | Data Analysis',
data: { permission: 'GetNodesAsync' },
},
{
path: 'add-graph',
component: AddGraphComponent,
title: 'StarData | Add Graph',
data: { permission: 'UploadNodeFile' },
},
{
path: 'assign-file',
component: AssignFileComponent,
title: 'StarData | Assign File',
data: { permission: 'AccessFileToUser' },
},
{
path: 'manage-category',
component: CategoryComponent,
title: 'StarData | Manage Category',
data: { permission: 'GetCategories' },
},
],
},
Expand All @@ -90,11 +89,6 @@ const routes: Routes = [
component: ResetPasswordComponent,
title: 'StarData | Reset Password',
},
{
path: '',
component: AppComponent,
canActivate: [AuthGuard],
},
];

@NgModule({
Expand Down
26 changes: 4 additions & 22 deletions src/app/guards/auth/auth.guard.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ describe('AuthGuard', () => {
| UrlTree
| Observable<boolean | UrlTree>
| Promise<boolean | UrlTree>,
done: DoneFn,
done: DoneFn
) {
if (result instanceof Observable) {
result.subscribe((value) => {
Expand Down Expand Up @@ -78,25 +78,7 @@ describe('AuthGuard', () => {

authService.getPermissions.and.returnValue(of(mockPermissions));

const result = guard.canActivate(route);

handleResult(result, done);
});

it('should redirect to /dashboard if the user has permissions but tries to access another page', (done) => {
const mockPermissions = {
permission: ['viewDashboard'],
firstName: 'John',
lastName: 'Doe',
image: 'some-image-url',
};

route.url = [createMockUrlSegment('otherPage')];

authService.getPermissions.and.returnValue(of(mockPermissions));
router.parseUrl.and.returnValue('/dashboard' as unknown as UrlTree);

const result = guard.canActivate(route);
const result = guard.canActivate();

handleResult(result, done);
});
Expand All @@ -114,7 +96,7 @@ describe('AuthGuard', () => {
authService.getPermissions.and.returnValue(of(mockPermissions));
router.parseUrl.and.returnValue('/login' as unknown as UrlTree);

const result = guard.canActivate(route);
const result = guard.canActivate();

handleResult(result, done);
});
Expand All @@ -123,7 +105,7 @@ describe('AuthGuard', () => {
route.url = [createMockUrlSegment('dashboard')];
authService.getPermissions.and.returnValue(throwError('Error'));

const result = guard.canActivate(route);
const result = guard.canActivate();

if (result instanceof Observable) {
result.subscribe((value) => {
Expand Down
32 changes: 5 additions & 27 deletions src/app/guards/auth/auth.guard.ts
Original file line number Diff line number Diff line change
@@ -1,54 +1,32 @@
import { Injectable } from '@angular/core';
import {
ActivatedRouteSnapshot,
CanActivate,
CanActivateFn,
Router,
UrlTree,
} from '@angular/router';
import { CanActivate, Router, UrlTree } from '@angular/router';
import { catchError, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { AuthService } from '../../user/services/auth/auth.service';

export const authGuard: CanActivateFn = (route, state) => {
if (route && state) return true;
return true;
};

@Injectable({
providedIn: 'root',
})
export class AuthGuard implements CanActivate {
constructor(
private authService: AuthService,
private router: Router,
) {}
constructor(private authService: AuthService, private router: Router) {}

canActivate(
route: ActivatedRouteSnapshot,
):
canActivate():
| Observable<boolean | UrlTree>
| Promise<boolean | UrlTree>
| boolean
| UrlTree {
return this.authService.getPermissions().pipe(
map((permissions) => {
if (permissions?.permission.length) {
if (route.url[0].path !== 'dashboard') {
return this.router.parseUrl('/dashboard');
}
return true;
} else {
if (route.url[0].path !== 'login') {
return this.router.parseUrl('/login');
}
return true;
return this.router.parseUrl('/login');
}
}),
catchError(() => {
this.router.navigate(['/login']);
return [false];
}),
})
);
}
}
104 changes: 104 additions & 0 deletions src/app/guards/auth/login.guard.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import { TestBed } from '@angular/core/testing';
import {
ActivatedRouteSnapshot,
Router,
UrlSegment,
UrlTree,
} from '@angular/router';
import { Observable, of } from 'rxjs';
import { LoginGuard } from './login.guard';
import { AuthService } from '../../user/services/auth/auth.service';

describe('AuthGuard', () => {
let guard: LoginGuard;
let authService: jasmine.SpyObj<AuthService>;
let router: jasmine.SpyObj<Router>;
let route: ActivatedRouteSnapshot;
// let state: RouterStateSnapshot;

beforeEach(() => {
const authServiceSpy = jasmine.createSpyObj('AuthService', [
'getPermissions',
]);
const routerSpy = jasmine.createSpyObj('Router', ['navigate', 'parseUrl']);

TestBed.configureTestingModule({
providers: [
LoginGuard,
{ provide: AuthService, useValue: authServiceSpy },
{ provide: Router, useValue: routerSpy },
],
});

guard = TestBed.inject(LoginGuard);
authService = TestBed.inject(AuthService) as jasmine.SpyObj<AuthService>;
router = TestBed.inject(Router) as jasmine.SpyObj<Router>;

route = {} as ActivatedRouteSnapshot;
// state = {} as RouterStateSnapshot;
});

function createMockUrlSegment(path: string): UrlSegment {
return new UrlSegment(path, {});
}

function handleResult(
result:
| boolean
| UrlTree
| Observable<boolean | UrlTree>
| Promise<boolean | UrlTree>,
done: DoneFn
) {
if (result instanceof Observable) {
result.subscribe((value) => {
expect(value).toBeTruthy();
done();
});
} else if (result instanceof Promise) {
result.then((value) => {
expect(value).toBeTruthy();
done();
});
} else {
expect(result).toBeTruthy();
done();
}
}

it('should redirect to /dashboard if the user has permissions but tries to access another page', (done) => {
const mockPermissions = {
permission: ['viewDashboard'],
firstName: 'John',
lastName: 'Doe',
image: 'some-image-url',
};

route.url = [createMockUrlSegment('otherPage')];

authService.getPermissions.and.returnValue(of(mockPermissions));
router.parseUrl.and.returnValue('/dashboard' as unknown as UrlTree);

const result = guard.canActivate();

handleResult(result, done);
});

it('should redirect to /login if the user does not have permissions and tries to access a non-login page', (done) => {
const mockPermissions = {
permission: [],
firstName: 'John',
lastName: 'Doe',
image: 'some-image-url',
};

route.url = [createMockUrlSegment('dashboard')];

authService.getPermissions.and.returnValue(of(mockPermissions));
router.parseUrl.and.returnValue('/login' as unknown as UrlTree);

const result = guard.canActivate();

handleResult(result, done);
});
});
36 changes: 36 additions & 0 deletions src/app/guards/auth/login.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { Injectable } from '@angular/core';
import { CanActivate, CanActivateFn, Router, UrlTree } from '@angular/router';
import { catchError, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { AuthService } from '../../user/services/auth/auth.service';

export const loginGuard: CanActivateFn = (route, state) => {
if (route && state) return true;
return true;
};

@Injectable({
providedIn: 'root',
})
export class LoginGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}

canActivate():
| Observable<boolean | UrlTree>
| Promise<boolean | UrlTree>
| boolean
| UrlTree {
return this.authService.getPermissions().pipe(
map((permissions) => {
if (permissions?.permission.length) {
return this.router.parseUrl('/dashboard');
} else {
return true;
}
}),
catchError(() => {
return [true];
})
);
}
}
4 changes: 1 addition & 3 deletions src/app/user/services/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,7 @@ export class AuthService {
})
.pipe(
tap((response) => {
if (response.firstName) {
this.permissions.next(response);
}
this.permissions.next(response);
})
);
}
Expand Down