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

Add guards #28

Merged
merged 2 commits into from
Aug 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
5 changes: 3 additions & 2 deletions src/app/app.routes.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { Routes } from '@angular/router';
import { AuthComponent } from './page/auth/auth.component';
import { DashboardComponent } from './page/dashboard/dashboard.component';
import { AuthGuardService } from './services/gaurds/auth-guard/auth-guard.service';

export const routes: Routes = [
{ path: '', component: AuthComponent },
{ path: 'dashboard', component: DashboardComponent }
{ path: '', component: AuthComponent, canActivate: [AuthGuardService] },
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuardService] },
];
5 changes: 3 additions & 2 deletions src/app/page/auth/auth.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,13 @@ export class AuthComponent implements OnInit {

ngOnInit(): void {
this.ngParticlesService.init(async (engine: Engine) => {
console.log(engine);
await loadSlim(engine);
});
}

/* eslint-disable @typescript-eslint/no-unused-vars */
particlesLoaded(container: Container): void {
console.log(container);
// Placeholder implementation
}
/* eslint-enable @typescript-eslint/no-unused-vars */
}
7 changes: 7 additions & 0 deletions src/app/page/dashboard/dashboard.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { SidebarComponent } from '../../components/sidebar/sidebar.component';
import { SignInComponent } from "../../components/sign-in/sign-in.component";
import { AuthComponent } from "../auth/auth.component";
import { UsersTableComponent } from "../../components/users-table/users-table.component";
import { PermisionsService } from '../../services/permisisons/permisions.service';

@Component({
selector: 'app-dashboard',
Expand All @@ -30,6 +31,12 @@ import { UsersTableComponent } from "../../components/users-table/users-table.co
export class DashboardComponent {
isCollapsed = false;

constructor(private premissionSubject: PermisionsService) {
this.premissionSubject.permissions$.subscribe((v) => {
console.log(v)
})
}

toggleSidebar() {
this.isCollapsed = !this.isCollapsed;
}
Expand Down
18 changes: 18 additions & 0 deletions src/app/services/gaurds/auth-guard/auth-guard.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { TestBed } from '@angular/core/testing';
import { AuthGuardService } from './auth-guard.service';
import { provideHttpClient } from '@angular/common/http';

describe('AuthGuardService', () => {
let service: AuthGuardService;

beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideHttpClient()]
});
service = TestBed.inject(AuthGuardService);
});

it('should be created', () => {
expect(service).toBeTruthy();
});
});
36 changes: 36 additions & 0 deletions src/app/services/gaurds/auth-guard/auth-guard.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { Injectable } from '@angular/core';
import { LoginService } from '../../login/login.service';
import { Router } from '@angular/router';
import { HttpErrorResponse } from '@angular/common/http';
import { PermisionsService } from '../../permisisons/permisions.service';

@Injectable({
providedIn: 'root',
})
export class AuthGuardService {
constructor(
private loginService: LoginService,
private router: Router,
private permissionService: PermisionsService
) {}

canActivate() {
this.loginService.isLoggedIn().subscribe({
next: (response: string[] | HttpErrorResponse) => {
if (
Array.isArray(response) &&
response.every((item) => typeof item === 'string')
) {
this.permissionService.setPermissions(response);
return true;
}else{
this.router.navigate(['/']);
return false;
}
},
error: () => {
return false;
},
});
}
}
3 changes: 2 additions & 1 deletion src/app/services/login/login.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,14 @@ describe('LoginService', () => {
it('SHOULD call post method with proper data WHEN submited', () => {
// Arrange
const spy = spyOn(httpClient, 'post').and.callThrough();
const apiUrl = 'http://192.168.24.166:5293/api/Auth/Login';
const apiUrl = 'http://192.168.24.180:5293/api/Auth/Login';
const body = { username: 'armin', password: '123' };
// Act
service.login('armin', '123');
// Assert
expect(spy).toHaveBeenCalledWith(apiUrl, body, {
headers: jasmine.any(HttpHeaders),
withCredentials: true
});
});
});
29 changes: 24 additions & 5 deletions src/app/services/login/login.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import {
HttpClient,
HttpErrorResponse,
HttpHeaders,
} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { loginResponse } from '../../models/login-response';
Expand All @@ -7,15 +11,30 @@ import { loginResponse } from '../../models/login-response';
providedIn: 'root',
})
export class LoginService {
private apiUrl = 'http://192.168.24.166:5293/api/Auth/Login';

private URL = 'http://192.168.24.180:5293';
constructor(private http: HttpClient) {}

login(username: string, password: string): Observable<loginResponse | HttpErrorResponse> {
login(
username: string,
password: string
): Observable<loginResponse | HttpErrorResponse> {
const apiUrl = `${this.URL}/api/Auth/Login`;

const body = { username, password };

const headers = new HttpHeaders({ 'Content-Type': 'application/json' });

return this.http.post<loginResponse | HttpErrorResponse>(this.apiUrl, body, { headers });
return this.http.post<loginResponse | HttpErrorResponse>(apiUrl, body, {
headers,
withCredentials: true,
});
}

isLoggedIn(): Observable<string[] | HttpErrorResponse> {
const apiUrl = `${this.URL}/api/Access/GetPermissions`;

const headers = new HttpHeaders({ 'Content-Type': 'application/json' });

return this.http.get<string[]>(apiUrl, { headers, withCredentials: true });
}
}
16 changes: 16 additions & 0 deletions src/app/services/permisisons/permisions.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';

import { PermisionsService } from './permisions.service';

describe('PermisionsService', () => {
let service: PermisionsService;

beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(PermisionsService);
});

it('should be created', () => {
expect(service).toBeTruthy();
});
});
22 changes: 22 additions & 0 deletions src/app/services/permisisons/permisions.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable({
providedIn: 'root'
})
export class PermisionsService {
private permissionsSubject: BehaviorSubject<string[]> = new BehaviorSubject<string[]>([]);
public permissions$: Observable<string[]> = this.permissionsSubject.asObservable();

setPermissions(permissions: string[]): void {
this.permissionsSubject.next(permissions);
}

getPermissions(): string[] {
return this.permissionsSubject.value;
}

clearPermissions(): void {
this.permissionsSubject.next([]);
}
}