resolution merge

This commit is contained in:
Thomas Cardon 2022-03-02 13:46:34 +01:00
commit 9148c51a1f
14 changed files with 279 additions and 12664 deletions

12632
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -21,6 +21,7 @@
"@angular/router": "~13.0.0",
"bootstrap": "^5.1.3",
"bootstrap-icons": "^1.7.2",
"jwt-decode": "^3.1.2",
"rxjs": "~7.4.0",
"tslib": "^2.3.0",
"zone.js": "~0.11.4"

View File

@ -8,6 +8,7 @@ import { PageNotFoundComponent } from './pages/page-not-found/page-not-found.com
import { FiltersPageComponent } from './pages/filters-page/filters-page.component';
import { SigninComponent } from './pages/signin/signin.component';
import { AdminPageComponent } from './pages/admin-page/admin-page.component';
import { AuthGuard } from './services/auth.guard';
const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
@ -16,7 +17,7 @@ const routes: Routes = [
{ path: 'favoris', component: FavorisUserComponent },
{ path: 'filtres', component: FiltersPageComponent },
{ path: 'Deconnexion', redirectTo: 'home'},
{path: 'restaurants',component: RestoPageComponent},
{path: 'restaurants', canActivate: [AuthGuard], component: RestoPageComponent},
{path: 'page-not-found',component: PageNotFoundComponent},
{path: 'signin', component: SigninComponent},
{path: 'admin', component: AdminPageComponent},

View File

@ -9,7 +9,7 @@ import { CardCategoryComponent } from './card-category/card-category.component';
import { CardRestoComponent } from './card-resto/card-resto.component';
import { FooterComponent } from './footer/footer.component';
import { HomePageComponent } from './pages/home-page/home-page.component';
import { HttpClientModule } from '@angular/common/http';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { ListCategoriesComponent } from './pages/list-categories/list-categories.component';
import { SigninComponent } from './pages/signin/signin.component';
import { RestoPageComponent } from './pages/resto-page/resto-page.component';
@ -22,6 +22,7 @@ import { AdminPageComponent } from './pages/admin-page/admin-page.component';
import { AddRestauComponent } from './admin-component/add-restau/add-restau.component';
import { UpdateDelRestauComponent } from './admin-component/update-del-restau/update-del-restau.component';
import { HeaderLogoComponent } from './header/components/header-logo/header-logo.component';
import { AuthInterceptor } from './services/auth.interceptor';
@NgModule({
declarations: [
@ -52,7 +53,9 @@ import { HeaderLogoComponent } from './header/components/header-logo/header-logo
FormsModule,
ReactiveFormsModule
],
providers: [],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
],
bootstrap: [AppComponent]
})
export class AppModule { }

View File

@ -1,4 +1,6 @@
import { Component, OnInit } from '@angular/core';
import { ApiBackService } from 'src/app/services/api-back.service';
import { TokenService } from 'src/app/services/token.service';
@Component({
selector: 'app-favoris-user',
@ -7,9 +9,16 @@ import { Component, OnInit } from '@angular/core';
})
export class FavorisUserComponent implements OnInit {
constructor() { }
personneConnectee : any;
constructor(private apiBackService : ApiBackService,private tokenService : TokenService) { }
ngOnInit(): void {
this.personneConnectee = this.apiBackService.getPersonneById(this.tokenService.getCurrentUserId());
console.log(this.personneConnectee);
}
}

View File

