]> BookStack Code Mirror - bookstack/blob - app/Http/Middleware/ApiAuthenticate.php
Fixed phpstan wanring about usage of static
[bookstack] / app / Http / Middleware / ApiAuthenticate.php
1 <?php
2
3 namespace BookStack\Http\Middleware;
4
5 use BookStack\Exceptions\ApiAuthException;
6 use BookStack\Exceptions\UnauthorizedException;
7 use Closure;
8 use Illuminate\Http\Request;
9
10 class ApiAuthenticate
11 {
12     /**
13      * Handle an incoming request.
14      */
15     public function handle(Request $request, Closure $next)
16     {
17         // Validate the token and it's users API access
18         try {
19             $this->ensureAuthorizedBySessionOrToken();
20         } catch (UnauthorizedException $exception) {
21             return $this->unauthorisedResponse($exception->getMessage(), $exception->getCode());
22         }
23
24         return $next($request);
25     }
26
27     /**
28      * Ensure the current user can access authenticated API routes, either via existing session
29      * authentication or via API Token authentication.
30      *
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() || session()->isStarted()) {
38             if (!$this->sessionUserHasApiAccess()) {
39                 throw new ApiAuthException(trans('errors.api_user_no_api_permission'), 403);
40             }
41
42             return;
43         }
44
45         // Set our api guard to be the default for this request lifecycle.
46         auth()->shouldUse('api');
47
48         // Validate the token and it's users API access
49         auth()->authenticate();
50     }
51
52     /**
53      * Check if the active session user has API access.
54      */
55     protected function sessionUserHasApiAccess(): bool
56     {
57         $hasApiPermission = user()->can('access-api');
58
59         return $hasApiPermission && hasAppAccess();
60     }
61
62     /**
63      * Provide a standard API unauthorised response.
64      */
65     protected function unauthorisedResponse(string $message, int $code)
66     {
67         return response()->json([
68             'error' => [
69                 'code'    => $code,
70                 'message' => $message,
71             ],
72         ], $code);
73     }
74 }