You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Application-Web/src/Core/Model/AuthModel.php

81 lines
2.3 KiB

<?php
namespace IQBall\Core\Model;
use IQBall\Core\Data\Account;
use IQBall\Core\Gateway\AccountGateway;
use IQBall\Core\Validation\FieldValidationFail;
use IQBall\Core\Validation\ValidationFail;
class AuthModel {
private AccountGateway $gateway;
/**
* @param AccountGateway $gateway
*/
public function __construct(AccountGateway $gateway) {
$this->gateway = $gateway;
}
/**
* @param string $username
* @param string $password
* @param string $confirmPassword
* @param string $email
* @param ValidationFail[] $failures
* @return Account|null the registered account or null if failures occurred
*/
public function register(string $username, string $password, string $confirmPassword, string $email, array &$failures): ?Account {
if ($password != $confirmPassword) {
$failures[] = new FieldValidationFail("confirmpassword", "Le mot de passe et la confirmation ne sont pas les mêmes.");
}
if ($this->gateway->exists($email)) {
$failures[] = new FieldValidationFail("email", "L'email existe déjà");
}
if (!empty($failures)) {
return null;
}
$hash = password_hash($password, PASSWORD_DEFAULT);
$token = $this->generateToken();
$accountId = $this->gateway->insertAccount($username, $email, $token, $hash);
return new Account($email, $username, $token, $accountId);
}
/**
* Generate a random base 64 string
* @return string
*/
private function generateToken(): string {
return base64_encode(random_bytes(64));
}
/**
* @param string $email
* @param string $password
* @param ValidationFail[] $failures
* @return Account|null the authenticated account or null if failures occurred
*/
public function login(string $email, string $password, array &$failures): ?Account {
$hash = $this->gateway->getHash($email);
if ($hash == null) {
$failures[] = new FieldValidationFail("email", "l'addresse email n'est pas connue.");
return null;
}
if (!password_verify($password, $hash)) {
$failures[] = new FieldValidationFail("password", "Mot de passe invalide.");
return null;
}
return $this->gateway->getAccountFromMail($email);
}
}