96 lines
3.1 KiB
TypeScript
96 lines
3.1 KiB
TypeScript
import {Component, inject, signal, viewChild} from '@angular/core';
|
|
import {IonicModule, NavController, ToastController} from "@ionic/angular";
|
|
import {SignInFormComponent} from "../../components/sign-in-form/sign-in-form.component";
|
|
import {SignOnFormComponent} from "../../components/sign-on-form/sign-on-form.component";
|
|
import {AuthManageService} from "../../services/auth-manage";
|
|
import {firstValueFrom} from "rxjs";
|
|
import {UsersService} from "../../services/api";
|
|
|
|
@Component({
|
|
selector: 'app-login',
|
|
templateUrl: './login.component.html',
|
|
styleUrls: ['./login.component.scss'],
|
|
imports: [
|
|
IonicModule,
|
|
SignInFormComponent,
|
|
SignOnFormComponent
|
|
]
|
|
})
|
|
export class LoginComponent {
|
|
authState = signal<boolean>(true)
|
|
errorMessage = signal<string | null>(null);
|
|
login = viewChild<SignInFormComponent>('loginForm');
|
|
user = viewChild<SignOnFormComponent>('userForm');
|
|
|
|
private authManageService = inject(AuthManageService);
|
|
private usersService = inject(UsersService);
|
|
private navCtrl = inject(NavController);
|
|
private toastCtrl = inject(ToastController);
|
|
|
|
async createAccount() {
|
|
if (this.authState()) {
|
|
this.authState.set(false);
|
|
} else if (this.authState() == false) {
|
|
if (await this.addUser()) {
|
|
this.authState.set(true);
|
|
const toast = await this.toastCtrl.create({
|
|
message: 'Utilisateur crée',
|
|
duration: 2000,
|
|
color: 'success'
|
|
});
|
|
await toast.present();
|
|
}
|
|
}
|
|
}
|
|
|
|
async connectUser() {
|
|
const user = this.login().loginForm.getRawValue();
|
|
this.errorMessage.set(null);
|
|
|
|
try {
|
|
await this.authManageService.connectUser(user.username, user.password);
|
|
|
|
await this.navCtrl.navigateRoot('/home');
|
|
} catch (e) {
|
|
if (e.status === 401) {
|
|
this.errorMessage.set("Identifiants incorrects");
|
|
} else {
|
|
this.errorMessage.set("Connexion impossible");
|
|
}
|
|
|
|
const toast = await this.toastCtrl.create({
|
|
message: this.errorMessage(),
|
|
duration: 2000,
|
|
color: 'danger'
|
|
});
|
|
await toast.present();
|
|
|
|
this.login().loginForm.reset();
|
|
}
|
|
}
|
|
|
|
async addUser() {
|
|
if (this.user().userForm.invalid) {
|
|
const toast = await this.toastCtrl.create({
|
|
message: 'Tout les champs sont requis',
|
|
duration: 2000,
|
|
color: 'danger'
|
|
});
|
|
await toast.present();
|
|
return false;
|
|
}
|
|
try {
|
|
const users = this.user().userForm.getRawValue();
|
|
await firstValueFrom(this.usersService.createUserEndpoint(users));
|
|
return true;
|
|
} catch (e) {
|
|
const toast = await this.toastCtrl.create({
|
|
message: 'Email ou mot de passe incorrect',
|
|
duration: 2000,
|
|
color: 'danger'
|
|
});
|
|
await toast.present();
|
|
}
|
|
}
|
|
}
|