1. Go to this page and download the library: Download albertorc87/easyapi library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
namespace App\V1\Middlewares;
use EasyAPI\Middleware;
use EasyAPI\Request;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\ExpiredException;
use Exception;
use EasyAPI\Exceptions\HttpException;
class BasicAuth extends Middleware
{
public function handle(Request $request): Request
{
if(empty($_SERVER['HTTP_AUTHORIZATION'])) {
throw new HttpException('You must send Authorization header', 422);
}
$token = $_SERVER['HTTP_AUTHORIZATION'];
try {
$decoded = JWT::decode($token, new Key($_ENV['JWT_KEY'], 'HS256'));
$request->setData('user_id', $decoded->data->id);
return $request;
}
catch(ExpiredException $e) {
throw new HttpException('Your token has expired, please login again', 401);
}
catch(Exception $e) {
throw new HttpException('An error has ocurred, please, make again login, if persists, contact with admin');
}
}
}
// Rutas, BasicAuth sería nuestro middleware el cual enviamos como tercer parámetro en la ruta.
.
.
.
Router::get('/v1/tasks/(?<id>\d+)', TaskController::class . '@show', BasicAuth::class);
.
.
.
// Controlador TaskController
public function show(int $id, Request $request)
{
$user_id = $request->getData('user_id');
$ddbb = new DBTask();
$task = $ddbb->getTaskByUserId($id, $user_id);
if(empty($task)) {
throw new HttpException('Task not found', 404);
}
return view('json', $task);
}
namespace EasyAPI;
/**
* Set data from middleware to later access it from a controller
*/
class Request
{
private $data = [];
public function setData(string $key, $value)
{
$this->data[$key] = $value;
}
public function getData(string $key)
{
return $this->data[$key] ?? null;
}
}
public function show(int $id, Request $request)
{
$user_id = $request->getData('user_id');
$ddbb = new DBTask();
$task = $ddbb->getTaskByUserId($id, $user_id);
if(empty($task)) {
throw new HttpException('Task not found', 404);
}
return view('json', $task);
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.