]> BookStack Code Mirror - bookstack/blobdiff - app/Http/Middleware/ApiAuthenticate.php
Added "page_include_parse" theme event
[bookstack] / app / Http / Middleware / ApiAuthenticate.php
index 655334450f8d1cfac8a2efc148c337edcccf4cb3..5d621ac119a22abf16c103d4cfc40dc617fcb5e8 100644 (file)
@@ -2,14 +2,13 @@
 
 namespace BookStack\Http\Middleware;
 
+use BookStack\Exceptions\ApiAuthException;
 use BookStack\Exceptions\UnauthorizedException;
 use Closure;
 use Illuminate\Http\Request;
 
 class ApiAuthenticate
 {
-    use ChecksForEmailConfirmation;
-
     /**
      * Handle an incoming request.
      */
@@ -28,14 +27,18 @@ class ApiAuthenticate
     /**
      * Ensure the current user can access authenticated API routes, either via existing session
      * authentication or via API Token authentication.
+     *
      * @throws UnauthorizedException
      */
     protected function ensureAuthorizedBySessionOrToken(): void
     {
         // Return if the user is already found to be signed in via session-based auth.
         // This is to make it easy to browser the API via browser after just logging into the system.
-        if (signedInUser()) {
-            $this->ensureEmailConfirmedIfRequested();
+        if (signedInUser() || session()->isStarted()) {
+            if (!$this->sessionUserHasApiAccess()) {
+                throw new ApiAuthException(trans('errors.api_user_no_api_permission'), 403);
+            }
+
             return;
         }
 
@@ -44,7 +47,16 @@ class ApiAuthenticate
 
         // Validate the token and it's users API access
         auth()->authenticate();
-        $this->ensureEmailConfirmedIfRequested();
+    }
+
+    /**
+     * Check if the active session user has API access.
+     */
+    protected function sessionUserHasApiAccess(): bool
+    {
+        $hasApiPermission = user()->can('access-api');
+
+        return $hasApiPermission && hasAppAccess();
     }
 
     /**
@@ -54,9 +66,9 @@ class ApiAuthenticate
     {
         return response()->json([
             'error' => [
-                'code' => $code,
+                'code'    => $code,
                 'message' => $message,
-            ]
+            ],
         ], $code);
     }
 }