2022-02-14 15:56:05 +01:00
|
|
|
import { HttpClient } from '@angular/common/http';
|
|
|
|
import { Injectable } from '@angular/core';
|
|
|
|
import { map, Observable } from 'rxjs';
|
|
|
|
import { environment } from 'src/environments/environment';
|
|
|
|
import { User } from 'src/app/pages/models/user';
|
2022-03-07 15:36:40 +01:00
|
|
|
import jwt_decode from 'jwt-decode';
|
|
|
|
import { Router } from '@angular/router';
|
|
|
|
|
2022-02-14 15:56:05 +01:00
|
|
|
|
|
|
|
|
|
|
|
@Injectable({
|
|
|
|
providedIn: 'root'
|
|
|
|
})
|
|
|
|
export class AuthService {
|
|
|
|
private apiUrl: string;
|
|
|
|
private tokenKey: string;
|
|
|
|
|
2022-03-07 15:36:40 +01:00
|
|
|
constructor(private http: HttpClient, private router: Router) {
|
2022-02-14 15:56:05 +01:00
|
|
|
// On se sert des variables d'environnement de notre application
|
|
|
|
this.apiUrl = environment.apiUrl;
|
|
|
|
this.tokenKey = environment.tokenKey;
|
|
|
|
}
|
|
|
|
|
2022-03-07 13:48:33 +01:00
|
|
|
signup(newUser: User): Observable<any> {
|
2022-02-14 15:56:05 +01:00
|
|
|
|
2022-03-07 13:48:33 +01:00
|
|
|
console.log("Mon nouvel utilisateur : ", newUser);
|
|
|
|
return this.http.post(`${this.apiUrl}/signup`, newUser);
|
|
|
|
}
|
2022-02-14 15:56:05 +01:00
|
|
|
|
|
|
|
|
|
|
|
signin(email: string, password: string): Observable<any> {
|
|
|
|
const body = {
|
|
|
|
email: email,
|
|
|
|
password: password
|
|
|
|
};
|
|
|
|
|
|
|
|
console.log("Mon body : ", body);
|
|
|
|
|
2022-03-07 13:48:33 +01:00
|
|
|
|
2022-02-14 15:56:05 +01:00
|
|
|
|
2022-03-01 15:02:17 +01:00
|
|
|
return this.http.post(`${this.apiUrl}/signin`, body).pipe(
|
2022-02-14 15:56:05 +01:00
|
|
|
map((x: any) => {
|
2022-03-02 13:43:30 +01:00
|
|
|
console.log(x);
|
2022-03-01 15:02:17 +01:00
|
|
|
|
|
|
|
console.log('Service : ', x.token);
|
2022-02-14 15:56:05 +01:00
|
|
|
// Modification à faire ici
|
2022-03-01 15:02:17 +01:00
|
|
|
localStorage.setItem(this.tokenKey, x.token);
|
2022-02-14 15:56:05 +01:00
|
|
|
return x; // permet de renvoyer la réponse à l'initiateur (page Signin) après le traitement du map
|
|
|
|
})
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2022-03-07 15:36:40 +01:00
|
|
|
getConnectedUserInfo(): Observable<User> | void {
|
|
|
|
const token = localStorage.getItem(this.tokenKey);
|
|
|
|
if(token) {
|
|
|
|
const decodedToken = jwt_decode<any>(token);
|
|
|
|
const userId = decodedToken.userId;
|
|
|
|
return this.http.get<User>(`${this.apiUrl}/user/${userId}`);
|
|
|
|
} else {
|
|
|
|
this.router.navigate(['signin']);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-02-14 15:56:05 +01:00
|
|
|
}
|