@ -1,4 +1,5 @@
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from '../../services/auth.service';
@Component({
@ -8,7 +9,8 @@ import { AuthService } from '../../services/auth.service';
})
export class SigninComponent implements OnInit {
public errorForm: boolean;
constructor(private authService: AuthService) {
constructor(private authService: AuthService , private router: Router) {
this.errorForm = false;
}
@ -21,7 +23,9 @@ export class SigninComponent implements OnInit {
const password = submittedForm.form.value['password'];
if(email !== '' && password !== '') {
this.authService.signin(email, password).subscribe(
resp => console.log('Component Page Signin: ', resp)
resp => {console.log('Component Page Signin ', resp)
this.router.navigate(['home'])
}
)
} else {
// afficher une erreur à l'utilisateur

View File

@ -8,14 +8,14 @@ import { Restaurant } from '../pages/models/restaurant';
providedIn: 'root'
})
export class ApiBackService {
public restoByCat : Observable<any[]> = of([]);
restoLiked$ = new Subject<any>();
public restoFilter : any[];
public routeParam ?: string;
@Input() restaurant : any;
constructor(private httpClient: HttpClient) {
public restoByCat: Observable<any[]> = of([]);
restoLiked$ = new Subject<any>();
public restoFilter: any[];
public routeParam?: string;
@Input() restaurant: any;
constructor(private httpClient: HttpClient) {
this.restoFilter = [];
this.routeParam = "";
}
@ -24,49 +24,53 @@ export class ApiBackService {
return this.httpClient.get<any[]>(`${environment.apiUrl}/restaurants`);
}
getRestaurantsByCateg(id : number, routeParam ?: string ): void {
getRestaurantsByCateg(id: number, routeParam?: string): void {
this.restoByCat = this.httpClient.get<any[]>(`${environment.apiUrl}/restaurantbytype/${id}`);
this.routeParam = routeParam;
}
getCategories(): Observable<any[]>{
getCategories(): Observable<any[]> {
return this.httpClient.get<any[]>(`${environment.apiUrl}/types`);
}
setListRestau(listRestau : any[], routeParam ?: string ) : void{
setListRestau(listRestau: any[], routeParam?: string): void {
this.restoFilter = listRestau;
this.restoFilter = listRestau;
this.routeParam = routeParam;
}
setDistance(lat1 : number , lon1 : number, lat2 : number, lon2 : number){
}
let R = 6371; // Radius of the earth in km
let dLat = this.deg2rad(lat2-lat1); // deg2rad below
let dLon = this.deg2rad(lon2-lon1);
let a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(this.deg2rad(lat1)) * Math.cos(this.deg2rad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
;
let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
let d = R * c * 1000; // Distance in meters
return d;
}
deg2rad(deg : number) {
return deg * (Math.PI/180)
}
addRestaurant( newRestau : Restaurant) : Observable<any>{
setDistance(lat1: number, lon1: number, lat2: number, lon2: number) {
let R = 6371; // Radius of the earth in km
let dLat = this.deg2rad(lat2 - lat1); // deg2rad below
let dLon = this.deg2rad(lon2 - lon1);
let a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(this.deg2rad(lat1)) * Math.cos(this.deg2rad(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2)
;
let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
let d = R * c * 1000; // Distance in meters
return d;
}
deg2rad(deg: number) {
return deg * (Math.PI / 180)
}
addRestaurant(newRestau: Restaurant): Observable<any> {
return this.httpClient.post<any[]>(`${environment.apiUrl}/add-restaurant`, newRestau);
}
deleteRestau( idRestau : number | undefined) : Observable<any>{
deleteRestau(idRestau: number | undefined): Observable<any> {
return this.httpClient.delete<Restaurant>(`${environment.apiUrl}/delete-restaurant/${idRestau}`);
}
}
getPersonneById(id: number | null) {
return this.httpClient.get<any[]>(`${environment.apiUrl}/user/${id}`);
}
}

View File

@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { AuthGuard } from './auth.guard';
describe('AuthGuard', () => {
let guard: AuthGuard;
beforeEach(() => {
TestBed.configureTestingModule({});
guard = TestBed.inject(AuthGuard);
});
it('should be created', () => {
expect(guard).toBeTruthy();
});
});

View File

@ -0,0 +1,46 @@
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { environment } from 'src/environments/environment';
import jwt_decode from 'jwt-decode';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
private tokenKey: string;
constructor(private router: Router){
this.tokenKey = environment.tokenKey;
}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
const token = localStorage.getItem(this.tokenKey);
if(token) {
const decodedToken = jwt_decode<any>(token);
console.log('decodedToken : ', decodedToken);
if(decodedToken.exp) {
console.log('Date d\'exp decodedToken : ', decodedToken.exp);
const dateExp = new Date(decodedToken.exp * 1000);
if(new Date() >= dateExp) {
// le token a expiré, je n'autorise pas l'accès
this.router.navigate(['signin']);
return false;
}
}
console.log("C'est ok ! ")
return true;
} else {
console.log("You shall not pass !!!!")
this.router.navigate(['signin']); // redirection de notre utilisateur vers une url de notre application (dans notre code TS)
return false;
}
}
}

View File

@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { AuthInterceptor } from './auth.interceptor';
describe('AuthInterceptor', () => {
beforeEach(() => TestBed.configureTestingModule({
providers: [
AuthInterceptor
]
}));
it('should be created', () => {
const interceptor: AuthInterceptor = TestBed.inject(AuthInterceptor);
expect(interceptor).toBeTruthy();
});
});

View File

@ -0,0 +1,31 @@
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { TokenService } from './token.service';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private tokenService: TokenService) {}
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
console.log('Coucou je suis le videur ! ');
const token = this.tokenService.getToken();
if(token) {
const authReq = request.clone(
{
headers : request.headers.set('Authorization', `Bearer ${token}`)
}
)
return next.handle(authReq);
} else {
return next.handle(request);
}
}
}

View File

@ -18,18 +18,18 @@ export class AuthService {
this.tokenKey = environment.tokenKey;
}
signup(newUser: User): Observable<any> {
// const body = {
// firstName: firstName,
// lastName: lastName,
// email: email,
// password: password
// };
// signup(): Observable<any> {
// // const body = {
// // firstName: firstName,
// // lastName: lastName,
// // email: email,
// // password: password
// // };
console.log("Mon nouvel utilisateur : ", newUser);
// console.log("Mon nouvel utilisateur : ", newUser);
return this.http.post(`${this.apiUrl}/register`, newUser);
}
// return this.http.post(`${this.apiUrl}/register`, newUser);
// }
signin(email: string, password: string): Observable<any> {
const body = {
@ -41,27 +41,29 @@ export class AuthService {
// Modifier cette partie ci-dessous :
// - pour pouvoir stocker dans le localstorage notre accesstoken
// - Sous la clé "TOKEN-LBP"
// - Sous la clé "TOKEN-SIMPLEAT"
return this.http.post(`${this.apiUrl}/login`, body).pipe(
return this.http.post(`${this.apiUrl}/signin`, body).pipe(
map((x: any) => {
console.log('Service : ', x.accessToken);
console.log(x);
console.log('Service : ', x.token);
// Modification à faire ici
localStorage.setItem(this.tokenKey, x.accessToken);
localStorage.setItem(this.tokenKey, x.token);
return x; // permet de renvoyer la réponse à l'initiateur (page Signin) après le traitement du map
})
);
}
forgotPassword(email: string, password: string): Observable<any> {
const body = {
email: email,
password: password
};
// forgotPassword(email: string, password: string): Observable<any> {
// const body = {
// email: email,
// password: password
// };
console.log("Mon body : ", body);
// console.log("Mon body : ", body);
return this.http.post(`${this.apiUrl}/forgot-psw`, body);
}
// return this.http.post(`${this.apiUrl}/forgot-psw`, body);
// }
}

View File

@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { TokenService } from './token.service';
describe('TokenService', () => {
let service: TokenService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(TokenService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});

View File

@ -0,0 +1,34 @@
import { Injectable } from '@angular/core';
import { environment } from 'src/environments/environment';
import jwt_decode from 'jwt-decode';
@Injectable({
providedIn: 'root'
})
export class TokenService {
tokenKey = environment.tokenKey;
constructor() { }
public getToken(): string | null {
const token = localStorage.getItem(this.tokenKey);
if(token) {
return token;
} else {
return null;
}
}
public getCurrentUserId(): number | null {
const token = this.getToken();
if(token) {
const decodedToken = jwt_decode<any>(token);
const userId = decodedToken.sub;
console.log(userId);
return userId;
} else {
return null;
}
}
}