]> BookStack Code Mirror - bookstack/blob - app/Http/Middleware/ApiAuthenticate.php
Merge branch 'footer-links' of git://github.com/james-geiger/BookStack into james...
[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     use ChecksForEmailConfirmation;
13
14     /**
15      * Handle an incoming request.
16      */
17     public function handle(Request $request, Closure $next)
18     {
19         // Validate the token and it's users API access
20         try {
21             $this->ensureAuthorizedBySessionOrToken();
22         } catch (UnauthorizedException $exception) {
23             return $this->unauthorisedResponse($exception->getMessage(), $exception->getCode());
24         }
25
26         return $next($request);
27     }
28
29     /**
30      * Ensure the current user can access authenticated API routes, either via existing session
31      * authentication or via API Token authentication.
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             $this->ensureEmailConfirmedIfRequested();
40             if (!user()->can('access-api')) {
41                 throw new ApiAuthException(trans('errors.api_user_no_api_permission'), 403);
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         $this->ensureEmailConfirmedIfRequested();
52     }
53
54     /**
55      * Provide a standard API unauthorised response.
56      */
57     protected function unauthorisedResponse(string $message, int $code)
58     {
59         return response()->json([
60             'error' => [
61                 'code' => $code,
62                 'message' => $message,
63             ]
64         ], $code);
65     }
66 }