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.
78 lines
2.5 KiB
78 lines
2.5 KiB
<?php
|
|
|
|
namespace IQBall\Core\Model;
|
|
|
|
use Exception;
|
|
use IQBall\Core\Data\Account;
|
|
use IQBall\Core\Data\User;
|
|
use IQBall\Core\Gateway\AccountGateway;
|
|
use IQBall\Core\Validation\FieldValidationFail;
|
|
use IQBall\Core\Validation\ValidationFail;
|
|
|
|
class AuthModel {
|
|
private AccountGateway $gateway;
|
|
private const DEFAULT_PROFILE_PICTURE = "https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_960_720.png";
|
|
|
|
/**
|
|
* @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
|
|
* @throws Exception
|
|
*/
|
|
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,self::DEFAULT_PROFILE_PICTURE);
|
|
return new Account($token,new User($email,$username,$accountId,self::DEFAULT_PROFILE_PICTURE));
|
|
}
|
|
|
|
/**
|
|
* Generate a random base 64 string
|
|
* @return string
|
|
* @throws Exception
|
|
*/
|
|
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 or (!password_verify($password, $hash))) {
|
|
$failures[] = new ValidationFail("email","Adresse email ou mot de passe invalide");
|
|
return null;
|
|
}
|
|
return $this->gateway->getAccountFromMail($email);
|
|
}
|
|
|
|
}
|