]> BookStack Code Mirror - bookstack/blob - app/Http/Middleware/ApiAuthenticate.php
Added API listing filtering & cleaned ApiAuthenticate returns
[bookstack] / app / Http / Middleware / ApiAuthenticate.php
1 <?php
2
3 namespace BookStack\Http\Middleware;
4
5 use BookStack\Exceptions\UnauthorizedException;
6 use Closure;
7 use Illuminate\Http\Request;
8
9 class ApiAuthenticate
10 {
11     use ChecksForEmailConfirmation;
12
13     /**
14      * Handle an incoming request.
15      */
16     public function handle(Request $request, Closure $next)
17     {
18         // Validate the token and it's users API access
19         try {
20             $this->ensureAuthorizedBySessionOrToken();
21         } catch (UnauthorizedException $exception) {
22             return $this->unauthorisedResponse($exception->getMessage(), $exception->getCode());
23         }
24
25         return $next($request);
26     }
27
28     /**
29      * Ensure the current user can access authenticated API routes, either via existing session
30      * authentication or via API Token authentication.
31      * @throws UnauthorizedException
32      */
33     protected function ensureAuthorizedBySessionOrToken(): void
34     {
35         // Return if the user is already found to be signed in via session-based auth.
36         // This is to make it easy to browser the API via browser after just logging into the system.
37         if (signedInUser()) {
38             $this->ensureEmailConfirmedIfRequested();
39             return;
40         }
41
42         // Set our api guard to be the default for this request lifecycle.
43         auth()->shouldUse('api');
44
45         // Validate the token and it's users API access
46         auth()->authenticate();
47         $this->ensureEmailConfirmedIfRequested();
48     }
49
50     /**
51      * Provide a standard API unauthorised response.
52      */
53     protected function unauthorisedResponse(string $message, int $code)
54     {
55         return response()->json([
56             'error' => [
57                 'code' => $code,
58                 'message' => $message,
59             ]
60         ], $code);
61     }
62 }