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.
33 * @throws UnauthorizedException
35 protected function ensureAuthorizedBySessionOrToken(): void
37 // Return if the user is already found to be signed in via session-based auth.
38 // This is to make it easy to browser the API via browser after just logging into the system.
39 if (signedInUser() || session()->isStarted()) {
40 $this->ensureEmailConfirmedIfRequested();
41 if (!user()->can('access-api')) {
42 throw new ApiAuthException(trans('errors.api_user_no_api_permission'), 403);
48 // Set our api guard to be the default for this request lifecycle.
49 auth()->shouldUse('api');
51 // Validate the token and it's users API access
52 auth()->authenticate();
53 $this->ensureEmailConfirmedIfRequested();
57 * Provide a standard API unauthorised response.
59 protected function unauthorisedResponse(string $message, int $code)
61 return response()->json([
64 'message' => $message,