Skip to content

Commit b264bd5

Browse files
committed
✨ mis en place de la recuperation de l'utilisateur connecte
1 parent a1aab6f commit b264bd5

File tree

11 files changed

+62
-19
lines changed

11 files changed

+62
-19
lines changed

src/app/core/guards/auth.guard.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@ export class AuthGuard implements CanActivateChild {
1818
canActivateChild(): Observable<boolean> {
1919
return this.store.select(selectIsLoggedIn).pipe(
2020
first((value) => value !== null),
21-
map((isLoggedIn: boolean | null) => {
22-
if (! isLoggedIn && ! this.accessTokenService.getAccessToken()) {
21+
map(() => {
22+
if ( ! this.accessTokenService.getAccessToken()) {
2323
this.router.navigateByUrl('/auth/login')
2424
return false;
2525
}

src/app/core/guards/guest.guard.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
import { Injectable } from '@angular/core';
2-
import { ActivatedRouteSnapshot, CanActivateChild, Router, RouterStateSnapshot } from '@angular/router';
2+
import { CanActivateChild, Router } from '@angular/router';
33
import { AccessTokenService } from '@app/modules/authentication/services/access-token.service';
44
import { selectIsLoggedIn } from '@app/modules/authentication/store/auth.selectors';
55
import { Store } from '@ngrx/store';
6-
import { filter, first, map, Observable } from 'rxjs';
6+
import { first, map, Observable } from 'rxjs';
77

88
@Injectable({
99
providedIn: 'root'
@@ -18,8 +18,8 @@ export class GuestGuard implements CanActivateChild {
1818
canActivateChild(): Observable<boolean> {
1919
return this.store.select(selectIsLoggedIn).pipe(
2020
first((value) => value !== null),
21-
map((isLoggedIn: boolean | null) => {
22-
if (isLoggedIn && this.accessTokenService.getAccessToken()) {
21+
map(() => {
22+
if (! this.accessTokenService.tokenExpired()) {
2323
this.router.navigateByUrl('/dashboard')
2424
return false
2525
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import { Injectable } from '@angular/core';
2+
import { Store } from '@ngrx/store';
3+
import { first, map, Observable } from 'rxjs';
4+
import { CanActivateChild } from '@angular/router';
5+
6+
import { selectCurrentUser } from '@app/modules/authentication/store/auth.selectors';
7+
import { getCurrentUserAction } from '@app/modules/authentication/store/auth.actions';
8+
import { User } from '@app/modules/user/interfaces/user.interface';
9+
10+
@Injectable({
11+
providedIn: 'root'
12+
})
13+
export class UserDataGuard implements CanActivateChild {
14+
constructor(private store: Store) {}
15+
16+
canActivateChild(): Observable<boolean> {
17+
return this.store.select(selectCurrentUser).pipe(
18+
first(),
19+
map((user: User | null) => {
20+
if (! user) {
21+
this.store.dispatch(getCurrentUserAction());
22+
}
23+
console.log(user);
24+
return true;
25+
})
26+
);
27+
}
28+
29+
}

src/app/core/store/app.store.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1-
import { AuthState } from '@app/modules/authentication/interfaces/state.interface';
2-
import { authFeatureKey, authReducer } from '@app/modules/authentication/store/auth.reducer';
31
import { routerReducer, RouterState } from '@ngrx/router-store';
42
import { Action, ActionReducerMap } from '@ngrx/store';
53

4+
import { AuthState } from '@app/modules/authentication/interfaces/state.interface';
5+
import { authFeatureKey, authReducer } from '@app/modules/authentication/store/auth.reducer';
6+
67
export interface AppState {
78
router: RouterState;
89
[authFeatureKey]: AuthState;

src/app/modules/authentication/services/access-token.service.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,22 @@ import { Injectable } from '@angular/core';
66
export class AccessTokenService {
77
constructor() { }
88

9-
public setAccessToken(accessToken: string): void {
9+
public setAccessToken(accessToken: string, expiredIn: number): void {
1010
localStorage.setItem('accessToken', accessToken);
11+
localStorage.setItem('expiredIn', expiredIn.toString());
1112
}
1213

1314
public getAccessToken(): string | null {
14-
return localStorage.getItem('accessToken');
15+
return localStorage.getItem('accessToken');
1516
}
1617

1718
public removeAccessToken(): void {
1819
localStorage.removeItem('accessToken');
20+
localStorage.removeItem('expiredIn');
21+
}
22+
23+
public tokenExpired(): boolean {
24+
return !this.getAccessToken() && parseInt(localStorage.getItem('expiredIn') || '0') <= 0
1925
}
2026

2127
public setLocalStorage(key: string, value: any): void {

src/app/modules/authentication/services/auth.service.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,8 @@ export class AuthService {
3434
}
3535

3636
public getCurrentUser(): Observable<User> {
37-
return this.http.get<User>(`${environment.apiUrl}/current-user`);
37+
console.log('getCurrentUser');
38+
return this.http.get<User>(`${environment.apiUrl}/user/me`);
3839
}
3940

4041
public logout(): Observable<any> {

src/app/modules/authentication/store/auth.effects.ts

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import { catchError, map, switchMap } from 'rxjs/operators';
77
import * as AuthActions from './auth.actions';
88
import { AuthService } from '../services/auth.service';
99
import { Credentials, ResetPasswordCredentials } from '../interfaces/credentials.interface';
10-
import { AuthResponse, User } from '@app/modules/user/interfaces/user.interface';
10+
import { AuthResponse } from '@app/modules/user/interfaces/user.interface';
1111
import { AccessTokenService } from '../services/access-token.service';
1212

1313
@Injectable()
@@ -18,14 +18,14 @@ export class AuthEffects {
1818
switchMap(({ credentials }: { credentials: Credentials }) =>
1919
this.authService.authenticate(credentials).pipe(
2020
map((authResponse: AuthResponse) => {
21-
this.accessTokenService.setAccessToken(authResponse.data.access_token);
21+
this.accessTokenService.setAccessToken(authResponse.data.access_token, authResponse.data.expires_in);
2222
this.router.navigateByUrl('/dashboard');
2323
return AuthActions.fetchAuthenticateSuccessAction({ user: authResponse.data.user });
2424
}),
2525
catchError((error) => {
2626
return of(
2727
AuthActions.authenticateFailureAction({
28-
error: error.error?.message ?? 'Unknown error occurred',
28+
error: error.error?.message ?? 'Une erreur est survenue',
2929
})
3030
)
3131
})
@@ -42,7 +42,7 @@ export class AuthEffects {
4242
catchError((error) => {
4343
return of(
4444
AuthActions.forgotPasswordFailureAction({
45-
error: error.error?.message ?? 'Unknown error occurred',
45+
error: error.error?.message ?? 'Une erreur est survenue',
4646
})
4747
)
4848
})
@@ -58,7 +58,7 @@ export class AuthEffects {
5858
catchError((error) => {
5959
return of(
6060
AuthActions.resetPasswordFailureAction({
61-
error: error.error?.message ?? 'Unknown error occurred',
61+
error: error.error?.message ?? 'Une erreur est survenue',
6262
})
6363
)
6464
}
@@ -70,7 +70,10 @@ export class AuthEffects {
7070
this.actions$.pipe(
7171
ofType(AuthActions.getCurrentUserAction),
7272
switchMap(() => this.authService.getCurrentUser().pipe(
73-
map((user: User | null) => AuthActions.fetchCurrentUserSuccessAction({ user })),
73+
map(({ data }: any) => {
74+
console.log(data);
75+
return AuthActions.fetchCurrentUserSuccessAction({ user: data.user })
76+
}),
7477
catchError(() => EMPTY)
7578
))
7679
)

src/app/modules/authentication/store/auth.reducer.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ export const authReducer = createReducer(
4949
...state,
5050
isLoading: false,
5151
error,
52+
message: null,
5253
}
5354
}
5455
),

src/app/modules/authentication/store/auth.selectors.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1+
import { Params } from '@angular/router';
12
import { createFeatureSelector, createSelector } from '@ngrx/store';
23

34
import { selectQueryParams } from '@app/core/store/router.selectors';
45
import { AuthState } from '../interfaces/state.interface';
56
import { authFeatureKey } from './auth.reducer';
6-
import { Params } from '@angular/router';
77

88
const authSelectorFeature = createFeatureSelector<AuthState>(authFeatureKey);
99

src/app/modules/dashboard/routes/dashboard.routes.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { Routes } from '@angular/router';
22

33
import { AuthGuard } from '@app/core/guards/auth.guard';
4+
import { UserDataGuard } from '@app/core/guards/user-data.guard';
45

56
import { CpanelComponent } from '@app/shared/themes/layouts/cpanel/cpanel.component';
67
import { DashboardComponent } from '../pages/dashboard/dashboard.component';
@@ -9,7 +10,7 @@ export const dashboardRoutes: Routes = [
910
{
1011
path: '',
1112
component: CpanelComponent,
12-
canActivateChild: [AuthGuard],
13+
canActivateChild: [AuthGuard, UserDataGuard],
1314
children: [
1415
{ path: '', component: DashboardComponent },
1516
],

0 commit comments

Comments
 (0)