1
0
Fork 0
mirror of synced 2024-06-26 18:20:43 +12:00

Updated auth check

This commit is contained in:
Eldad Fux 2020-12-28 22:31:42 +02:00
parent 002361c3b8
commit 5e4619b6e0
2 changed files with 27 additions and 8 deletions

View file

@ -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());
}

View file

@ -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']);