3 namespace BookStack\Http\Middleware;
5 use BookStack\Exceptions\ApiAuthException;
6 use BookStack\Exceptions\UnauthorizedException;
8 use Illuminate\Http\Request;
13 * Handle an incoming request.
15 public function handle(Request $request, Closure $next)
17 // Validate the token and it's users API access
19 $this->ensureAuthorizedBySessionOrToken();
20 } catch (UnauthorizedException $exception) {
21 return $this->unauthorisedResponse($exception->getMessage(), $exception->getCode());
24 return $next($request);
28 * Ensure the current user can access authenticated API routes, either via existing session
29 * authentication or via API Token authentication.
31 * @throws UnauthorizedException
33 protected function ensureAuthorizedBySessionOrToken(): void
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);
45 // Set our api guard to be the default for this request lifecycle.
46 auth()->shouldUse('api');
48 // Validate the token and it's users API access
49 auth()->authenticate();
53 * Check if the active session user has API access.
55 protected function sessionUserHasApiAccess(): bool
57 $hasApiPermission = user()->can('access-api');
59 return $hasApiPermission && hasAppAccess();
63 * Provide a standard API unauthorised response.
65 protected function unauthorisedResponse(string $message, int $code)
67 return response()->json([
70 'message' => $message,