From 56deaad74462121ca1eea036cf10e7038c843088 Mon Sep 17 00:00:00 2001 From: "bedran.sezer" <bedran.sezer@etu.hesge.ch> Date: Mon, 26 Feb 2024 23:47:48 +0100 Subject: [PATCH] correct localStorage token --- AngularApp/src/app/auth_service.ts | 96 ++++++++------------- AngularApp/src/app/login/login.component.ts | 23 ++--- 2 files changed, 41 insertions(+), 78 deletions(-) diff --git a/AngularApp/src/app/auth_service.ts b/AngularApp/src/app/auth_service.ts index 260aaa2..5356675 100644 --- a/AngularApp/src/app/auth_service.ts +++ b/AngularApp/src/app/auth_service.ts @@ -7,14 +7,16 @@ import { takeUntil } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) -export class AuthService implements OnDestroy { +export class AuthService { private gitLabClientId = 'aa238db2a5ca6d9eda4214dc563c0ae49224d1dad2b1364cfe68f8a653c4bd9f'; private gitLabRedirectUri = 'http://localhost:4200/login'; - private gitLabAuthUrl = 'https://githepia.hesge.ch/oauth/authorize'; - private gitLabTokenUrl = 'https://githepia.hesge.ch/oauth/token'; + private gitLabAuthUrl = 'https://gitedu.hesge.ch/oauth/authorize'; + private gitLabTokenUrl = 'https://gitedu.hesge.ch/oauth/token'; + private gitLabScope = 'api+create_runner+read_repository+write_repository'; private GITLAB_SECRET = 'gloas-4b3615b522437402e34617e1ce2bccaf690caf8225c664fee4cd14f38300521a' - private destroy$ = new Subject<void>(); + + private accessTokenSubject: BehaviorSubject<string | null> = new BehaviorSubject<string | null>(null); // Propriété pour stocker le nom d'utilisateur private usernameSubject: BehaviorSubject<string> = new BehaviorSubject<string>(''); @@ -22,75 +24,49 @@ export class AuthService implements OnDestroy { // Propriété observable pour permettre à d'autres parties de l'application d'accéder au nom d'utilisateur username$ = this.usernameSubject.asObservable(); - constructor(private http: HttpClient, private router: Router) {} + constructor(private http: HttpClient) {} authenticateWithGitLab(): void { const redirectUri = encodeURIComponent(this.gitLabRedirectUri); - const authUrl = `${this.gitLabAuthUrl}?client_id=${this.gitLabClientId}&redirect_uri=${redirectUri}&response_type=code&scope=api+create_runner+read_repository+write_repository`; - + const authUrl = `${this.gitLabAuthUrl}?client_id=${this.gitLabClientId}&redirect_uri=${redirectUri}&response_type=code&scope=${this.gitLabScope}`; window.location.href = authUrl; - - console.log("test"); - } - - getUserInfo(accessToken: string): void { - const headers = new HttpHeaders({ - Authorization: `Bearer ${accessToken}` - }); - - // Faire une requête à l'API GitLab pour obtenir les détails de l'utilisateur - this.http.get('https://githepia.hesge.ch/api/v4/user', { headers }) - .pipe(takeUntil(this.destroy$)) - .subscribe( - (user: any) => { - // Récupérer le nom du compte de l'utilisateur - const accountName = user.username; - this.usernameSubject.next(accountName); - - console.log(`Nom du compte: ${accountName}`); - }, - (error) => { - console.error(error); - } - ); } exchangeCodeForToken(code: string): void { const redirectUri = encodeURIComponent(this.gitLabRedirectUri); const body = `client_id=${this.gitLabClientId}&client_secret=${this.GITLAB_SECRET}&code=${code}&grant_type=authorization_code&redirect_uri=${redirectUri}`; + const headers = new HttpHeaders({ + 'Content-Type': 'application/x-www-form-urlencoded' + }); - this.http.post(this.gitLabTokenUrl, body) - .pipe(takeUntil(this.destroy$)) - .subscribe( - (response: any) => { - // Récupérer le jeton d'accès depuis la réponse - const accessToken = response.access_token; - - // Ajouter une déclaration de débogage pour vérifier l'accessToken - console.log('AccessToken récupéré :', accessToken); - - // Utiliser le jeton pour récupérer les informations de l'utilisateur - this.getUserInfo(accessToken); - - localStorage.setItem('authorizationCode', code); - localStorage.setItem('accessToken', response.access_token); - }, - (error) => { - console.error(error); - } - ); + this.http.post<any>(this.gitLabTokenUrl, body, { headers }).subscribe( + response => { + const accessToken = response.access_token; + console.log('AccessToken récupéré :', accessToken); + this.setAccessToken(accessToken); + // Stockez le jeton d'accès dans localStorage ou dans un service approprié + }, + error => { + console.error('Erreur lors de l\'échange du code d\'autorisation contre un jeton d\'accès :', error); + } + ); } - - isAuthorizationCodeStored(): boolean { - return localStorage.getItem('authorizationCode') !== null; + setAccessToken(accessToken: string): void { + localStorage.setItem('accessToken', accessToken); + this.accessTokenSubject.next(accessToken); + console.log('Access token stocké dans localStorage :', accessToken); } - isAccessTokenStored(): boolean { - return localStorage.getItem('accessToken') !== null; + getAccessToken(): string | null { + const accessToken = localStorage.getItem('accessToken'); + console.log('Access token récupéré depuis localStorage :', accessToken); + return accessToken; } - ngOnDestroy(): void { - this.destroy$.next(); - this.destroy$.complete(); + clearAccessToken(): void { + localStorage.removeItem('accessToken'); + this.accessTokenSubject.next(null); + console.log('Access token supprimé de localStorage.'); } -} + +} \ No newline at end of file diff --git a/AngularApp/src/app/login/login.component.ts b/AngularApp/src/app/login/login.component.ts index 86165b6..bf54928 100644 --- a/AngularApp/src/app/login/login.component.ts +++ b/AngularApp/src/app/login/login.component.ts @@ -8,36 +8,23 @@ import { ActivatedRoute } from '@angular/router'; styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { - username: string = ''; - private res = ""; - constructor(private route: ActivatedRoute, private authService: AuthService) {} ngOnInit(): void { - console.log("Affichage test"); - - // Subscription aux queryParams + + this.route.queryParams.subscribe(params => { const code = params['code']; - if (code) { console.log('Code d\'autorisation récupéré :', code); this.authService.exchangeCodeForToken(code); - this.res = code; + const accessToken = this.authService.getAccessToken(); + console.log('Access token dans LoginComponent :', accessToken); } else { - console.log("Aucun code d'autorisation trouvé dans les queryParams."); + console.log('Aucun code d\'autorisation trouvé dans les queryParams.'); } }); - - // Vérification du stockage du code d'autorisation - const isCodeStored = this.authService.isAuthorizationCodeStored(); - console.log('Le code d\'autorisation est stocké :', isCodeStored); - - // Vérification du stockage du jeton d'accès - const isTokenStored = this.authService.isAccessTokenStored(); - console.log('Le jeton d\'accès est stocké :', isTokenStored); - console.log('Code d\'autorisation récupéré :', this.res); } login(): void { -- GitLab