Files
idp/idp_client/src/app/auth/login/login.component.ts
Bastian Wagner 834323f68a login
2024-08-25 20:50:06 +02:00

95 lines
2.7 KiB
TypeScript

import { HttpClient } from '@angular/common/http';
import { Component, inject } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { CommonModule } from '@angular/common';
import { FormControl, FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { environment } from '../../../environments/environment';
import { HotToastService } from '@ngxpert/hot-toast';
@Component({
selector: 'app-login',
standalone: true,
imports: [CommonModule, FormsModule, ReactiveFormsModule],
templateUrl: './login.component.html',
styleUrl: '../auth.scss'
})
export class LoginComponent {
private http: HttpClient = inject(HttpClient);
private route: ActivatedRoute = inject(ActivatedRoute);
private toast: HotToastService = inject(HotToastService);
private router: Router = inject(Router);
redirectUri = null;
client: string = "";
client_id = null;
loginForm = new FormGroup({
username: new FormControl(''),
password: new FormControl(''),
})
constructor() {
this.getclient();
this.loginWithSessionId();
}
loginWithSessionId() {
const id = window.localStorage.getItem("auth_sesion_key");
if (!id ||id.length < 2) { return; }
this.http.post(environment.api_url + 'auth/login-with-session-id', {
code: id,
client_id: this.client_id
}).subscribe({
next: (data) => {
if (data["code"] != null) {
location.href = this.redirectUri + "?code=" + data["code"];
}
},
error: (error) => {
this.toast.error('Invalid session, please log in with your credentials');
console.error(error);
}
});
}
getclient() {
const params = (this.route.snapshot.queryParamMap as any)["params"];
this.redirectUri = params.redirect_uri;
this.client_id = params.client_id;
this.http.get<any>(environment.api_url + 'auth/', {
params
}).subscribe({
next: (client) => {
this.client = client.clientName;
},
error: (error) => {
console.error(error);
this.toast.error('Invalid client');
}
})
}
login() {
this.toast.loading('Logging in...');
this.http.post(environment.api_url + 'auth/login?'+ 'client_id=' + this.client_id, this.loginForm.value).subscribe({
next: (data) => {
if (data["code"] != null) {
window.localStorage.setItem("auth_sesion_key", data["session_key"]);
location.href = this.redirectUri + "?code=" + data["code"];
}
},
error: (error) => {
console.error(error);
this.toast.error('Invalid login');
}
})
}
toRegister() {
this.router.navigate(['/register'], { queryParams: this.route.snapshot.queryParams });
}
}