Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
28.99% |
20 / 69 |
|
0.00% |
0 / 4 |
CRAP | |
0.00% |
0 / 1 |
| AuthenticateWithToken | |
28.99% |
20 / 69 |
|
0.00% |
0 / 4 |
330.19 | |
0.00% |
0 / 1 |
| handle | |
71.43% |
20 / 28 |
|
0.00% |
0 / 1 |
18.57 | |||
| logConsumerRequest | |
0.00% |
0 / 23 |
|
0.00% |
0 / 1 |
20 | |||
| responseBody | |
0.00% |
0 / 12 |
|
0.00% |
0 / 1 |
56 | |||
| redact | |
0.00% |
0 / 6 |
|
0.00% |
0 / 1 |
20 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace App\Http\Middleware; |
| 4 | |
| 5 | use App\Models\TblAuthUsers; |
| 6 | use App\Models\TblUsers; |
| 7 | use Carbon\Carbon; |
| 8 | use Closure; |
| 9 | use Illuminate\Http\Request; |
| 10 | use Illuminate\Support\Facades\DB; |
| 11 | use Symfony\Component\HttpFoundation\BinaryFileResponse; |
| 12 | use Symfony\Component\HttpFoundation\StreamedResponse; |
| 13 | |
| 14 | class AuthenticateWithToken |
| 15 | { |
| 16 | public function handle(Request $request, Closure $next) |
| 17 | { |
| 18 | $token = $request->bearerToken(); |
| 19 | |
| 20 | if (! $token) { |
| 21 | return response(['error' => 'Token expired or invalid'], 401); |
| 22 | } |
| 23 | |
| 24 | $user = TblUsers::where('api_token', $token)->first(); |
| 25 | $authUser = TblAuthUsers::where('api_token', $token)->first(); |
| 26 | |
| 27 | $validUser = null; |
| 28 | |
| 29 | if ($user && $user->token_expires_at > Carbon::now()) { |
| 30 | $validUser = $user; |
| 31 | } elseif ($authUser && $authUser->token_expires_at > Carbon::now()) { |
| 32 | $validUser = $authUser; |
| 33 | } |
| 34 | |
| 35 | if (! $validUser) { |
| 36 | return response(['error' => 'Token expired or invalid'], 401); |
| 37 | } |
| 38 | |
| 39 | // FIRE-1539: block inactive users from any authenticated call, even if |
| 40 | // their token is still within the 24h window. tbl_auth_users (external |
| 41 | // API consumers) has no is_active column so this only applies to |
| 42 | // Titan-native users on tbl_users. |
| 43 | if ($validUser instanceof TblUsers && (int) ($validUser->is_active ?? 1) === 0) { |
| 44 | return response(['error' => 'User is inactive. Contact your admin.'], 403); |
| 45 | } |
| 46 | |
| 47 | // Set the authenticated user for the request |
| 48 | $request->setUserResolver(fn () => $validUser); |
| 49 | |
| 50 | // Derive role and user identity from DB — never trust client-supplied headers |
| 51 | $request->headers->set('backend-user-id', (string) $validUser->id); |
| 52 | |
| 53 | $customerServiceRoleId = config('services.role_ids.customer_service'); |
| 54 | |
| 55 | if (! empty($validUser->is_commercial)) { |
| 56 | $request->headers->set('backend-role', 'commercial'); |
| 57 | } elseif (! empty($customerServiceRoleId) && (int) $validUser->role_id === (int) $customerServiceRoleId) { |
| 58 | // Only classify as customer_service when the role id is actually |
| 59 | // configured. Without the `! empty` guard an unset config (null) |
| 60 | // and a user with a null role_id both cast to 0, so `0 === 0` |
| 61 | // silently tagged every role-less user as customer_service and |
| 62 | // stripped their write access (403 on deletes/updates). |
| 63 | $request->headers->set('backend-role', 'customer_service'); |
| 64 | } else { |
| 65 | $request->headers->remove('backend-role'); |
| 66 | } |
| 67 | |
| 68 | // Full request/response log for external API consumers |
| 69 | // (tbl_auth_users). This middleware is the only place the token → party |
| 70 | // link is known, so we capture the whole call here — after $next so the |
| 71 | // response is available. Best-effort; never blocks the host request. |
| 72 | // Disabled unless services.api_consumer_log.enabled is set. |
| 73 | if ($validUser instanceof TblAuthUsers && config('services.api_consumer_log.enabled')) { |
| 74 | $start = microtime(true); |
| 75 | $response = $next($request); |
| 76 | $this->logConsumerRequest($request, $response, (int) $validUser->id, $start); |
| 77 | |
| 78 | return $response; |
| 79 | } |
| 80 | |
| 81 | return $next($request); |
| 82 | } |
| 83 | |
| 84 | /** Max response-body length stored (chars). Larger bodies are truncated. */ |
| 85 | private const MAX_RESPONSE_BODY = 1000000; |
| 86 | |
| 87 | /** Keys redacted from payload/query/headers before storing. */ |
| 88 | private const REDACT_KEYS = [ |
| 89 | 'password', 'password_confirmation', 'api_token', 'token', |
| 90 | 'authorization', 'x-auth-token', 'remember_token', |
| 91 | ]; |
| 92 | |
| 93 | /** |
| 94 | * Record one row per external-consumer request: caller, endpoint, request |
| 95 | * payload/query/headers (secrets redacted), response status + body (capped; |
| 96 | * binary/streamed responses skipped), IP and duration. Stored as JSON in |
| 97 | * tbl_api_consumer_endpoints. Wrapped so logging never breaks the request. |
| 98 | */ |
| 99 | private function logConsumerRequest(Request $request, $response, int $authUserId, float $start): void |
| 100 | { |
| 101 | try { |
| 102 | $route = $request->route(); |
| 103 | $durationMs = (int) round((microtime(true) - $start) * 1000); |
| 104 | |
| 105 | $payload = $this->redact($request->except(self::REDACT_KEYS)); |
| 106 | $query = $this->redact($request->query()); |
| 107 | $headers = $this->redact($request->headers->all()); |
| 108 | |
| 109 | $status = method_exists($response, 'getStatusCode') ? $response->getStatusCode() : null; |
| 110 | $body = $this->responseBody($response); |
| 111 | |
| 112 | DB::table('tbl_api_consumer_endpoints')->insert([ |
| 113 | 'auth_user_id' => $authUserId, |
| 114 | 'method' => $request->method(), |
| 115 | 'path' => $route ? $route->uri() : $request->path(), |
| 116 | 'url' => mb_substr($request->fullUrl(), 0, 2048), |
| 117 | 'query' => json_encode($query, JSON_UNESCAPED_UNICODE | JSON_PARTIAL_OUTPUT_ON_ERROR), |
| 118 | 'payload' => json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_PARTIAL_OUTPUT_ON_ERROR), |
| 119 | 'request_headers' => json_encode($headers, JSON_UNESCAPED_UNICODE | JSON_PARTIAL_OUTPUT_ON_ERROR), |
| 120 | 'status_code' => $status, |
| 121 | 'response_body' => $body, |
| 122 | 'ip_address' => $request->ip(), |
| 123 | 'duration_ms' => $durationMs, |
| 124 | 'created_at' => Carbon::now(), |
| 125 | 'updated_at' => Carbon::now(), |
| 126 | ]); |
| 127 | } catch (\Throwable) { |
| 128 | // Logging must never break the host request. |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | /** |
| 133 | * Extract the response body for logging. Binary/streamed responses aren't |
| 134 | * materialised (a marker is stored); textual bodies are capped. |
| 135 | */ |
| 136 | private function responseBody($response): ?string |
| 137 | { |
| 138 | if ($response instanceof BinaryFileResponse |
| 139 | || $response instanceof StreamedResponse) { |
| 140 | return '[binary/streamed response not logged]'; |
| 141 | } |
| 142 | |
| 143 | if (! method_exists($response, 'getContent')) { |
| 144 | return null; |
| 145 | } |
| 146 | |
| 147 | $content = $response->getContent(); |
| 148 | if ($content === false || $content === null) { |
| 149 | return null; |
| 150 | } |
| 151 | |
| 152 | $content = (string) $content; |
| 153 | |
| 154 | return mb_strlen($content) > self::MAX_RESPONSE_BODY |
| 155 | ? mb_substr($content, 0, self::MAX_RESPONSE_BODY).'…[truncated]' |
| 156 | : $content; |
| 157 | } |
| 158 | |
| 159 | /** Recursively redact secret keys from an array (case-insensitive keys). */ |
| 160 | private function redact(array $data): array |
| 161 | { |
| 162 | foreach ($data as $key => $value) { |
| 163 | if (in_array(strtolower((string) $key), self::REDACT_KEYS, true)) { |
| 164 | $data[$key] = '[REDACTED]'; |
| 165 | } elseif (is_array($value)) { |
| 166 | $data[$key] = $this->redact($value); |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | return $data; |
| 171 | } |
| 172 | } |