microserviciile de register, login finalizate
This commit is contained in:
Executable
+80
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
namespace app\core;
|
||||
|
||||
use app\exceptions\InvalidAuthTokenException;
|
||||
use app\exceptions\InvalidBodyException;
|
||||
use app\exceptions\InvalidRequestException;
|
||||
use app\exceptions\InvalidAuthRequestException;
|
||||
|
||||
use app\models\LoginModel;
|
||||
use app\models\RegisterModel;
|
||||
use Exception;
|
||||
|
||||
class Controller
|
||||
{
|
||||
private string $method;
|
||||
private ?array $body;
|
||||
private ?string $token;
|
||||
private ?string $authRequest;
|
||||
|
||||
public function __construct(string $method, ?string $authRequest, ?array $body, ?string $token)
|
||||
{
|
||||
$this->method = $method;
|
||||
$this->body = $body;
|
||||
$this->authRequest = $authRequest;
|
||||
$this->token = $token;
|
||||
}
|
||||
|
||||
public function run(): void
|
||||
{
|
||||
try {
|
||||
if (!$this->isTokenValid()) throw new InvalidAuthTokenException();
|
||||
if (!$this->isAuthRequestValid()) throw new InvalidAuthRequestException();
|
||||
if (!$this->body) throw new InvalidBodyException();
|
||||
|
||||
$model = match ($this->method) {
|
||||
'GET' => new LoginModel(),
|
||||
'PUT' => new RegisterModel(),
|
||||
default => throw new InvalidRequestException(),
|
||||
};
|
||||
|
||||
$model->createConnection();
|
||||
$result = $model->executeReq($this->body);
|
||||
|
||||
$this->writeResponse(
|
||||
DVC::getHttpCodeWithCode(DVC::$successReturnCode),
|
||||
DVC::$successReturnCode, $result
|
||||
);
|
||||
|
||||
} catch (Exception $e){
|
||||
$this->writeResponse(DVC::getHttpCodeWithCode($e->getCode()),
|
||||
$e->getCode(), $e->getMessage()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private function isTokenValid(): bool
|
||||
{
|
||||
$validToken = hash('md5', 'service_authentication');
|
||||
return $validToken === $this->token;
|
||||
}
|
||||
|
||||
private function isAuthRequestValid(): bool
|
||||
{
|
||||
return match ($this->authRequest){
|
||||
"register", "login" => true,
|
||||
default => false
|
||||
};
|
||||
}
|
||||
|
||||
private function writeResponse(int $httpCode, int $returnCode, string|array $returnMessage): void
|
||||
{
|
||||
header("Content-Disposition: ".DVC::$nameOfResponsePackage);
|
||||
header("Content-Type: application/json");
|
||||
http_response_code($httpCode);
|
||||
echo json_encode([
|
||||
"code" => $returnCode,
|
||||
"message" => $returnMessage
|
||||
]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user