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