3 namespace BookStack\Http\Middleware;
5 use BookStack\Exceptions\ApiAuthException;
6 use BookStack\Permissions\Permission;
8 use Illuminate\Http\Request;
13 * Handle an incoming request.
15 * @throws ApiAuthException
17 public function handle(Request $request, Closure $next)
19 // Validate the token and it's users API access
20 $this->ensureAuthorizedBySessionOrToken();
22 return $next($request);
26 * Ensure the current user can access authenticated API routes, either via existing session
27 * authentication or via API Token authentication.
29 * @throws ApiAuthException
31 protected function ensureAuthorizedBySessionOrToken(): void
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);
43 // Set our api guard to be the default for this request lifecycle.
44 auth()->shouldUse('api');
46 // Validate the token and it's users API access
47 auth()->authenticate();
51 * Check if the active session user has API access.
53 protected function sessionUserHasApiAccess(): bool
55 $hasApiPermission = user()->can(Permission::AccessApi);
57 return $hasApiPermission && user()->hasAppAccess();