Skip to content

Commit

Permalink
Merge add-dashboard-layout to dev
Browse files Browse the repository at this point in the history
  • Loading branch information
Abodawoud authored May 18, 2024
2 parents 32d4103 + dda2bd9 commit 5aac7a6
Show file tree
Hide file tree
Showing 21 changed files with 450 additions and 32 deletions.
2 changes: 0 additions & 2 deletions bisHelpers/src/app/app-routing.module.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AuthGuard } from './core/guards/auth.guard';

const routes: Routes = [
{ path: '', redirectTo: 'landing', pathMatch: 'full' },
Expand All @@ -17,7 +16,6 @@ const routes: Routes = [
import('./modules/dashboard/dashboard.module').then(
(m) => m.DashboardModule
),
canActivate: [AuthGuard],
},
{
path: 'auth',
Expand Down
2 changes: 2 additions & 0 deletions bisHelpers/src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
} from 'src/app/modules/auth/store/login-reducer';
import { provideEffects } from '@ngrx/effects';
import * as authEffects from 'src/app/modules/auth/store/login-effects';
import { CoreModule } from './core/core.module';

@NgModule({
declarations: [AppComponent],
Expand All @@ -23,6 +24,7 @@ import * as authEffects from 'src/app/modules/auth/store/login-effects';
AppRoutingModule,
BrowserAnimationsModule,
HttpClientModule,
CoreModule,
],
providers: [
provideStore(),
Expand Down
12 changes: 11 additions & 1 deletion bisHelpers/src/app/core/core.module.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,21 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AuthService } from '../modules/auth/services/auth.service';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { JwtInterceptor } from './services/jwt.interceptor';
//where to add interfaces
//answer: core module is the best place to add interfaces at the providers or
@NgModule({
declarations: [],
imports: [CommonModule],
providers: [],
providers: [
AuthService,
{
provide: HTTP_INTERCEPTORS,
useClass: JwtInterceptor,
multi: true,
},
],
exports: [],
})
export class CoreModule {}
39 changes: 28 additions & 11 deletions bisHelpers/src/app/core/guards/auth.guard.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,44 @@
// auth.guard.ts

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Observable, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { Store } from '@ngrx/store';
import { selectUser } from 'src/app/modules/auth/store/login-reducer';
import { LocalStorageService } from '../services/local-storage.service';
import { AuthService } from 'src/app/modules/auth/services/auth.service';

@Injectable({
providedIn: 'root',
})
export class AuthGuard implements CanActivate {
constructor(private store: Store, private router: Router) {}
constructor(
private store: Store,
private router: Router,
private localStorageService: LocalStorageService,
private authService: AuthService
) {}
// canActivate(): boolean {
// return true;
// }

isUser$ = this.store.select(selectUser);
canActivate(): Observable<boolean> {
return this.isUser$.pipe(
map((user) => {
if (user && user.token) {
const token = this.localStorageService.getItem('accessToken');
if (!token) {
this.router.navigateByUrl('/auth/login');
return of(false);
}

return this.authService.validateToken(token).pipe(
map((isValid) => {
if (isValid) {
return true;
} else {
this.router.navigateByUrl('/auth/login');
return false;
}
}),
catchError(() => {
this.router.navigateByUrl('/auth/login');
return false;
return of(false);
})
);
}
Expand Down
48 changes: 48 additions & 0 deletions bisHelpers/src/app/core/services/jwt.interceptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { Injectable } from '@angular/core';
import {
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest,
HttpErrorResponse,
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, switchMap } from 'rxjs/operators';
import { AuthService } from 'src/app/modules/auth/services/auth.service';

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(private authService: AuthService) {}

intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
const token = localStorage.getItem('token');
if (!token) {
return next.handle(req);
}

return this.authService.validateToken(token).pipe(
switchMap((isValid) => {
if (isValid) {
const authReq = req.clone({
setHeaders: {
Authorization: `Bearer ${token}`,
},
});
return next.handle(authReq);
} else {
this.authService.logout();
return throwError('Token is invalid');
}
}),
catchError((error: HttpErrorResponse) => {
if (error.status === 401) {
this.authService.logout();
}
return throwError(error);
})
);
}
}
10 changes: 9 additions & 1 deletion bisHelpers/src/app/core/services/local-storage.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export class LocalStorageService {
}
}

getItem(key: string): unknown {
getItem(key: string): string | null {
try {
const data = localStorage.getItem(key);
return data ? JSON.parse(data) : null;
Expand All @@ -23,4 +23,12 @@ export class LocalStorageService {
return null;
}
}

removeItem(key: string): void {
try {
localStorage.removeItem(key);
} catch (error) {
console.error('Error removing from localStorage', error);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ import { LoginResponseInterface } from './login-response-interface';
export interface AuthStateInterface {
isSubmitting: boolean;
user: LoginResponseInterface | null | undefined;
token: string | null;
validationErrors: ErrorBody[] | null | undefined;
isLoggedIn: boolean;
}
6 changes: 4 additions & 2 deletions bisHelpers/src/app/modules/auth/login/login.component.html
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<div
class="form-gradient max-lg:h-full flex items-center lg:py-10 py-5 px-5 lg:px-10"
class="form-gradient max-lg:h-screen flex items-center lg:py-10 py-5 px-5 lg:px-10"
>
<div
class="image-form-gradient rounded-s-2xl lg:h-screen hidden lg:flex items-center justify-center rounded-e"
Expand All @@ -10,7 +10,9 @@
<div
class="bg-white px-5 rounded-2xl lg:grow flex flex-col justify-center items-center gap-5 lg:gap-10 py-5 w-full lg:w-auto"
>
<img class="max-w-[115px]" src="assets/images/logo.png" alt="" />
<a href="#"
><img class="max-w-[115px]" src="assets/images/logo.png" alt=""
/></a>
<h1
class="text-heading-sm lg:text-heading-lg lg:leading-heading-lg font-semibold"
>
Expand Down
48 changes: 44 additions & 4 deletions bisHelpers/src/app/modules/auth/services/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,62 @@
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { LoginRequestInterface } from '../interfaces/login-request-interface';
import { environment } from 'src/environments/environment.development';
import { Observable } from 'rxjs';
import { Observable, catchError, map, of, tap } from 'rxjs';
import { LoginResponseInterface } from '../interfaces/login-response-interface';
import { Router } from '@angular/router';
import { LocalStorageService } from 'src/app/core/services/local-storage.service';

@Injectable({
providedIn: 'root',
})
export class AuthService {
constructor(private http: HttpClient) {}
constructor(
private http: HttpClient,
private router: Router,
private localStorageService: LocalStorageService
) {}

private API_BASE_URL = environment.API_BASE_URL + '/Auth';
private API_BASE_URL = environment.API_BASE_URL + '/auth';

login(data: LoginRequestInterface): Observable<LoginResponseInterface> {
return this.http.post<LoginResponseInterface>(
`${this.API_BASE_URL}/login`,
data
);
}

validateToken(token: string): Observable<boolean> {
const headers = new HttpHeaders({
Authorization: `Bearer ${token}`,
});
return this.http
.get(`${this.API_BASE_URL}/validateToken`, {
headers,
observe: 'response',
})
.pipe(
map((response) => response.status === 200),
catchError(() => of(false))
);
}

refreshToken(): Observable<any> {
return this.http
.post<any>(
`${this.API_BASE_URL}/refreshToken`,
{},
{ withCredentials: true }
)
.pipe(
tap((response) => {
this.localStorageService.setItem('accessToken', response.token);
})
);
}

logout() {
localStorage.removeItem('token');
this.router.navigate(['/auth/login']);
}
}
1 change: 1 addition & 0 deletions bisHelpers/src/app/modules/auth/store/login-effects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export const loginEffects = createEffect(
return authService.login(request).pipe(
map((loginresponse: LoginResponseInterface) => {
localStorageService.setItem('accessToken', loginresponse.token);
localStorageService.setItem('user', loginresponse);
return authActions.loginSuccess({ loginresponse });
}),
catchError((errorResponse: HttpErrorResponse) => {
Expand Down
4 changes: 2 additions & 2 deletions bisHelpers/src/app/modules/auth/store/login-reducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ import { authActions } from './login-action';

const initialState: AuthStateInterface = {
isSubmitting: false,
token: null,
user: undefined,
validationErrors: null,
isLoggedIn: false,
};

const authFeature = createFeature({
Expand All @@ -22,7 +22,6 @@ const authFeature = createFeature({
...state,
isSubmitting: false,
user: action.loginresponse,
token: action.loginresponse.token,
})),
on(authActions.loginFailure, (state, action) => ({
...state,
Expand All @@ -38,4 +37,5 @@ export const {
selectIsSubmitting,
selectUser,
selectValidationErrors,
selectIsLoggedIn,
} = authFeature;
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<p>gpa-analysis works!</p>
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Component } from '@angular/core';

@Component({
selector: 'app-gpa-analysis',
templateUrl: './gpa-analysis.component.html',
styleUrls: ['./gpa-analysis.component.css']
})
export class GpaAnalysisComponent {

}
Empty file.
Loading

0 comments on commit 5aac7a6

Please sign in to comment.