From 5e4619b6e0bdcf58f5db4ae83b1377c009afc6fa Mon Sep 17 00:00:00 2001 From: Eldad Fux Date: Mon, 28 Dec 2020 22:31:42 +0200 Subject: [PATCH] Updated auth check --- app/controllers/general.php | 10 ++-------- app/init.php | 25 +++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 8 deletions(-) diff --git a/app/controllers/general.php b/app/controllers/general.php index 31e39712f7..5f9301aec1 100644 --- a/app/controllers/general.php +++ b/app/controllers/general.php @@ -2,7 +2,6 @@ require_once __DIR__.'/../init.php'; -use Ahc\Jwt\JWT; use Utopia\App; use Utopia\Swoole\Request; use Appwrite\Utopia\Response; @@ -161,9 +160,9 @@ App::init(function ($utopia, $request, $response, $console, $project, $user, $lo $roles = Config::getParam('roles', []); $scope = $route->getLabel('scope', 'none'); // Allowed scope for chosen route $scopes = $roles[$role]['scopes']; // Allowed scopes for user role + $authKey = $request->getHeader('x-appwrite-key', ''); - $authJWT = $request->getHeader('x-appwrite-jwt', ''); - + if (!empty($authKey)) { // API Key authentication // Check if given key match project API keys $key = $project->search('secret', $authKey, $project->getAttribute('keys', [])); @@ -188,11 +187,6 @@ App::init(function ($utopia, $request, $response, $console, $project, $user, $lo } } - if (!empty($authJWT)) { // JWT authentication - $jwt = new JWT(App::getEnv('_APP_OPENSSL_KEY_V1'), 'HS256', 3600, 10); // Instantiate with key, algo, maxAge and leeway. - $payload = $jwt->decode($authJWT); - } - if ($user->getId()) { Authorization::setRole('user:'.$user->getId()); } diff --git a/app/init.php b/app/init.php index 34ef3a5823..ad50ce17b5 100644 --- a/app/init.php +++ b/app/init.php @@ -11,6 +11,8 @@ if (\file_exists(__DIR__.'/../vendor/autoload.php')) { require_once __DIR__.'/../vendor/autoload.php'; } +use Ahc\Jwt\JWT; +use Ahc\Jwt\JWTException; use Appwrite\Auth\Auth; use Appwrite\Database\Database; use Appwrite\Database\Adapter\MySQL as MySQLAdapter; @@ -400,6 +402,29 @@ App::setResource('user', function($mode, $project, $console, $request, $response } } + $authJWT = $request->getHeader('x-appwrite-jwt', ''); + + if (!empty($authJWT)) { // JWT authentication + $jwt = new JWT(App::getEnv('_APP_OPENSSL_KEY_V1'), 'HS256', 3600, 10); // Instantiate with key, algo, maxAge and leeway. + + try { + $payload = $jwt->decode($authJWT); + } catch (JWTException $error) { + throw new Exception('Failed to verify JWT. '.$error->getMessage(), 401); + } + + $jwtUserId = $payload['userId'] ?? ''; + $jwtSessionId = $payload['sessionId'] ?? ''; + + if($jwtUserId && $jwtSessionId) { + $user = $projectDB->getDocument($jwtUserId); + } + + if (empty($user->search('$id', $jwtSessionId, $user->getAttribute('tokens')))) { // Match JWT to active token + $user = new Document(['$id' => '', '$collection' => Database::SYSTEM_COLLECTION_USERS]); + } + } + return $user; }, ['mode', 'project', 'console', 'request', 'response', 'projectDB', 'consoleDB']);