Merge branch 'feat-oauth-token-endpoint' of https://github.com/appwrite/appwrite into feat-oauth-token-endpoint

This commit is contained in:
loks0n
2024-02-05 12:45:17 +00:00
25 changed files with 583 additions and 270 deletions
+1
View File
@@ -4,6 +4,7 @@ _APP_WORKER_PER_CORE=6
_APP_CONSOLE_WHITELIST_ROOT=disabled
_APP_CONSOLE_WHITELIST_EMAILS=
_APP_CONSOLE_WHITELIST_IPS=
_APP_CONSOLE_COUNTRIES_DENYLIST=AQ
_APP_CONSOLE_HOSTNAMES=localhost,appwrite.io,*.appwrite.io
_APP_SYSTEM_EMAIL_NAME=Appwrite
_APP_SYSTEM_EMAIL_ADDRESS=team@appwrite.io
+22
View File
@@ -2117,6 +2117,28 @@ $commonCollections = [
'array' => false,
'filters' => [],
],
[
'$id' => ID::custom('sessionId'),
'type' => Database::VAR_STRING,
'format' => '',
'size' => Database::LENGTH_KEY,
'signed' => true,
'required' => false,
'default' => null,
'array' => false,
'filters' => [],
],
[
'$id' => ID::custom('sessionInternalId'),
'type' => Database::VAR_STRING,
'format' => '',
'size' => Database::LENGTH_KEY,
'signed' => true,
'required' => false,
'default' => null,
'array' => false,
'filters' => [],
],
[
'$id' => ID::custom('providerType'),
'type' => Database::VAR_STRING,
+5
View File
@@ -114,6 +114,11 @@ return [
'description' => 'Value must be a valid phone number. Format this number with a leading \'+\' and a country code, e.g., +16175551212.',
'code' => 400,
],
Exception::GENERAL_REGION_ACCESS_DENIED => [
'name' => Exception::GENERAL_REGION_ACCESS_DENIED,
'description' => 'Your location is not supported due to legal requirements.',
'code' => 451,
],
/** User Errors */
Exception::USER_COUNT_EXCEEDED => [
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+224 -163
View File
@@ -379,6 +379,7 @@ App::get('/v1/account/sessions/oauth2/:provider')
$oauth2 = new $className($appId, $appSecret, $callback, [
'success' => $success,
'failure' => $failure,
'token' => false,
], $scopes);
$response
@@ -1286,9 +1287,9 @@ App::post('/v1/account/tokens/magic-url')
App::post('/v1/account/tokens/email')
->desc('Create email token (OTP)')
->groups(['api', 'account'])
->groups(['api', 'account', 'auth'])
->label('scope', 'sessions.write')
->label('auth.type', 'email')
->label('auth.type', 'email-otp')
->label('audits.event', 'session.create')
->label('audits.resource', 'user/{response.userId}')
->label('audits.userId', '{response.userId}')
@@ -2033,76 +2034,6 @@ App::post('/v1/account/jwt')
])]), Response::MODEL_JWT);
});
App::post('/v1/account/targets/push')
->desc('Create Account\'s push target')
->groups(['api', 'account'])
->label('scope', 'account')
->label('audits.event', 'target.create')
->label('audits.resource', 'target/response.$id')
->label('event', 'users.[userId].targets.[targetId].create')
->label('sdk.auth', [APP_AUTH_TYPE_SESSION])
->label('sdk.namespace', 'account')
->label('sdk.method', 'createPushTarget')
->label('sdk.response.code', Response::STATUS_CODE_CREATED)
->label('sdk.response.type', Response::CONTENT_TYPE_JSON)
->label('sdk.response.model', Response::MODEL_TARGET)
->param('targetId', '', new CustomId(), 'Target ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can\'t start with a special char. Max length is 36 chars.')
->param('identifier', '', new Text(Database::LENGTH_KEY), 'The target identifier (token, email, phone etc.)')
->param('providerId', '', new UID(), 'Provider ID. Message will be sent to this target from the specified provider ID. If no provider ID is set the first setup provider will be used.', true)
->inject('queueForEvents')
->inject('user')
->inject('request')
->inject('response')
->inject('dbForProject')
->action(function (string $targetId, string $providerId, string $identifier, Event $queueForEvents, Document $user, Request $request, Response $response, Database $dbForProject) {
$targetId = $targetId == 'unique()' ? ID::unique() : $targetId;
$provider = Authorization::skip(fn () => $dbForProject->getDocument('providers', $providerId));
if ($user->isEmpty()) {
throw new Exception(Exception::USER_NOT_FOUND);
}
$target = Authorization::skip(fn () => $dbForProject->getDocument('targets', $targetId));
if (!$target->isEmpty()) {
throw new Exception(Exception::USER_TARGET_ALREADY_EXISTS);
}
$detector = new Detector($request->getUserAgent());
$detector->skipBotDetection(); // OPTIONAL: If called, bot detection will completely be skipped (bots will be detected as regular devices then)
$device = $detector->getDevice();
try {
$target = $dbForProject->createDocument('targets', new Document([
'$id' => $targetId,
'$permissions' => [
Permission::read(Role::user($user->getId())),
Permission::update(Role::user($user->getId())),
],
'providerId' => !empty($providerId) ? $providerId : null,
'providerInternalId' => !empty($providerId) ? $provider->getInternalId() : null,
'providerType' => MESSAGE_TYPE_PUSH,
'userId' => $user->getId(),
'userInternalId' => $user->getInternalId(),
'identifier' => $identifier,
'name' => "{$device['deviceBrand']} {$device['deviceModel']}"
]));
} catch (Duplicate) {
throw new Exception(Exception::USER_TARGET_ALREADY_EXISTS);
}
$dbForProject->purgeCachedDocument('users', $user->getId());
$queueForEvents
->setParam('userId', $user->getId())
->setParam('targetId', $target->getId());
$response
->setStatusCode(Response::STATUS_CODE_CREATED)
->dynamic($target, Response::MODEL_TARGET);
});
App::get('/v1/account')
->desc('Get account')
->groups(['api', 'account'])
@@ -2657,8 +2588,9 @@ App::delete('/v1/account/sessions/:sessionId')
->inject('dbForProject')
->inject('locale')
->inject('queueForEvents')
->inject('queueForDeletes')
->inject('project')
->action(function (?string $sessionId, ?\DateTime $requestTimestamp, Request $request, Response $response, Document $user, Database $dbForProject, Locale $locale, Event $queueForEvents, Document $project) {
->action(function (?string $sessionId, ?\DateTime $requestTimestamp, Request $request, Response $response, Document $user, Database $dbForProject, Locale $locale, Event $queueForEvents, Delete $queueForDeletes, Document $project) {
$protocol = $request->getProtocol();
$sessionId = ($sessionId === 'current')
@@ -2667,43 +2599,48 @@ App::delete('/v1/account/sessions/:sessionId')
$sessions = $user->getAttribute('sessions', []);
foreach ($sessions as $key => $session) {/** @var Document $session */
if ($sessionId == $session->getId()) {
$dbForProject->withRequestTimestamp($requestTimestamp, function () use ($dbForProject, $session) {
return $dbForProject->deleteDocument('sessions', $session->getId());
});
foreach ($sessions as $key => $session) {
/** @var Document $session */
if ($sessionId !== $session->getId()) {
continue;
}
unset($sessions[$key]);
$dbForProject->withRequestTimestamp($requestTimestamp, function () use ($dbForProject, $session) {
return $dbForProject->deleteDocument('sessions', $session->getId());
});
$session->setAttribute('current', false);
unset($sessions[$key]);
if ($session->getAttribute('secret') == Auth::hash(Auth::$secret)) { // If current session delete the cookies too
$session
->setAttribute('current', true)
->setAttribute('countryName', $locale->getText('countries.' . strtolower($session->getAttribute('countryCode')), $locale->getText('locale.country.unknown')))
;
$session->setAttribute('current', false);
if (!Config::getParam('domainVerification')) {
$response
->addHeader('X-Fallback-Cookies', \json_encode([]))
;
}
if ($session->getAttribute('secret') == Auth::hash(Auth::$secret)) { // If current session delete the cookies too
$session
->setAttribute('current', true)
->setAttribute('countryName', $locale->getText('countries.' . strtolower($session->getAttribute('countryCode')), $locale->getText('locale.country.unknown')));
$response
->addCookie(Auth::$cookieName . '_legacy', '', \time() - 3600, '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, null)
->addCookie(Auth::$cookieName, '', \time() - 3600, '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, Config::getParam('cookieSamesite'))
;
if (!Config::getParam('domainVerification')) {
$response->addHeader('X-Fallback-Cookies', \json_encode([]));
}
$dbForProject->purgeCachedDocument('users', $user->getId());
$queueForEvents
->setParam('userId', $user->getId())
->setParam('sessionId', $session->getId())
->setPayload($response->output($session, Response::MODEL_SESSION))
;
return $response->noContent();
$response
->addCookie(Auth::$cookieName . '_legacy', '', \time() - 3600, '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, null)
->addCookie(Auth::$cookieName, '', \time() - 3600, '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, Config::getParam('cookieSamesite'));
}
$dbForProject->purgeCachedDocument('users', $user->getId());
$queueForEvents
->setParam('userId', $user->getId())
->setParam('sessionId', $session->getId())
->setPayload($response->output($session, Response::MODEL_SESSION));
$queueForDeletes
->setType(DELETE_TYPE_SESSION_TARGETS)
->setDocument($session)
->trigger();
$response->noContent();
return;
}
throw new Exception(Exception::USER_SESSION_NOT_FOUND);
@@ -2805,7 +2742,8 @@ App::delete('/v1/account/sessions')
->inject('dbForProject')
->inject('locale')
->inject('queueForEvents')
->action(function (Request $request, Response $response, Document $user, Database $dbForProject, Locale $locale, Event $queueForEvents) {
->inject('queueForDeletes')
->action(function (Request $request, Response $response, Document $user, Database $dbForProject, Locale $locale, Event $queueForEvents, Delete $queueForDeletes) {
$protocol = $request->getProtocol();
$sessions = $user->getAttribute('sessions', []);
@@ -2819,8 +2757,7 @@ App::delete('/v1/account/sessions')
$session
->setAttribute('current', false)
->setAttribute('countryName', $locale->getText('countries.' . strtolower($session->getAttribute('countryCode')), $locale->getText('locale.country.unknown')))
;
->setAttribute('countryName', $locale->getText('countries.' . strtolower($session->getAttribute('countryCode')), $locale->getText('locale.country.unknown')));
if ($session->getAttribute('secret') == Auth::hash(Auth::$secret)) {
$session->setAttribute('current', true);
@@ -2831,7 +2768,13 @@ App::delete('/v1/account/sessions')
->addCookie(Auth::$cookieName, '', \time() - 3600, '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, Config::getParam('cookieSamesite'));
// Use current session for events.
$queueForEvents->setPayload($response->output($session, Response::MODEL_SESSION));
$queueForEvents
->setPayload($response->output($session, Response::MODEL_SESSION));
$queueForDeletes
->setType(DELETE_TYPE_SESSION_TARGETS)
->setDocument($session)
->trigger();
}
}
@@ -3880,63 +3823,6 @@ App::put('/v1/account/mfa/challenge')
$response->dynamic($session, Response::MODEL_SESSION);
});
App::put('/v1/account/targets/:targetId/push')
->desc('Update Account\'s push target')
->groups(['api', 'account'])
->label('scope', 'account')
->label('audits.event', 'target.update')
->label('audits.resource', 'target/response.$id')
->label('event', 'users.[userId].targets.[targetId].update')
->label('sdk.auth', [APP_AUTH_TYPE_SESSION])
->label('sdk.namespace', 'account')
->label('sdk.method', 'updatePushTarget')
->label('sdk.response.code', Response::STATUS_CODE_OK)
->label('sdk.response.type', Response::CONTENT_TYPE_JSON)
->label('sdk.response.model', Response::MODEL_TARGET)
->param('targetId', '', new UID(), 'Target ID.')
->param('identifier', '', new Text(Database::LENGTH_KEY), 'The target identifier (token, email, phone etc.)')
->inject('queueForEvents')
->inject('user')
->inject('request')
->inject('response')
->inject('dbForProject')
->action(function (string $targetId, string $identifier, Event $queueForEvents, Document $user, Request $request, Response $response, Database $dbForProject) {
if ($user->isEmpty()) {
throw new Exception(Exception::USER_NOT_FOUND);
}
$target = Authorization::skip(fn () => $dbForProject->getDocument('targets', $targetId));
if ($target->isEmpty()) {
throw new Exception(Exception::USER_TARGET_NOT_FOUND);
}
if ($user->getId() !== $target->getAttribute('userId')) {
throw new Exception(Exception::USER_TARGET_NOT_FOUND);
}
if ($identifier) {
$target->setAttribute('identifier', $identifier);
}
$detector = new Detector($request->getUserAgent());
$detector->skipBotDetection(); // OPTIONAL: If called, bot detection will completely be skipped (bots will be detected as regular devices then)
$device = $detector->getDevice();
$target->setAttribute('name', "{$device['deviceBrand']} {$device['deviceModel']}");
$target = $dbForProject->updateDocument('targets', $target->getId(), $target);
$dbForProject->purgeCachedDocument('users', $user->getId());
$queueForEvents
->setParam('userId', $user->getId())
->setParam('targetId', $target->getId());
$response
->dynamic($target, Response::MODEL_TARGET);
});
App::delete('/v1/account')
->desc('Delete account')
->groups(['api', 'account'])
@@ -3972,3 +3858,178 @@ App::delete('/v1/account')
$response->noContent();
});
App::post('/v1/account/targets/push')
->desc('Create a push target')
->groups(['api', 'account'])
->label('scope', 'targets.write')
->label('audits.event', 'target.create')
->label('audits.resource', 'target/response.$id')
->label('event', 'users.[userId].targets.[targetId].create')
->label('sdk.auth', [APP_AUTH_TYPE_SESSION])
->label('sdk.namespace', 'account')
->label('sdk.method', 'createPushTarget')
->label('sdk.response.code', Response::STATUS_CODE_CREATED)
->label('sdk.response.type', Response::CONTENT_TYPE_JSON)
->label('sdk.response.model', Response::MODEL_TARGET)
->param('targetId', '', new CustomId(), 'Target ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can\'t start with a special char. Max length is 36 chars.')
->param('identifier', '', new Text(Database::LENGTH_KEY), 'The target identifier (token, email, phone etc.)')
->param('providerId', '', new UID(), 'Provider ID. Message will be sent to this target from the specified provider ID. If no provider ID is set the first setup provider will be used.', true)
->inject('queueForEvents')
->inject('user')
->inject('request')
->inject('response')
->inject('dbForProject')
->action(function (string $targetId, string $identifier, string $providerId, Event $queueForEvents, Document $user, Request $request, Response $response, Database $dbForProject) {
$targetId = $targetId == 'unique()' ? ID::unique() : $targetId;
$provider = Authorization::skip(fn () => $dbForProject->getDocument('providers', $providerId));
$target = Authorization::skip(fn () => $dbForProject->getDocument('targets', $targetId));
if (!$target->isEmpty()) {
throw new Exception(Exception::USER_TARGET_ALREADY_EXISTS);
}
$detector = new Detector($request->getUserAgent());
$detector->skipBotDetection(); // OPTIONAL: If called, bot detection will completely be skipped (bots will be detected as regular devices then)
$device = $detector->getDevice();
$sessionId = Auth::sessionVerify($user->getAttribute('sessions'), Auth::$secret);
$session = $dbForProject->getDocument('sessions', $sessionId);
try {
$target = $dbForProject->createDocument('targets', new Document([
'$id' => $targetId,
'$permissions' => [
Permission::read(Role::user($user->getId())),
Permission::update(Role::user($user->getId())),
Permission::delete(Role::user($user->getId())),
],
'providerId' => !empty($providerId) ? $providerId : null,
'providerInternalId' => !empty($providerId) ? $provider->getInternalId() : null,
'providerType' => MESSAGE_TYPE_PUSH,
'userId' => $user->getId(),
'userInternalId' => $user->getInternalId(),
'sessionId' => $session->getId(),
'sessionInternalId' => $session->getInternalId(),
'identifier' => $identifier,
'name' => "{$device['deviceBrand']} {$device['deviceModel']}"
]));
} catch (Duplicate) {
throw new Exception(Exception::USER_TARGET_ALREADY_EXISTS);
}
$dbForProject->purgeCachedDocument('users', $user->getId());
$queueForEvents
->setParam('userId', $user->getId())
->setParam('targetId', $target->getId());
$response
->setStatusCode(Response::STATUS_CODE_CREATED)
->dynamic($target, Response::MODEL_TARGET);
});
App::put('/v1/account/targets/:targetId/push')
->desc('Update a push target')
->groups(['api', 'account'])
->label('scope', 'targets.write')
->label('audits.event', 'target.update')
->label('audits.resource', 'target/response.$id')
->label('event', 'users.[userId].targets.[targetId].update')
->label('sdk.auth', [APP_AUTH_TYPE_SESSION])
->label('sdk.namespace', 'account')
->label('sdk.method', 'updatePushTarget')
->label('sdk.response.code', Response::STATUS_CODE_OK)
->label('sdk.response.type', Response::CONTENT_TYPE_JSON)
->label('sdk.response.model', Response::MODEL_TARGET)
->param('targetId', '', new UID(), 'Target ID.')
->param('identifier', '', new Text(Database::LENGTH_KEY), 'The target identifier (token, email, phone etc.)')
->inject('queueForEvents')
->inject('user')
->inject('request')
->inject('response')
->inject('dbForProject')
->action(function (string $targetId, string $identifier, Event $queueForEvents, Document $user, Request $request, Response $response, Database $dbForProject) {
$target = Authorization::skip(fn () => $dbForProject->getDocument('targets', $targetId));
if ($target->isEmpty()) {
throw new Exception(Exception::USER_TARGET_NOT_FOUND);
}
if ($user->getId() !== $target->getAttribute('userId')) {
throw new Exception(Exception::USER_TARGET_NOT_FOUND);
}
if ($identifier) {
$target->setAttribute('identifier', $identifier);
}
$detector = new Detector($request->getUserAgent());
$detector->skipBotDetection(); // OPTIONAL: If called, bot detection will completely be skipped (bots will be detected as regular devices then)
$device = $detector->getDevice();
$target->setAttribute('name', "{$device['deviceBrand']} {$device['deviceModel']}");
$target = $dbForProject->updateDocument('targets', $target->getId(), $target);
$dbForProject->purgeCachedDocument('users', $user->getId());
$queueForEvents
->setParam('userId', $user->getId())
->setParam('targetId', $target->getId());
$response
->dynamic($target, Response::MODEL_TARGET);
});
App::delete('/v1/account/targets/:targetId/push')
->desc('Delete a push target')
->groups(['api', 'account'])
->label('scope', 'targets.write')
->label('audits.event', 'target.delete')
->label('audits.resource', 'target/response.$id')
->label('event', 'users.[userId].targets.[targetId].delete')
->label('sdk.auth', [APP_AUTH_TYPE_SESSION])
->label('sdk.namespace', 'account')
->label('sdk.method', 'deletePushTarget')
->label('sdk.response.code', Response::STATUS_CODE_NOCONTENT)
->label('sdk.response.type', Response::CONTENT_TYPE_JSON)
->label('sdk.response.model', Response::MODEL_TARGET)
->param('targetId', '', new UID(), 'Target ID.')
->inject('queueForEvents')
->inject('queueForDeletes')
->inject('user')
->inject('request')
->inject('response')
->inject('dbForProject')
->action(function (string $targetId, Event $queueForEvents, Delete $queueForDeletes, Document $user, Request $request, Response $response, Database $dbForProject) {
$target = Authorization::skip(fn() => $dbForProject->getDocument('targets', $targetId));
if ($target->isEmpty()) {
throw new Exception(Exception::USER_TARGET_NOT_FOUND);
}
if ($user->getInternalId() !== $target->getAttribute('userInternalId')) {
throw new Exception(Exception::USER_TARGET_NOT_FOUND);
}
$dbForProject->deleteDocument('targets', $target->getId());
$dbForProject->purgeCachedDocument('users', $user->getId());
$queueForDeletes
->setType(DELETE_TYPE_TARGET)
->setDocument($target);
$queueForEvents
->setParam('userId', $user->getId())
->setParam('targetId', $target->getId())
->setPayload($response->output($target, Response::MODEL_TARGET));
$response->noContent();
});
+4 -3
View File
@@ -2893,12 +2893,11 @@ App::get('/v1/databases/:databaseId/collections/:collectionId/documents')
->label('sdk.offline.model', '/databases/{databaseId}/collections/{collectionId}/documents')
->param('databaseId', '', new UID(), 'Database ID.')
->param('collectionId', '', new UID(), 'Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection).')
->param('queries', [], new JSON(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' queries are allowed, each ' . APP_LIMIT_ARRAY_ELEMENT_SIZE . ' characters long.', true)
->param('queries', [], new ArrayList(new Text(APP_LIMIT_ARRAY_ELEMENT_SIZE), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' queries are allowed, each ' . APP_LIMIT_ARRAY_ELEMENT_SIZE . ' characters long.', true)
->inject('response')
->inject('dbForProject')
->inject('mode')
->action(function (string $databaseId, string $collectionId, array $queries, Response $response, Database $dbForProject, string $mode) {
$queries = Query::parseQueries($queries);
$database = Authorization::skip(fn() => $dbForProject->getDocument('databases', $databaseId));
$isAPIKey = Auth::isAppUser(Authorization::getRoles());
$isPrivilegedUser = Auth::isPrivilegedUser(Authorization::getRoles());
@@ -2913,6 +2912,8 @@ App::get('/v1/databases/:databaseId/collections/:collectionId/documents')
throw new Exception(Exception::COLLECTION_NOT_FOUND);
}
$queries = Query::parseQueries($queries);
// Get cursor document if there was a cursor query
$cursor = \array_filter($queries, function ($query) {
return \in_array($query->getMethod(), [Query::TYPE_CURSOR_AFTER, Query::TYPE_CURSOR_BEFORE]);
@@ -3017,7 +3018,7 @@ App::get('/v1/databases/:databaseId/collections/:collectionId/documents/:documen
->param('databaseId', '', new UID(), 'Database ID.')
->param('collectionId', '', new UID(), 'Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection).')
->param('documentId', '', new UID(), 'Document ID.')
->param('queries', [], new JSON(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' queries are allowed, each ' . APP_LIMIT_ARRAY_ELEMENT_SIZE . ' characters long.', true)
->param('queries', [], new ArrayList(new Text(APP_LIMIT_ARRAY_ELEMENT_SIZE), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' queries are allowed, each ' . APP_LIMIT_ARRAY_ELEMENT_SIZE . ' characters long.', true)
->inject('response')
->inject('dbForProject')
->inject('mode')
+1 -1
View File
@@ -3296,7 +3296,7 @@ App::patch('/v1/messaging/messages/push/:messageId')
->label('scope', 'messages.write')
->label('sdk.auth', [APP_AUTH_TYPE_ADMIN, APP_AUTH_TYPE_KEY])
->label('sdk.namespace', 'messaging')
->label('sdk.method', 'updatePushNotification')
->label('sdk.method', 'updatePush')
->label('sdk.description', '/docs/references/messaging/update-push-notification.md')
->label('sdk.response.code', Response::STATUS_CODE_OK)
->label('sdk.response.type', Response::CONTENT_TYPE_JSON)
+1
View File
@@ -736,6 +736,7 @@ App::error()
case 412: // Error allowed publicly
case 416: // Error allowed publicly
case 429: // Error allowed publicly
case 451: // Error allowed publicly
case 501: // Error allowed publicly
case 503: // Error allowed publicly
break;
+18 -1
View File
@@ -22,6 +22,7 @@ use Utopia\Database\Database;
use Utopia\Database\DateTime;
use Utopia\Database\Document;
use Utopia\Database\Validator\Authorization;
use MaxMind\Db\Reader;
$parseLabel = function (string $label, array $responsePayload, array $requestParams, Document $user) {
preg_match_all('/{(.*?)}/', $label, $matches);
@@ -319,7 +320,17 @@ App::init()
->inject('utopia')
->inject('request')
->inject('project')
->action(function (App $utopia, Request $request, Document $project) {
->inject('geodb')
->action(function (App $utopia, Request $request, Document $project, Reader $geodb) {
$denylist = App::getEnv('_APP_CONSOLE_COUNTRIES_DENYLIST', '');
if (!empty($denylist) && $project->getId() === 'console') {
$countries = explode(',', $denylist);
$record = $geodb->get($request->getIP()) ?? [];
$country = $record['country']['iso_code'] ?? '';
if (in_array($country, $countries)) {
throw new Exception(Exception::GENERAL_REGION_ACCESS_DENIED);
}
}
$route = $utopia->getRoute();
@@ -368,6 +379,12 @@ App::init()
}
break;
case 'email-otp':
if (($auths['emailOTP'] ?? true) === false) {
throw new Exception(Exception::USER_AUTH_METHOD_UNSUPPORTED, 'Email OTP authentication is disabled for this project');
}
break;
default:
throw new Exception(Exception::USER_AUTH_METHOD_UNSUPPORTED, 'Unsupported authentication route');
break;
+18 -1
View File
@@ -6,13 +6,24 @@ use Utopia\App;
use Appwrite\Extend\Exception;
use Utopia\Database\Document;
use Utopia\Database\Validator\Authorization;
use MaxMind\Db\Reader;
App::init()
->groups(['auth'])
->inject('utopia')
->inject('request')
->inject('project')
->action(function (App $utopia, Request $request, Document $project) {
->inject('geodb')
->action(function (App $utopia, Request $request, Document $project, Reader $geodb) {
$denylist = App::getEnv('_APP_CONSOLE_COUNTRIES_DENYLIST', '');
if (!empty($denylist && $project->getId() === 'console')) {
$countries = explode(',', $denylist);
$record = $geodb->get($request->getIP()) ?? [];
$country = $record['country']['iso_code'] ?? '';
if (in_array($country, $countries)) {
throw new Exception(Exception::GENERAL_REGION_ACCESS_DENIED);
}
}
$route = $utopia->match($request);
@@ -61,6 +72,12 @@ App::init()
}
break;
case 'email-otp':
if (($auths['emailOTP'] ?? true) === false) {
throw new Exception(Exception::USER_AUTH_METHOD_UNSUPPORTED, 'Email OTP authentication is disabled for this project');
}
break;
default:
throw new Exception(Exception::USER_AUTH_METHOD_UNSUPPORTED, 'Unsupported authentication route');
break;
+1
View File
@@ -177,6 +177,7 @@ const DELETE_TYPE_SCHEDULES = 'schedules';
const DELETE_TYPE_TOPIC = 'topic';
const DELETE_TYPE_TARGET = 'target';
const DELETE_TYPE_EXPIRED_TARGETS = 'invalid_targets';
const DELETE_TYPE_SESSION_TARGETS = 'session_targets';
// Mail Types
const MAIL_TYPE_VERIFICATION = 'verification';
const MAIL_TYPE_MAGIC_SESSION = 'magicSession';
+1 -1
View File
@@ -65,7 +65,7 @@
"utopia-php/queue": "0.6.*",
"utopia-php/registry": "0.5.*",
"utopia-php/storage": "0.18.*",
"utopia-php/swoole": "0.5.*",
"utopia-php/swoole": "0.8.*",
"utopia-php/vcs": "0.6.*",
"utopia-php/websocket": "0.1.*",
"matomo/device-detector": "6.1.*",
Generated
+17 -17
View File
@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "3b43bf6f0fca50a3a2834e1bbaa90d63",
"content-hash": "e6e0d6874f4d718d96396d71a66864da",
"packages": [
{
"name": "adhocore/jwt",
@@ -1543,16 +1543,16 @@
},
{
"name": "utopia-php/database",
"version": "0.48.1",
"version": "0.48.2",
"source": {
"type": "git",
"url": "https://github.com/utopia-php/database.git",
"reference": "52abe057180a76fe354a516300344b33f268f6ea"
"reference": "0a231a2874fdbc0cf2ae2170b3f132fdee0ddfd4"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/utopia-php/database/zipball/52abe057180a76fe354a516300344b33f268f6ea",
"reference": "52abe057180a76fe354a516300344b33f268f6ea",
"url": "https://api.github.com/repos/utopia-php/database/zipball/0a231a2874fdbc0cf2ae2170b3f132fdee0ddfd4",
"reference": "0a231a2874fdbc0cf2ae2170b3f132fdee0ddfd4",
"shasum": ""
},
"require": {
@@ -1593,9 +1593,9 @@
],
"support": {
"issues": "https://github.com/utopia-php/database/issues",
"source": "https://github.com/utopia-php/database/tree/0.48.1"
"source": "https://github.com/utopia-php/database/tree/0.48.2"
},
"time": "2024-02-02T04:54:13+00:00"
"time": "2024-02-02T14:10:14+00:00"
},
{
"name": "utopia-php/domains",
@@ -2432,28 +2432,28 @@
},
{
"name": "utopia-php/swoole",
"version": "0.5.0",
"version": "0.8.2",
"source": {
"type": "git",
"url": "https://github.com/utopia-php/swoole.git",
"reference": "c2a3a4f944a2f22945af3cbcb95b13f0769628b1"
"reference": "5fa9d42c608ad46a4ce42a6d2b2eae00592fccd4"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/utopia-php/swoole/zipball/c2a3a4f944a2f22945af3cbcb95b13f0769628b1",
"reference": "c2a3a4f944a2f22945af3cbcb95b13f0769628b1",
"url": "https://api.github.com/repos/utopia-php/swoole/zipball/5fa9d42c608ad46a4ce42a6d2b2eae00592fccd4",
"reference": "5fa9d42c608ad46a4ce42a6d2b2eae00592fccd4",
"shasum": ""
},
"require": {
"ext-swoole": "*",
"php": ">=8.0",
"utopia-php/framework": "0.*.*"
"utopia-php/framework": "0.33.*"
},
"require-dev": {
"laravel/pint": "1.2.*",
"phpstan/phpstan": "^1.10",
"phpunit/phpunit": "^9.3",
"swoole/ide-helper": "4.8.3",
"vimeo/psalm": "4.15.0"
"swoole/ide-helper": "5.0.2"
},
"type": "library",
"autoload": {
@@ -2477,9 +2477,9 @@
],
"support": {
"issues": "https://github.com/utopia-php/swoole/issues",
"source": "https://github.com/utopia-php/swoole/tree/0.5.0"
"source": "https://github.com/utopia-php/swoole/tree/0.8.2"
},
"time": "2022-10-19T22:19:07+00:00"
"time": "2024-02-01T14:54:12+00:00"
},
{
"name": "utopia-php/system",
@@ -5523,5 +5523,5 @@
"platform-overrides": {
"php": "8.2"
},
"plugin-api-version": "2.3.0"
"plugin-api-version": "2.6.0"
}
+1
View File
@@ -188,6 +188,7 @@ services:
- _APP_MESSAGE_SMS_TEST_DSN
- _APP_MESSAGE_EMAIL_TEST_DSN
- _APP_MESSAGE_PUSH_TEST_DSN
- _APP_CONSOLE_COUNTRIES_DENYLIST
appwrite-realtime:
entrypoint: realtime
+1
View File
@@ -57,6 +57,7 @@ class Exception extends \Exception
public const GENERAL_NOT_IMPLEMENTED = 'general_not_implemented';
public const GENERAL_INVALID_EMAIL = 'general_invalid_email';
public const GENERAL_INVALID_PHONE = 'general_invalid_phone';
public const GENERAL_REGION_ACCESS_DENIED = 'general_region_access_denied';
/** Users */
public const USER_COUNT_EXCEEDED = 'user_count_exceeded';
+19 -2
View File
@@ -164,6 +164,9 @@ class Deletes extends Action
case DELETE_TYPE_EXPIRED_TARGETS:
$this->deleteExpiredTargets($project, $getProjectDB);
break;
case DELETE_TYPE_SESSION_TARGETS:
$this->deleteSessionTargets($project, $getProjectDB, $document);
break;
default:
throw new \Exception('No delete operation for type: ' . \strval($type));
}
@@ -249,7 +252,7 @@ class Deletes extends Action
* @param Document $target
* @throws Exception
*/
private function deleteTargetSubscribers(Document $project, callable $getProjectDB, Document $target)
private function deleteTargetSubscribers(Document $project, callable $getProjectDB, Document $target): void
{
/** @var Database */
$dbForProject = $getProjectDB($project);
@@ -279,7 +282,7 @@ class Deletes extends Action
* @return void
* @throws Exception
*/
private function deleteExpiredTargets(Document $project, callable $getProjectDB)
private function deleteExpiredTargets(Document $project, callable $getProjectDB): void
{
$this->deleteByGroup(
'targets',
@@ -293,6 +296,20 @@ class Deletes extends Action
);
}
private function deleteSessionTargets(Document $project, callable $getProjectDB, Document $session): void
{
$this->deleteByGroup(
'targets',
[
Query::equal('sessionInternalId', [$session->getInternalId()])
],
$getProjectDB($project),
function (Document $target) use ($getProjectDB, $project) {
$this->deleteTargetSubscribers($project, $getProjectDB, $target);
}
);
}
/**
* @param Document $project
* @param callable $getProjectDB
+173 -23
View File
@@ -116,7 +116,28 @@ abstract class Format
case 'account':
switch ($method) {
case 'createOAuth2Session':
return 'Provider';
switch ($param) {
case 'provider':
return 'OAuthProvider';
}
break;
case 'addAuthenticator':
case 'verifyAuthenticator':
case 'deleteAuthenticator':
switch ($param) {
case 'factor':
return 'AuthenticatorFactor';
case 'provider':
return 'AuthenticatorProvider';
}
break;
case 'createChallenge':
case 'verifyChallenge':
switch ($param) {
case 'provider':
return 'AuthenticatorProvider';
}
break;
}
break;
case 'avatars':
@@ -129,20 +150,16 @@ abstract class Format
return 'Flag';
}
break;
case 'storage':
switch ($method) {
case 'getFilePreview':
switch ($param) {
case 'gravity':
return 'ImageGravity';
case 'output':
return 'ImageFormat';
}
break;
}
break;
case 'databases':
switch ($method) {
case 'getUsage':
case 'getCollectionUsage':
case 'getDatabaseUsage':
switch ($param) {
case 'range':
return 'DatabaseUsageRange';
}
break;
case 'createRelationshipAttribute':
switch ($param) {
case 'type':
@@ -166,14 +183,144 @@ abstract class Format
}
}
break;
case 'functions':
switch ($method) {
case 'getUsage':
case 'getFunctionUsage':
switch ($param) {
case 'range':
return 'FunctionUsageRange';
}
break;
case 'createExecution':
switch ($param) {
case 'method':
return 'ExecutionMethod';
}
break;
}
break;
case 'messaging':
switch ($method) {
case 'getUsage':
switch ($param) {
case 'period':
return 'MessagingUsageRange';
}
break;
case 'createSMS':
case 'createPush':
case 'createEmail':
case 'updateSMS':
case 'updatePush':
case 'updateEmail':
switch ($param) {
case 'status':
return 'MessageType';
}
break;
case 'createSMTPProvider':
case 'updateSMTPProvider':
switch ($param) {
case 'encryption':
return 'SMTPEncryption';
}
break;
}
break;
case 'project':
switch ($method) {
case 'getUsage':
switch ($param) {
case 'period':
return 'ProjectUsageRange';
}
break;
}
break;
case 'projects':
switch ($method) {
case 'getSmsTemplate':
case 'getEmailTemplate':
case 'updateSmsTemplate':
case 'updateEmailTemplate':
case 'deleteSmsTemplate':
case 'deleteEmailTemplate':
switch ($param) {
case 'type':
return 'TemplateType';
case 'locale':
return 'TemplateLocale';
}
break;
case 'createPlatform':
switch ($param) {
case 'type':
return 'PlatformType';
}
break;
case 'createSmtpTest':
case 'updateSmtp':
switch ($param) {
case 'secure':
return 'SMTPSecure';
}
break;
case 'updateOAuth2':
switch ($param) {
case 'provider':
return 'OAuthProvider';
}
break;
case 'updateAuthStatus':
switch ($param) {
case 'method':
return 'AuthMethod';
}
break;
}
break;
case 'storage':
switch ($method) {
case 'getUsage':
case 'getBucketUsage':
switch ($param) {
case 'range':
return 'StorageUsageRange';
}
break;
case 'getFilePreview':
switch ($param) {
case 'gravity':
return 'ImageGravity';
case 'output':
return 'ImageFormat';
}
break;
}
break;
case 'users':
switch ($method) {
case 'getUsage':
switch ($param) {
case 'range':
return 'UserUsageRange';
}
break;
case 'deleteAuthenticator':
switch ($param) {
case 'factor':
return 'AuthenticatorFactor';
case 'provider':
return 'AuthenticatorProvider';
}
break;
case 'createTarget':
switch ($param) {
case 'providerType':
return 'MessagingProviderType';
}
break;
}
break;
}
@@ -211,27 +358,23 @@ abstract class Format
case 'getCollectionUsage':
case 'getDatabaseUsage':
// Range Enum Keys
$values = ['Twenty Four Hours', 'Seven Days', 'Thirty Days', 'Ninety Days'];
return $values;
return ['Twenty Four Hours', 'Thirty Days', 'Ninety Days'];
}
break;
case 'function':
case 'functions':
switch ($method) {
case 'getUsage':
case 'getFunctionUsage':
// Range Enum Keys
$values = ['Twenty Four Hours', 'Seven Days', 'Thirty Days', 'Ninety Days'];
return $values;
return ['Twenty Four Hours', 'Thirty Days', 'Ninety Days'];
}
break;
case 'users':
switch ($method) {
case 'getUsage':
case 'getUserUsage':
// Range Enum Keys
if ($param == 'range') {
$values = ['Twenty Four Hours', 'Seven Days', 'Thirty Days', 'Ninety Days'];
return $values;
return ['Twenty Four Hours', 'Thirty Days', 'Ninety Days'];
}
}
break;
@@ -240,9 +383,16 @@ abstract class Format
case 'getUsage':
case 'getBucketUsage':
// Range Enum Keys
$values = ['Twenty Four Hours', 'Seven Days', 'Thirty Days', 'Ninety Days'];
return $values;
return ['Twenty Four Hours', 'Thirty Days', 'Ninety Days'];
}
break;
case 'project':
switch ($method) {
case 'getUsage':
// Range Enum Keys
return ['One Hour', 'One Day'];
}
break;
}
return $values;
}
+26 -24
View File
@@ -8,7 +8,10 @@ use Appwrite\Utopia\Response\Model;
use Utopia\Database\Helpers\Permission;
use Utopia\Database\Helpers\Role;
use Utopia\Validator;
use Utopia\Validator\ArrayList;
use Utopia\Validator\Nullable;
use Utopia\Validator\Range;
use Utopia\Validator\WhiteList;
class OpenAPI3 extends Format
{
@@ -288,12 +291,6 @@ class OpenAPI3 extends Format
'required' => !$param['optional'],
];
foreach ($this->services as $service) {
if ($route->getLabel('sdk.namespace', 'default') === $service['name'] && in_array($name, $service['x-globalAttributes'] ?? [])) {
$node['x-global'] = true;
}
}
$isNullable = $validator instanceof Nullable;
if ($isNullable) {
@@ -302,6 +299,7 @@ class OpenAPI3 extends Format
}
switch ((!empty($validator)) ? \get_class($validator) : '') {
case 'Utopia\Database\Validator\UID':
case 'Utopia\Validator\Text':
$node['schema']['type'] = $validator->getType();
$node['schema']['x-example'] = '[' . \strtoupper(Template::fromCamelCaseToSnake($node['name'])) . ']';
@@ -310,10 +308,6 @@ class OpenAPI3 extends Format
$node['schema']['type'] = $validator->getType();
$node['schema']['x-example'] = false;
break;
case 'Utopia\Database\Validator\UID':
$node['schema']['type'] = $validator->getType();
$node['schema']['x-example'] = '[' . \strtoupper(Template::fromCamelCaseToSnake($node['name'])) . ']';
break;
case 'Appwrite\Utopia\Database\Validator\CustomId':
if ($route->getLabel('sdk.methodType', '') === 'upload') {
$node['schema']['x-upload-id'] = true;
@@ -331,6 +325,7 @@ class OpenAPI3 extends Format
$node['schema']['format'] = 'email';
$node['schema']['x-example'] = 'email@example.com';
break;
case 'Utopia\Validator\Host':
case 'Utopia\Validator\URL':
$node['schema']['type'] = $validator->getType();
$node['schema']['format'] = 'url';
@@ -342,7 +337,6 @@ class OpenAPI3 extends Format
$param['default'] = (empty($param['default'])) ? new \stdClass() : $param['default'];
$node['schema']['type'] = 'object';
$node['schema']['x-example'] = '{}';
//$node['schema']['format'] = 'json';
break;
case 'Utopia\Storage\Validator\File':
$consumes = ['multipart/form-data'];
@@ -350,25 +344,38 @@ class OpenAPI3 extends Format
$node['schema']['format'] = 'binary';
break;
case 'Utopia\Validator\ArrayList':
/** @var ArrayList $validator */
$node['schema']['type'] = 'array';
$node['schema']['items'] = [
'type' => $validator->getValidator()->getType(),
];
break;
case 'Appwrite\Utopia\Database\Validator\Queries\Attributes':
case 'Appwrite\Utopia\Database\Validator\Queries\Buckets':
case 'Appwrite\Utopia\Database\Validator\Queries\Collections':
case 'Appwrite\Utopia\Database\Validator\Queries\Indexes':
case 'Appwrite\Utopia\Database\Validator\Queries\Attributes':
case 'Appwrite\Utopia\Database\Validator\Queries\Databases':
case 'Appwrite\Utopia\Database\Validator\Queries\Deployments':
case 'Appwrite\Utopia\Database\Validator\Queries\Installations':
case 'Appwrite\Utopia\Database\Validator\Queries\Documents':
case 'Utopia\Database\Validator\Queries\Documents':
case 'Appwrite\Utopia\Database\Validator\Queries\Executions':
case 'Appwrite\Utopia\Database\Validator\Queries\Files':
case 'Appwrite\Utopia\Database\Validator\Queries\Functions':
case 'Appwrite\Utopia\Database\Validator\Queries\Rules':
case 'Appwrite\Utopia\Database\Validator\Queries\Identities':
case 'Appwrite\Utopia\Database\Validator\Queries\Indexes':
case 'Appwrite\Utopia\Database\Validator\Queries\Installations':
case 'Appwrite\Utopia\Database\Validator\Queries\Memberships':
case 'Appwrite\Utopia\Database\Validator\Queries\Messages':
case 'Appwrite\Utopia\Database\Validator\Queries\Migrations':
case 'Appwrite\Utopia\Database\Validator\Queries\Projects':
case 'Appwrite\Utopia\Database\Validator\Queries\Providers':
case 'Appwrite\Utopia\Database\Validator\Queries\Rules':
case 'Appwrite\Utopia\Database\Validator\Queries\Subscribers':
case 'Appwrite\Utopia\Database\Validator\Queries\Targets':
case 'Appwrite\Utopia\Database\Validator\Queries\Teams':
case 'Appwrite\Utopia\Database\Validator\Queries\Topics':
case 'Appwrite\Utopia\Database\Validator\Queries\Users':
case 'Appwrite\Utopia\Database\Validator\Queries\Variables':
case 'Utopia\Database\Validator\Queries':
case 'Utopia\Database\Validator\Queries\Document':
case 'Utopia\Database\Validator\Queries\Documents':
$node['schema']['type'] = 'array';
$node['schema']['items'] = [
'type' => 'string',
@@ -399,7 +406,7 @@ class OpenAPI3 extends Format
$node['schema']['x-example'] = '+12065550100'; // In the US, 555 is reserved like example.com
break;
case 'Utopia\Validator\Range':
/** @var \Utopia\Validator\Range $validator */
/** @var Range $validator */
$node['schema']['type'] = $validator->getType() === Validator::TYPE_FLOAT ? 'number' : $validator->getType();
$node['schema']['format'] = $validator->getType() == Validator::TYPE_INTEGER ? 'int32' : 'float';
$node['schema']['x-example'] = $validator->getMin();
@@ -416,13 +423,8 @@ class OpenAPI3 extends Format
case 'Utopia\Validator\Length':
$node['schema']['type'] = $validator->getType();
break;
case 'Utopia\Validator\Host':
$node['schema']['type'] = $validator->getType();
$node['schema']['format'] = 'url';
$node['schema']['x-example'] = 'https://example.com';
break;
case 'Utopia\Validator\WhiteList':
/** @var \Utopia\Validator\WhiteList $validator */
/** @var WhiteList $validator */
$node['schema']['type'] = $validator->getType();
$node['schema']['x-example'] = $validator->getList()[0];
+29 -28
View File
@@ -8,7 +8,9 @@ use Appwrite\Utopia\Response\Model;
use Utopia\Database\Helpers\Permission;
use Utopia\Database\Helpers\Role;
use Utopia\Validator;
use Utopia\Validator\ArrayList;
use Utopia\Validator\Nullable;
use Utopia\Validator\Range;
class Swagger2 extends Format
{
@@ -276,7 +278,7 @@ class Swagger2 extends Format
);
foreach ($parameters as $name => $param) { // Set params
/** @var \Utopia\Validator $validator */
/** @var Validator $validator */
$validator = (\is_callable($param['validator'])) ? call_user_func_array($param['validator'], $this->app->getResources($param['injections'])) : $param['validator'];
$node = [
@@ -285,12 +287,6 @@ class Swagger2 extends Format
'required' => !$param['optional'],
];
foreach ($this->services as $service) {
if ($route->getLabel('sdk.namespace', 'default') === $service['name'] && in_array($name, $service['x-globalAttributes'] ?? [])) {
$node['x-global'] = true;
}
}
$isNullable = $validator instanceof Nullable;
if ($isNullable) {
@@ -298,9 +294,9 @@ class Swagger2 extends Format
$validator = $validator->getValidator();
}
switch ((!empty($validator)) ? \get_class($validator) : '') {
case 'Utopia\Validator\Text':
case 'Utopia\Database\Validator\UID':
$node['type'] = $validator->getType();
$node['x-example'] = '[' . \strtoupper(Template::fromCamelCaseToSnake($node['name'])) . ']';
break;
@@ -315,10 +311,6 @@ class Swagger2 extends Format
$node['type'] = $validator->getType();
$node['x-example'] = '[' . \strtoupper(Template::fromCamelCaseToSnake($node['name'])) . ']';
break;
case 'Utopia\Database\Validator\UID':
$node['type'] = $validator->getType();
$node['x-example'] = '[' . \strtoupper(Template::fromCamelCaseToSnake($node['name'])) . ']';
break;
case 'Utopia\Database\Validator\DatetimeValidator':
$node['type'] = $validator->getType();
$node['format'] = 'datetime';
@@ -329,11 +321,20 @@ class Swagger2 extends Format
$node['format'] = 'email';
$node['x-example'] = 'email@example.com';
break;
case 'Utopia\Validator\Host':
case 'Utopia\Validator\URL':
$node['type'] = $validator->getType();
$node['format'] = 'url';
$node['x-example'] = 'https://example.com';
break;
case 'Utopia\Validator\ArrayList':
/** @var ArrayList $validator */
$node['type'] = 'array';
$node['collectionFormat'] = 'multi';
$node['items'] = [
'type' => $validator->getValidator()->getType(),
];
break;
case 'Utopia\Validator\JSON':
case 'Utopia\Validator\Mock':
case 'Utopia\Validator\Assoc':
@@ -345,26 +346,32 @@ class Swagger2 extends Format
$consumes = ['multipart/form-data'];
$node['type'] = 'file';
break;
case 'Utopia\Validator\ArrayList':
case 'Appwrite\Utopia\Database\Validator\Queries\Attributes':
case 'Appwrite\Utopia\Database\Validator\Queries\Buckets':
case 'Appwrite\Utopia\Database\Validator\Queries\Collections':
case 'Appwrite\Utopia\Database\Validator\Queries\Indexes':
case 'Appwrite\Utopia\Database\Validator\Queries\Attributes':
case 'Appwrite\Utopia\Database\Validator\Queries\Databases':
case 'Appwrite\Utopia\Database\Validator\Queries\Deployments':
case 'Appwrite\Utopia\Database\Validator\Queries\Installations':
case 'Appwrite\Utopia\Database\Validator\Queries\Documents':
case 'Utopia\Database\Validator\Queries\Documents':
case 'Appwrite\Utopia\Database\Validator\Queries\Executions':
case 'Appwrite\Utopia\Database\Validator\Queries\Files':
case 'Appwrite\Utopia\Database\Validator\Queries\Functions':
case 'Appwrite\Utopia\Database\Validator\Queries\Rules':
case 'Appwrite\Utopia\Database\Validator\Queries\Identities':
case 'Appwrite\Utopia\Database\Validator\Queries\Indexes':
case 'Appwrite\Utopia\Database\Validator\Queries\Installations':
case 'Appwrite\Utopia\Database\Validator\Queries\Memberships':
case 'Appwrite\Utopia\Database\Validator\Queries\Messages':
case 'Appwrite\Utopia\Database\Validator\Queries\Migrations':
case 'Appwrite\Utopia\Database\Validator\Queries\Projects':
case 'Appwrite\Utopia\Database\Validator\Queries\Providers':
case 'Appwrite\Utopia\Database\Validator\Queries\Rules':
case 'Appwrite\Utopia\Database\Validator\Queries\Subscribers':
case 'Appwrite\Utopia\Database\Validator\Queries\Targets':
case 'Appwrite\Utopia\Database\Validator\Queries\Teams':
case 'Appwrite\Utopia\Database\Validator\Queries\Topics':
case 'Appwrite\Utopia\Database\Validator\Queries\Users':
case 'Appwrite\Utopia\Database\Validator\Queries\Variables':
case 'Utopia\Database\Validator\Queries':
case 'Utopia\Database\Validator\Queries\Document':
case 'Utopia\Database\Validator\Queries\Documents':
$node['type'] = 'array';
$node['collectionFormat'] = 'multi';
$node['items'] = [
@@ -398,7 +405,7 @@ class Swagger2 extends Format
$node['x-example'] = '+12065550100';
break;
case 'Utopia\Validator\Range':
/** @var \Utopia\Validator\Range $validator */
/** @var Range $validator */
$node['type'] = $validator->getType() === Validator::TYPE_FLOAT ? 'number' : $validator->getType();
$node['format'] = $validator->getType() == Validator::TYPE_INTEGER ? 'int32' : 'float';
$node['x-example'] = $validator->getMin();
@@ -415,18 +422,12 @@ class Swagger2 extends Format
case 'Utopia\Validator\Length':
$node['type'] = $validator->getType();
break;
case 'Utopia\Validator\Host':
$node['type'] = $validator->getType();
$node['format'] = 'url';
$node['x-example'] = 'https://example.com';
break;
case 'Utopia\Validator\WhiteList':
/** @var \Utopia\Validator\WhiteList $validator */
$node['type'] = $validator->getType();
$node['x-example'] = $validator->getList()[0];
//Iterate from the blackList. If it matches with the current one, then it is a blackList
// Do not add the enum
//Iterate the blackList. If it matches with the current one, then it is blackListed
$allowed = true;
foreach ($this->enumBlacklist as $blacklist) {
if ($blacklist['namespace'] == $route->getLabel('sdk.namespace', '') && $blacklist['method'] == $method && $blacklist['parameter'] == $name) {
@@ -454,7 +455,7 @@ class Swagger2 extends Format
$node['default'] = $param['default'];
}
if (false !== \strpos($url, ':' . $name)) { // Param is in URL path
if (\str_contains($url, ':' . $name)) { // Param is in URL path
$node['in'] = 'path';
$temp['parameters'][] = $node;
} elseif ($route->getMethod() == 'GET') { // Param is in query
@@ -44,6 +44,21 @@ trait AccountBase
/**
* Test for FAILURE
*/
// Deny request from blocked IP
$response = $this->client->call(Client::METHOD_POST, '/account', array_merge([
'origin' => 'http://localhost',
'content-type' => 'application/json',
'x-appwrite-project' => 'console',
'x-forwarded-for' => '103.152.127.250' // Test IP for denied access region
]), [
'userId' => ID::unique(),
'email' => $email,
'password' => $password,
'name' => $name,
]);
$this->assertEquals(451, $response['headers']['status-code']);
$response = $this->client->call(Client::METHOD_POST, '/account', array_merge([
'origin' => 'http://localhost',
'content-type' => 'application/json',