|
2 | 2 |
|
3 | 3 | namespace App\Middleware; |
4 | 4 |
|
| 5 | +use App\Models\User; |
5 | 6 | use Core\Exceptions\HTTPException; |
6 | 7 | use Core\Http\Middleware\Middleware; |
7 | 8 | use Core\Http\Request; |
| 9 | +use Exception; |
| 10 | +use Firebase\JWT\JWT; |
| 11 | +use Firebase\JWT\Key; |
8 | 12 | use Lib\Authentication\Auth; |
9 | 13 |
|
| 14 | +use function dd; |
| 15 | +use function getenv; |
| 16 | +use function http_response_code; |
| 17 | +use function json_encode; |
| 18 | +use function str_replace; |
| 19 | + |
10 | 20 | class AdminRole implements Middleware |
11 | 21 | { |
12 | 22 | public function handle(Request $request): void |
13 | 23 | { |
14 | | - if (Auth::user()->role_id != 1) { |
| 24 | + $headers = getallheaders(); |
| 25 | + if (!isset($headers['Authorization'])) { |
| 26 | + http_response_code(401); |
| 27 | + echo json_encode(["error" => "Token não fornecido"]); |
| 28 | + exit(); |
| 29 | + } |
| 30 | + |
| 31 | + $token = str_replace('Bearer ', '', $headers['Authorization']); |
| 32 | + $data = $this->validatesToken($token); |
| 33 | + $user = User::findById($data['user_id']); |
| 34 | + |
| 35 | + if ($user->role_id != 1) { |
15 | 36 | header('Content-Type: application/json', true, 401); |
16 | 37 | echo json_encode(['error' => 'Acesso restrito a admnistradores']); |
17 | 38 | exit; |
18 | 39 | } |
19 | 40 | } |
| 41 | + |
| 42 | + /** |
| 43 | + * |
| 44 | + * @param string $token |
| 45 | + * @return array<string, mixed>|null |
| 46 | + */ |
| 47 | + |
| 48 | + public function validatesToken(string $token): ?array |
| 49 | + { |
| 50 | + $key = $_ENV['PASSWORD_KEY_HASH'] ?? getenv('PASSWORD_KEY_HASH'); |
| 51 | + |
| 52 | + if (!$key) { |
| 53 | + return null; |
| 54 | + } |
| 55 | + |
| 56 | + try { |
| 57 | + $decoded = JWT::decode($token, new Key($key, 'HS256')); |
| 58 | + return (array) $decoded; |
| 59 | + } catch (Exception $e) { |
| 60 | + return null; |
| 61 | + } |
| 62 | + } |
20 | 63 | } |
0 commit comments