Skip to content
Snippets Groups Projects
Commit 56deaad7 authored by bedran.sezer's avatar bedran.sezer
Browse files

correct localStorage token

parent a2883d01
No related branches found
No related tags found
No related merge requests found
......@@ -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
......@@ -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 {
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment