]> BookStack Code Mirror - bookstack/blob - app/Http/Middleware/ApiAuthenticate.php
My Acount: Updated old preference url reference for watches
[bookstack] / app / Http / Middleware / ApiAuthenticate.php
1 <?php
2
3 namespace BookStack\Http\Middleware;
4
5 use BookStack\Exceptions\ApiAuthException;
6 use Closure;
7 use Illuminate\Http\Request;
8
9 class ApiAuthenticate
10 {
11     /**
12      * Handle an incoming request.
13      *
14      * @throws ApiAuthException
15      */
16     public function handle(Request $request, Closure $next)
17     {
18         // Validate the token and it's users API access
19         $this->ensureAuthorizedBySessionOrToken();
20
21         return $next($request);
22     }
23
24     /**
25      * Ensure the current user can access authenticated API routes, either via existing session
26      * authentication or via API Token authentication.
27      *
28      * @throws ApiAuthException
29      */
30     protected function ensureAuthorizedBySessionOrToken(): void
31     {
32         // Return if the user is already found to be signed in via session-based auth.
33         // This is to make it easy to browser the API via browser after just logging into the system.
34         if (!user()->isGuest() || session()->isStarted()) {
35             if (!$this->sessionUserHasApiAccess()) {
36                 throw new ApiAuthException(trans('errors.api_user_no_api_permission'), 403);
37             }
38
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     }
48
49     /**
50      * Check if the active session user has API access.
51      */
52     protected function sessionUserHasApiAccess(): bool
53     {
54         $hasApiPermission = user()->can('access-api');
55
56         return $hasApiPermission && user()->hasAppAccess();
57     }
58 }