3 namespace BookStack\Http\Middleware;
5 use BookStack\Exceptions\UnauthorizedException;
7 use Illuminate\Http\Request;
11 use ChecksForEmailConfirmation;
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.
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.
38 $this->ensureEmailConfirmedIfRequested();
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();
47 $this->ensureEmailConfirmedIfRequested();
51 * Provide a standard API unauthorised response.
53 protected function unauthorisedResponse(string $message, int $code)
55 return response()->json([
58 'message' => $message,