PHP-Course/exam/api/Refresh/Refresh.php
2024-07-29 22:06:57 +02:00

53 lines
1.2 KiB
PHP

<?php
namespace Api\Refresh;
use Exception;
use Khofmann\Api\Api;
use Khofmann\ApiError\ApiError;
use Khofmann\Input\Input;
use Khofmann\Response\Response;
use Khofmann\Models\User\User;
use Khofmann\Request\Request;
/**
* Refresh route handlers
*/
class Refresh extends Api
{
/**
* Refresh POST handler
*
* Refresh a users session. User is retrieved using the authentication `token`.
*
* Returns user and tokens.
*
* @throws 401 Missing field
* @throws 404 User not found
* @throws 500 Failed to refresh tokens
*/
public function post(): void
{
// Fetch all required inputs.
// Throw 400 error if a required one is missing.
$token = Request::token();
$refreshToken = Input::post("refreshToken");
if (empty($refreshToken)) throw ApiError::missingField(["refreshToken"]);
// Try and log in user.
// Throw errors according to situation.
try {
Response::json(User::refresh($token, $refreshToken));
} catch (Exception $err) {
switch ($err->getMessage()) {
case "Failed":
throw ApiError::failed("Refresh failed");
case "NotFound":
throw ApiError::unauthorized("Not authorized");
default:
throw $err;
}
}
}
}