3 namespace BookStack\Http\Middleware;
5 use BookStack\Exceptions\ApiAuthException;
6 use BookStack\Exceptions\UnauthorizedException;
8 use Illuminate\Http\Request;
12 use ChecksForEmailConfirmation;
15 * Handle an incoming request.
17 public function handle(Request $request, Closure $next)
19 // Validate the token and it's users API access
21 $this->ensureAuthorizedBySessionOrToken();
22 } catch (UnauthorizedException $exception) {
23 return $this->unauthorisedResponse($exception->getMessage(), $exception->getCode());
26 return $next($request);
30 * Ensure the current user can access authenticated API routes, either via existing session
31 * 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 $this->ensureEmailConfirmedIfRequested();
40 if (!user()->can('access-api')) {
41 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();
51 $this->ensureEmailConfirmedIfRequested();
55 * Provide a standard API unauthorised response.
57 protected function unauthorisedResponse(string $message, int $code)
59 return response()->json([
62 'message' => $message,