gateway = $gateway; } /** * @param string $username * @param string $password * @param string $email * @return Account|null the registered account or null if the account already exists for the given email address */ public function register( string $username, string $password, string $email ): ?Account { if ($this->gateway->exists($email)) { 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, false)); } /** * Generate a random base 64 string * @return string */ public static function generateToken(): string { try { return base64_encode(random_bytes(64)); } catch (Exception $e) { throw new \RuntimeException($e); } } /** * @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); } public function update(int $id, string $email, string $username, bool $isAdmin): void { $token = $this->generateToken(); $this->gateway->updateAccount($id, $username, $email, $token, $isAdmin); } }