3 namespace BookStack\Http\Middleware;
5 use BookStack\Exceptions\ApiAuthException;
6 use BookStack\Exceptions\UnauthorizedException;
8 use Illuminate\Http\Request;
14 * Handle an incoming request.
16 public function handle(Request $request, Closure $next)
18 // Validate the token and it's users API access
20 $this->ensureAuthorizedBySessionOrToken();
21 } catch (UnauthorizedException $exception) {
22 return $this->unauthorisedResponse($exception->getMessage(), $exception->getCode());
25 return $next($request);
29 * Ensure the current user can access authenticated API routes, either via existing session
30 * authentication or via API Token authentication.
32 * @throws UnauthorizedException
34 protected function ensureAuthorizedBySessionOrToken(): void
36 // Return if the user is already found to be signed in via session-based auth.
37 // This is to make it easy to browser the API via browser after just logging into the system.
38 if (signedInUser() || session()->isStarted()) {
39 if (!user()->can('access-api')) {
40 throw new ApiAuthException(trans('errors.api_user_no_api_permission'), 403);
46 // Set our api guard to be the default for this request lifecycle.
47 auth()->shouldUse('api');
49 // Validate the token and it's users API access
50 auth()->authenticate();
54 * Provide a standard API unauthorised response.
56 protected function unauthorisedResponse(string $message, int $code)
58 return response()->json([
61 'message' => $message,