]> BookStack Code Mirror - bookstack/blob - app/Http/Middleware/ApiAuthenticate.php
Cleaned some unused elements during testing
[bookstack] / app / Http / Middleware / ApiAuthenticate.php
1 <?php
2
3 namespace BookStack\Http\Middleware;
4
5 use BookStack\Exceptions\ApiAuthException;
6 use BookStack\Exceptions\UnauthorizedException;
7 use Closure;
8 use Illuminate\Http\Request;
9
10 class ApiAuthenticate
11 {
12
13     /**
14      * Handle an incoming request.
15      */
16     public function handle(Request $request, Closure $next)
17     {
18         // Validate the token and it's users API access
19         try {
20             $this->ensureAuthorizedBySessionOrToken();
21         } catch (UnauthorizedException $exception) {
22             return $this->unauthorisedResponse($exception->getMessage(), $exception->getCode());
23         }
24
25         return $next($request);
26     }
27
28     /**
29      * Ensure the current user can access authenticated API routes, either via existing session
30      * authentication or via API Token authentication.
31      *
32      * @throws UnauthorizedException
33      */
34     protected function ensureAuthorizedBySessionOrToken(): void
35     {
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);
41             }
42
43             return;
44         }
45
46         // Set our api guard to be the default for this request lifecycle.
47         auth()->shouldUse('api');
48
49         // Validate the token and it's users API access
50         auth()->authenticate();
51     }
52
53     /**
54      * Provide a standard API unauthorised response.
55      */
56     protected function unauthorisedResponse(string $message, int $code)
57     {
58         return response()->json([
59             'error' => [
60                 'code'    => $code,
61                 'message' => $message,
62             ],
63         ], $code);
64     }
65 }