]> BookStack Code Mirror - bookstack/blob - app/Http/Middleware/ApiAuthenticate.php
Extracted API auth into guard
[bookstack] / app / Http / Middleware / ApiAuthenticate.php
1 <?php
2
3 namespace BookStack\Http\Middleware;
4
5 use BookStack\Exceptions\ApiAuthException;
6 use BookStack\Http\Request;
7 use Closure;
8
9 class ApiAuthenticate
10 {
11
12     /**
13      * Handle an incoming request.
14      */
15     public function handle(Request $request, Closure $next)
16     {
17         // Return if the user is already found to be signed in via session-based auth.
18         // This is to make it easy to browser the API via browser after just logging into the system.
19         if (signedInUser()) {
20             return $next($request);
21         }
22
23         // Set our api guard to be the default for this request lifecycle.
24         auth()->shouldUse('api');
25
26         // Validate the token and it's users API access
27         try {
28             auth()->authenticate();
29         } catch (ApiAuthException $exception) {
30             return $this->unauthorisedResponse($exception->getMessage(), $exception->getCode());
31         }
32
33         return $next($request);
34     }
35
36     /**
37      * Provide a standard API unauthorised response.
38      */
39     protected function unauthorisedResponse(string $message, int $code)
40     {
41         return response()->json([
42             'error' => [
43                 'code' => $code,
44                 'message' => $message,
45             ]
46         ], 401);
47     }
48 }