From 448b0a56079ad3f7d8cfb4d3e0d853607af7eed2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Mon, 6 May 2024 08:35:27 +0000 Subject: [PATCH] Re-add api token auth --- app/controllers/shared/api.php | 36 ++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/app/controllers/shared/api.php b/app/controllers/shared/api.php index 1afd6b652e..6c01837195 100644 --- a/app/controllers/shared/api.php +++ b/app/controllers/shared/api.php @@ -1,5 +1,7 @@ getHeader('x-appwrite-token', ''); + if (!empty($apiToken) && $user->isEmpty() && empty($authKey)) { + $jwtObj = new JWT(App::getEnv('_APP_OPENSSL_KEY_V1'), 'HS256', 900, 10); + + try { + $payload = $jwtObj->decode($apiToken); + } catch (JWTException $error) { + // Ignore if token is invalid + } + + if (!empty($payload)) { + $projectId = $payload['projectId'] ?? ''; + $tokenScopes = $payload['scopes'] ?? []; + + // JWT includes project ID for better security + if ($projectId === $project->getId()) { + $user = new Document([ + '$id' => '', + 'status' => true, + 'email' => 'app.' . $project->getId() . '@service.' . $request->getHostname(), + 'password' => '', + 'name' => $project->getAttribute('name', 'Untitled'), + ]); + + $role = Auth::USER_ROLE_APPS; + $scopes = \array_merge($roles[$role]['scopes'], $tokenScopes); + + Authorization::setRole(Auth::USER_ROLE_APPS); + Authorization::setDefaultStatus(false); // Cancel security segmentation for API keys. + } + } + } + Authorization::setRole($role); foreach (Auth::getRoles($user) as $authRole) {