3 namespace BookStack\Http\Middleware;
5 use BookStack\Exceptions\ApiAuthException;
7 use Illuminate\Http\Request;
12 * Handle an incoming request.
14 * @throws ApiAuthException
16 public function handle(Request $request, Closure $next)
18 // Validate the token and it's users API access
19 $this->ensureAuthorizedBySessionOrToken();
21 return $next($request);
25 * Ensure the current user can access authenticated API routes, either via existing session
26 * authentication or via API Token authentication.
28 * @throws ApiAuthException
30 protected function ensureAuthorizedBySessionOrToken(): void
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);
42 // Set our api guard to be the default for this request lifecycle.
43 auth()->shouldUse('api');
45 // Validate the token and it's users API access
46 auth()->authenticate();
50 * Check if the active session user has API access.
52 protected function sessionUserHasApiAccess(): bool
54 $hasApiPermission = user()->can('access-api');
56 return $hasApiPermission && user()->hasAppAccess();