Selaa lähdekoodia

new routes: /verify/jwt and /token/get (filtered by token_uf)

EduLascala 2 viikkoa sitten
vanhempi
sitoutus
a8269477ed
5 muutettua tiedostoa jossa 143 lisäystä ja 4 poistoa
  1. 2 3
      controllers/HelloController.php
  2. 38 0
      controllers/TokenGetController.php
  3. 25 0
      models/TokenModel.php
  4. 3 1
      public/index.php
  5. 75 0
      routes.md

+ 2 - 3
controllers/HelloController.php

@@ -9,8 +9,7 @@ class HelloController
 {
     public function __invoke(ServerRequestInterface $request)
     {
-        //$apiUser = $request->getAttribute('api_user');  // Exemplo: usa atributo do middleware
-        $data = ["message" => "Hello World!"];
-        return ResponseLib::sendOk($data);
+        // Se a execução chegou aqui, o Middleware já garantiu que o JWT é válido.
+        return ResponseLib::sendOk(['status' => 'active']);
     }
 }

+ 38 - 0
controllers/TokenGetController.php

@@ -0,0 +1,38 @@
+<?php
+
+namespace Controllers;
+
+use Libs\ResponseLib;
+use Models\TokenModel;
+use Psr\Http\Message\ServerRequestInterface;
+use Respect\Validation\Validator as val;
+use Respect\Validation\Exceptions\ValidationException;
+
+class TokenGetController
+{
+    private TokenModel $model;
+
+    public function __construct()
+    {
+        $this->model = new TokenModel();
+    }
+
+    public function __invoke(ServerRequestInterface $request)
+    {
+        $body = json_decode((string)$request->getBody(), true) ?? [];
+
+        try {
+            val::key('token_uf', val::stringType()->notEmpty()->length(1, 100))
+                ->assert($body);
+        } catch (ValidationException $e) {
+            return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(400);
+        }
+
+        $uf = (string)($body['token_uf'] ?? '');
+        $tokens = $this->model->getByUf($uf);
+
+        return $tokens
+            ? ResponseLib::sendOk($tokens)
+            : ResponseLib::sendFail("Token Not Found", [], "E_DATABASE")->withStatus(204);
+    }
+}

+ 25 - 0
models/TokenModel.php

@@ -0,0 +1,25 @@
+<?php
+
+namespace Models;
+
+class TokenModel
+{
+    private \PDO $pdo;
+
+    public function __construct()
+    {
+        if (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof \PDO) {
+            $this->pdo = $GLOBALS['pdo'];
+            return;
+        }
+        throw new \RuntimeException('Global PDO connection not initialized');
+    }
+
+    public function getByUf(string $uf): array
+    {
+        $stmt = $this->pdo->prepare('SELECT token_id, token_external_id, token_commodities_amount, token_commodities_value, token_uf, token_city, token_content, token_flag, wallet_id, chain_id, commodities_id, cpr_id, user_id FROM "token" WHERE token_uf = :uf ORDER BY token_id');
+        $stmt->execute(['uf' => $uf]);
+        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
+    }
+}
+

+ 3 - 1
public/index.php

@@ -36,7 +36,7 @@ $GLOBALS['pdo']->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
 $app = new App();
 $authJwt = new JwtAuthMiddleware();
 
-$app->get('/jwthelloworld', $authJwt,\Controllers\HelloController::class);
+$app->post('/verify/jwt', $authJwt,\Controllers\HelloController::class);
 
 $app->post('/login', \Controllers\LoginController::class);
 $app->post('/register', $authJwt, \Controllers\RegisterController::class);
@@ -59,4 +59,6 @@ $app->get('/commodities', $authJwt, \Controllers\CommoditiesGetController::class
 // CPR registration
 $app->post('/cpr/create', $authJwt, \Controllers\RegisterCprController::class);
 
+$app->post('/token/get', $authJwt, \Controllers\TokenGetController::class);
+
 $app->run();

+ 75 - 0
routes.md

@@ -659,3 +659,78 @@ curl --location 'http://localhost:8000/commodity/delete' \
   "data": []
 }
 ```
+
+---
+
+## 10. Token Get
+
+Returns all tokens filtered by `token_uf`. Requires JWT.
+
+### **Endpoint**
+
+`POST /token/get`
+
+### **Headers**
+
+`Content-Type: application/json`
+
+`Authorization: Bearer <JWT>`
+
+### **Request Body (JSON)**
+
+```json
+{
+  "token_uf": "SP"
+}
+```
+
+### **cURL Example**
+
+```bash
+curl --location 'http://localhost:8000/token/get' \
+  -H 'Content-Type: application/json' \
+  -H 'Authorization: Bearer <JWT>' \
+  --data '{
+    "token_uf": "SP"
+  }'
+```
+
+### **Responses**
+
+#### **200 OK**
+
+```json
+{
+  "status": "ok",
+  "msg": "[100] Request ok.",
+  "code": "S_OK",
+  "data": [
+    {
+      "token_id": 1,
+      "token_external_id": "abc123",
+      "token_commodities_amount": 1000,
+      "token_commodities_value": 5000,
+      "token_uf": "SP",
+      "token_city": "Sao Paulo",
+      "token_content": "financial instrument",
+      "token_flag": "a",
+      "wallet_id": 1,
+      "chain_id": 1,
+      "commodities_id": 1,
+      "cpr_id": 1,
+      "user_id": 1
+    }
+  ]
+}
+```
+
+#### **204 No Content**
+
+```json
+{
+  "status": "fail",
+  "msg": "Token Not Found",
+  "code": "E_DATABASE",
+  "data": []
+}
+```