]> BookStack Code Mirror - bookstack/blob - app/Http/Middleware/ApiAuthenticate.php
c7fed405cc41e77b4176225a386b497e9793bc63
[bookstack] / app / Http / Middleware / ApiAuthenticate.php
1 <?php
2
3 namespace BookStack\Http\Middleware;
4
5 use BookStack\Exceptions\ApiAuthException;
6 use Closure;
7 use Illuminate\Http\Request;
8
9 class ApiAuthenticate
10 {
11     use ChecksForEmailConfirmation;
12
13     /**
14      * Handle an incoming request.
15      */
16     public function handle(Request $request, Closure $next)
17     {
18         // Return if the user is already found to be signed in via session-based auth.
19         // This is to make it easy to browser the API via browser after just logging into the system.
20         if (signedInUser()) {
21             if ($this->awaitingEmailConfirmation()) {
22                 return $this->emailConfirmationErrorResponse($request);
23             }
24             return $next($request);
25         }
26
27         // Set our api guard to be the default for this request lifecycle.
28         auth()->shouldUse('api');
29
30         // Validate the token and it's users API access
31         try {
32             auth()->authenticate();
33         } catch (ApiAuthException $exception) {
34             return $this->unauthorisedResponse($exception->getMessage(), $exception->getCode());
35         }
36
37         if ($this->awaitingEmailConfirmation()) {
38             return $this->emailConfirmationErrorResponse($request);
39         }
40
41         return $next($request);
42     }
43
44     /**
45      * Provide a standard API unauthorised response.
46      */
47     protected function unauthorisedResponse(string $message, int $code)
48     {
49         return response()->json([
50             'error' => [
51                 'code' => $code,
52                 'message' => $message,
53             ]
54         ], 401);
55     }
56 }