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.
45 lines
1.2 KiB
45 lines
1.2 KiB
<?php
|
|
|
|
namespace IQBall\Api\Controller;
|
|
|
|
use IQBall\App\Control;
|
|
use IQBall\Core\Http\HttpCodes;
|
|
use IQBall\Core\Http\HttpRequest;
|
|
use IQBall\Core\Http\HttpResponse;
|
|
use IQBall\Core\Http\JsonHttpResponse;
|
|
use IQBall\Core\Model\AuthModel;
|
|
use IQBall\Core\Validation\DefaultValidators;
|
|
|
|
class APIAuthController {
|
|
private AuthModel $model;
|
|
|
|
/**
|
|
* @param AuthModel $model
|
|
*/
|
|
public function __construct(AuthModel $model) {
|
|
$this->model = $model;
|
|
}
|
|
|
|
|
|
/**
|
|
* From given email address and password, authenticate the user and respond with its authorization token.
|
|
* @return HttpResponse
|
|
*/
|
|
public function authorize(): HttpResponse {
|
|
return Control::runChecked([
|
|
"email" => [DefaultValidators::email(), DefaultValidators::lenBetween(5, 256)],
|
|
"password" => [DefaultValidators::lenBetween(6, 256)],
|
|
], function (HttpRequest $req) {
|
|
$failures = [];
|
|
$account = $this->model->login($req["email"], $req["password"], $failures);
|
|
|
|
if (!empty($failures)) {
|
|
return new JsonHttpResponse($failures, HttpCodes::UNAUTHORIZED);
|
|
}
|
|
|
|
return new JsonHttpResponse(["authorization" => $account->getToken()]);
|
|
});
|
|
}
|
|
|
|
}
|