80 lines
2.5 KiB
TypeScript
80 lines
2.5 KiB
TypeScript
import {Component, OnInit} from '@angular/core';
|
|
import {HttpClient} from '@angular/common/http';
|
|
import {ActivatedRoute, Router} from '@angular/router';
|
|
import {AuthService} from '../../services/auth.service';
|
|
import {environment} from '../../../environments/environment';
|
|
import {SnackbarService} from '../../services/snackbar.service';
|
|
|
|
@Component({
|
|
selector: 'app-login',
|
|
templateUrl: './login.component.html',
|
|
styleUrls: ['./login.component.css']
|
|
})
|
|
export class LoginComponent implements OnInit {
|
|
|
|
openid_endpoint = environment.openid_endpoint;
|
|
id_token;
|
|
state;
|
|
parsedToken;
|
|
|
|
constructor(private http: HttpClient,
|
|
private router: Router,
|
|
private activatedRoute: ActivatedRoute,
|
|
private authService: AuthService,
|
|
private snackbar: SnackbarService) {
|
|
}
|
|
|
|
ngOnInit(): void {
|
|
this.activatedRoute.fragment.subscribe(data => {
|
|
if (data) {
|
|
data.split('&').forEach(
|
|
element => {
|
|
const split = element.split('=');
|
|
if (split[0] === 'error') {
|
|
this.snackbar.show(split[1], 'Schließen', 5000);
|
|
return;
|
|
}
|
|
if (split[0] === 'id_token') {
|
|
this.id_token = split[1];
|
|
this.parsedToken = JSON.parse(atob(this.id_token.split('.')[1]));
|
|
const nonce = sessionStorage.getItem('nonce');
|
|
if (nonce && nonce === this.parsedToken.nonce) {
|
|
this.authService.setToken(this.id_token);
|
|
} else {
|
|
this.snackbar.show('Fehler bei der Anmeldung', 'Schließen', 5000);
|
|
}
|
|
} else if (split[0] === 'state') {
|
|
this.state = split[1];
|
|
}
|
|
}
|
|
);
|
|
}
|
|
if (this.authService.isAuthenticated()) {
|
|
this.router.navigate(['tweets']);
|
|
}
|
|
});
|
|
}
|
|
|
|
login() {
|
|
const nonce = this.randomString(20);
|
|
sessionStorage.setItem('nonce', nonce);
|
|
const url = this.openid_endpoint + '/auth?' +
|
|
'client_id=waecm' +
|
|
'&response_type=id_token' +
|
|
'&prompt=consent' +
|
|
'&redirect_uri=http://' + environment.location + ':' + environment.port_fe +
|
|
'&scope=openid%20profile' +
|
|
'&nonce=' + nonce;
|
|
window.location.replace(url);
|
|
}
|
|
|
|
randomString(length: number) {
|
|
let text = '';
|
|
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
|
for (let i = 0; i < length; i++) {
|
|
text += possible.charAt(Math.floor(Math.random() * possible.length));
|
|
}
|
|
return text;
|
|
}
|
|
}
|