1
0
Fork 0
mirror of synced 2024-06-01 18:39:57 +12:00

Merge branch '0.8.x' into refactor-event-payload-to-data

This commit is contained in:
kodumbeats 2021-03-29 15:32:14 -04:00 committed by GitHub
commit d4b107bf1d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
57 changed files with 1469 additions and 244 deletions

2
.env
View file

@ -16,7 +16,7 @@ _APP_DB_PORT=3306
_APP_DB_SCHEMA=appwrite
_APP_DB_USER=user
_APP_DB_PASS=password
_APP_STORAGE_ANTIVIRUS=disabled
_APP_STORAGE_ANTIVIRUS=enabled
_APP_STORAGE_ANTIVIRUS_HOST=clamav
_APP_STORAGE_ANTIVIRUS_PORT=3310
_APP_INFLUXDB_HOST=influxdb

View file

@ -1,17 +1,39 @@
# Version 0.8.0 (Not Released Yet)
## Features
- Anonymous login (#914)
- Added Anonymous Login ([RFC-010](https://github.com/appwrite/rfc/blob/main/010-anonymous-login.md), #914)
- Added new Environment Variable to enable or disable Anonymous Login
- Added events for functions and executions (#971)
## Bugs
- Fixed default value for HTTPS force option
## Breaking Changes
- Only logged in users can execute functions (for guests, use anonymous login)
- Only the user who has triggered the execution get access to the relevant execution logs
# Version 0.7.2
## Features
- When creating new resources from the client API, the current user gets both read & write permissions by default. (#1007)
- Added timestamp to errors logs on the HTTP API container (#1002)
- Added verbose tests output on the terminal and CI (#1006)
## Upgrades
- Upgraded ClamAV to version 1.3.0
- Upgraded utopia-php/abuse to version 0.4.0
- Upgraded utopia-php/analytics to version 0.2.0
## Bugs
- Fixed certificates worker error on successful operations (#1010)
- Fixed head requests not responding (#998)
- Fixed bug when using auth credential for the Redis container (#993)
- Fixed server warning logs on 3** redirect endpoints (#1013)
# Version 0.7.1

View file

@ -92,7 +92,7 @@ After finishing the installation process, you can start writing and editing code
#### Advanced Topics
We love to create issues that are good for begginers and label them as `good for begginers` or `hacktoberfest`, but some more advanced topics might require extra knowledge. Below is a list of links you can use to learn more about some of the more advance topics that will help you master the Appwrite codebase.
We love to create issues that are good for beginners and label them as `good first issue` or `hacktoberfest`, but some more advanced topics might require extra knowledge. Below is a list of links you can use to learn more about some of the more advance topics that will help you master the Appwrite codebase.
##### Tools and Libs
- [Docker](https://www.docker.com/get-started)
@ -365,6 +365,7 @@ From time to time, our team will add tutorials that will help contributors find
* [Adding Support for a New OAuth2 Provider](./docs/tutorials/add-oauth2-provider.md)
* [Appwrite Environment Variables](./docs/tutorials/environment-variables.md)
* [Running in Production](./docs/tutorials/running-in-production.md)
* [Adding Storage Adapter](./docs/tutorials/add-storage-adapter.md)
## Other Ways to Help

View file

@ -16,7 +16,7 @@
Appwrite is an end-to-end backend server for Web, Mobile, Native, or Backend apps packaged as a set of Docker<nobr> microservices. Appwrite abstracts the complexity and repetitiveness required to build a modern backend API from scratch and allows you to build secure apps faster.
Using Appwrite, you can easily integrate your app with user authentication & multiple sign-in methods, a database for storing and querying users and team data, storage and file management, image manipulation, schedule CRON tasks, and [more services](https://appwrite.io/docs).
Using Appwrite, you can easily integrate your app with user authentication & multiple sign-in methods, a database for storing and querying users and team data, storage and file management, image manipulation, Cloud Functions, and [more services](https://appwrite.io/docs).
![Appwrite](public/images/github.png)
@ -53,7 +53,7 @@ docker run -it --rm \
--volume /var/run/docker.sock:/var/run/docker.sock \
--volume "$(pwd)"/appwrite:/usr/src/code/appwrite:rw \
--entrypoint="install" \
appwrite/appwrite:0.7.1
appwrite/appwrite:0.8.0
```
### Windows
@ -65,7 +65,7 @@ docker run -it --rm ^
--volume //var/run/docker.sock:/var/run/docker.sock ^
--volume "%cd%"/appwrite:/usr/src/code/appwrite:rw ^
--entrypoint="install" ^
appwrite/appwrite:0.7.1
appwrite/appwrite:0.8.0
```
#### PowerShell
@ -75,13 +75,13 @@ docker run -it --rm ,
--volume /var/run/docker.sock:/var/run/docker.sock ,
--volume ${pwd}/appwrite:/usr/src/code/appwrite:rw ,
--entrypoint="install" ,
appwrite/appwrite:0.7.1
appwrite/appwrite:0.8.0
```
Once the Docker installation completes, go to http://localhost to access the Appwrite console from your browser. Please note that on non-linux native hosts, the server might take a few minutes to start after installation completes.
For advanced production and custom installation, check out our Docker [environment variables](docs/tutorials/environment-variables.md) docs. You can also use our public [docker-compose.yml](https://appwrite.io/docker-compose.yml) file to manually set up an environment.
For advanced production and custom installation, check out our Docker [environment variables](https://appwrite.io/docs/environment-variables) docs. You can also use our public [docker-compose.yml](https://gist.github.com/eldadfux/977869ff6bdd7312adfd4e629ee15cc5#file-docker-compose-yml) file to manually set up an environment.
### Upgrade from an Older Version

View file

@ -204,7 +204,7 @@ $collections = [
'key' => 'email',
'type' => Database::SYSTEM_VAR_TYPE_EMAIL,
'default' => '',
'required' => true,
'required' => false,
'array' => false,
],
[
@ -222,7 +222,7 @@ $collections = [
'key' => 'password',
'type' => Database::SYSTEM_VAR_TYPE_TEXT,
'default' => '',
'required' => true,
'required' => false,
'array' => false,
],
[
@ -271,6 +271,16 @@ $collections = [
'required' => true,
'array' => false,
],
[
'$collection' => Database::SYSTEM_COLLECTION_RULES,
'label' => 'Sessions',
'key' => 'sessions',
'type' => Database::SYSTEM_VAR_TYPE_DOCUMENT,
'default' => [],
'required' => false,
'array' => true,
'list' => [Database::SYSTEM_COLLECTION_SESSIONS],
],
[
'$collection' => Database::SYSTEM_COLLECTION_RULES,
'label' => 'Tokens',
@ -293,11 +303,11 @@ $collections = [
],
],
],
Database::SYSTEM_COLLECTION_TOKENS => [
Database::SYSTEM_COLLECTION_SESSIONS => [
'$collection' => Database::SYSTEM_COLLECTION_COLLECTIONS,
'$id' => Database::SYSTEM_COLLECTION_TOKENS,
'$id' => Database::SYSTEM_COLLECTION_SESSIONS,
'$permissions' => ['read' => ['*']],
'name' => 'Token',
'name' => 'Session',
'structure' => true,
'rules' => [
[
@ -306,16 +316,34 @@ $collections = [
'key' => 'userId',
'type' => Database::SYSTEM_VAR_TYPE_TEXT,
'default' => null,
'required' => true,
'array' => false,
],
[
'$collection' => Database::SYSTEM_COLLECTION_RULES,
'label' => 'Provider',
'key' => 'provider',
'type' => Database::SYSTEM_VAR_TYPE_TEXT,
'default' => '',
'required' => true,
'array' => false,
],
[
'$collection' => Database::SYSTEM_COLLECTION_RULES,
'label' => 'Provider User Identifier',
'key' => 'providerUid',
'type' => Database::SYSTEM_VAR_TYPE_TEXT,
'default' => '',
'required' => false,
'array' => false,
],
[
'$collection' => Database::SYSTEM_COLLECTION_RULES,
'label' => 'Type',
'key' => 'type',
'type' => Database::SYSTEM_VAR_TYPE_NUMERIC,
'default' => null,
'required' => true,
'label' => 'Provider Token',
'key' => 'providerToken',
'type' => Database::SYSTEM_VAR_TYPE_TEXT,
'default' => '',
'required' => false,
'array' => false,
],
[
@ -473,6 +501,69 @@ $collections = [
],
],
],
Database::SYSTEM_COLLECTION_TOKENS => [
'$collection' => Database::SYSTEM_COLLECTION_COLLECTIONS,
'$id' => Database::SYSTEM_COLLECTION_TOKENS,
'$permissions' => ['read' => ['*']],
'name' => 'Token',
'structure' => true,
'rules' => [
[
'$collection' => Database::SYSTEM_COLLECTION_RULES,
'label' => 'User ID',
'key' => 'userId',
'type' => Database::SYSTEM_VAR_TYPE_TEXT,
'default' => null,
'required' => false,
'array' => false,
],
[
'$collection' => Database::SYSTEM_COLLECTION_RULES,
'label' => 'Type',
'key' => 'type',
'type' => Database::SYSTEM_VAR_TYPE_NUMERIC,
'default' => null,
'required' => true,
'array' => false,
],
[
'$collection' => Database::SYSTEM_COLLECTION_RULES,
'label' => 'Secret',
'key' => 'secret',
'type' => Database::SYSTEM_VAR_TYPE_TEXT,
'default' => '',
'required' => true,
'array' => false,
],
[
'$collection' => Database::SYSTEM_COLLECTION_RULES,
'label' => 'Expire',
'key' => 'expire',
'type' => Database::SYSTEM_VAR_TYPE_NUMERIC,
'default' => 0,
'required' => true,
'array' => false,
],
[
'$collection' => Database::SYSTEM_COLLECTION_RULES,
'label' => 'User Agent',
'key' => 'userAgent',
'type' => Database::SYSTEM_VAR_TYPE_TEXT,
'default' => '',
'required' => true,
'array' => false,
],
[
'$collection' => Database::SYSTEM_COLLECTION_RULES,
'label' => 'IP',
'key' => 'ip',
'type' => Database::SYSTEM_VAR_TYPE_IP,
'default' => '',
'required' => true,
'array' => false,
],
],
],
Database::SYSTEM_COLLECTION_MEMBERSHIPS => [
'$collection' => Database::SYSTEM_COLLECTION_COLLECTIONS,
'$id' => Database::SYSTEM_COLLECTION_MEMBERSHIPS,
@ -1617,26 +1708,6 @@ foreach ($providers as $index => $provider) {
'array' => false,
'filter' => ['encrypt'],
];
$collections[Database::SYSTEM_COLLECTION_USERS]['rules'][] = [
'$collection' => Database::SYSTEM_COLLECTION_RULES,
'label' => 'OAuth2 '.\ucfirst($index).' ID',
'key' => 'oauth2'.\ucfirst($index),
'type' => Database::SYSTEM_VAR_TYPE_TEXT,
'default' => '',
'required' => false,
'array' => false,
];
$collections[Database::SYSTEM_COLLECTION_USERS]['rules'][] = [
'$collection' => Database::SYSTEM_COLLECTION_RULES,
'label' => 'OAuth2 '.\ucfirst($index).' Access Token',
'key' => 'oauth2'.\ucfirst($index).'AccessToken',
'type' => Database::SYSTEM_VAR_TYPE_TEXT,
'default' => '',
'required' => false,
'array' => false,
];
}
return $collections;

View file

@ -32,7 +32,7 @@ return [
[
'key' => 'flutter',
'name' => 'Flutter',
'version' => '0.4.0-dev.3',
'version' => '0.4.0',
'url' => 'https://github.com/appwrite/sdk-for-flutter',
'package' => 'https://pub.dev/packages/appwrite',
'enabled' => true,

View file

@ -27,7 +27,7 @@ return [
'name' => '_APP_OPTIONS_FORCE_HTTPS',
'description' => 'Allows you to force HTTPS connection to your API. This feature redirects any HTTP call to HTTPS and adds the \'Strict-Transport-Security\' header to all HTTP responses. By default, set to \'disabled\'. To enable, set to \'enabled\'. This feature will work only when your ports are set to default 80 and 443.',
'introduction' => '',
'default' => 'enabled',
'default' => 'disabled',
'required' => false,
'question' => '',
],
@ -118,7 +118,7 @@ return [
'default' => 'enabled',
'required' => false,
'question' => '',
],
]
],
],
[

View file

@ -109,7 +109,7 @@ App::post('/v1/account')
throw new Exception('Account already exists', 409);
}
Authorization::enable();
Authorization::reset();
Authorization::unsetRole('role:'.Auth::USER_ROLE_GUEST);
Authorization::setRole('user:'.$user->getId());
@ -190,10 +190,11 @@ App::post('/v1/account/sessions')
$secret = Auth::tokenGenerator();
$session = new Document(array_merge(
[
'$collection' => Database::SYSTEM_COLLECTION_TOKENS,
'$collection' => Database::SYSTEM_COLLECTION_SESSIONS,
'$permissions' => ['read' => ['user:'.$profile->getId()], 'write' => ['user:'.$profile->getId()]],
'userId' => $profile->getId(),
'type' => Auth::TOKEN_TYPE_LOGIN,
'provider' => Auth::SESSION_PROVIDER_EMAIL,
'providerUid' => $email,
'secret' => Auth::hash($secret), // One way hash encryption to protect DB leak
'expire' => $expiry,
'userAgent' => $request->getUserAgent('UNKNOWN'),
@ -210,7 +211,7 @@ App::post('/v1/account/sessions')
throw new Exception('Failed saving session to DB', 500);
}
$profile->setAttribute('tokens', $session, Document::SET_TYPE_APPEND);
$profile->setAttribute('sessions', $session, Document::SET_TYPE_APPEND);
$profile = $projectDB->updateDocument($profile->getArrayCopy());
@ -441,7 +442,7 @@ App::get('/v1/account/sessions/oauth2/:provider/redirect')
throw new Exception('Missing ID from OAuth2 provider', 400);
}
$current = Auth::tokenVerify($user->getAttribute('tokens', []), Auth::TOKEN_TYPE_LOGIN, Auth::$secret);
$current = Auth::sessionVerify($user->getAttribute('sessions', []), Auth::$secret);
if ($current) {
$projectDB->deleteDocument($current); //throw new Exception('User already logged in', 401);
@ -451,7 +452,8 @@ App::get('/v1/account/sessions/oauth2/:provider/redirect')
'limit' => 1,
'filters' => [
'$collection='.Database::SYSTEM_COLLECTION_USERS,
'oauth2'.\ucfirst($provider).'='.$oauth2ID,
'sessions.provider='.$provider,
'sessions.providerUid='.$oauth2ID
],
]) : $user;
@ -487,7 +489,7 @@ App::get('/v1/account/sessions/oauth2/:provider/redirect')
throw new Exception('Account already exists', 409);
}
Authorization::enable();
Authorization::reset();
if (false === $user) {
throw new Exception('Failed saving user to DB', 500);
@ -506,10 +508,12 @@ App::get('/v1/account/sessions/oauth2/:provider/redirect')
$secret = Auth::tokenGenerator();
$expiry = \time() + Auth::TOKEN_EXPIRATION_LOGIN_LONG;
$session = new Document(array_merge([
'$collection' => Database::SYSTEM_COLLECTION_TOKENS,
'$collection' => Database::SYSTEM_COLLECTION_SESSIONS,
'$permissions' => ['read' => ['user:'.$user['$id']], 'write' => ['user:'.$user['$id']]],
'userId' => $user->getId(),
'type' => Auth::TOKEN_TYPE_LOGIN,
'provider' => $provider,
'providerUid' => $oauth2ID,
'providerToken' => $accessToken,
'secret' => Auth::hash($secret), // One way hash encryption to protect DB leak
'expire' => $expiry,
'userAgent' => $request->getUserAgent('UNKNOWN'),
@ -517,11 +521,18 @@ App::get('/v1/account/sessions/oauth2/:provider/redirect')
'countryCode' => ($record) ? \strtolower($record['country']['iso_code']) : '--',
], $detector->getOS(), $detector->getClient(), $detector->getDevice()));
$isAnonymousUser = is_null($user->getAttribute('email')) && is_null($user->getAttribute('password'));
if ($isAnonymousUser) {
$user
->setAttribute('name', $oauth2->getUserName($accessToken))
->setAttribute('email', $oauth2->getUserEmail($accessToken))
;
}
$user
->setAttribute('oauth2'.\ucfirst($provider), $oauth2ID)
->setAttribute('oauth2'.\ucfirst($provider).'AccessToken', $accessToken)
->setAttribute('status', Auth::USER_STATUS_ACTIVATED)
->setAttribute('tokens', $session, Document::SET_TYPE_APPEND)
->setAttribute('sessions', $session, Document::SET_TYPE_APPEND)
;
Authorization::setRole('user:'.$user->getId());
@ -566,6 +577,130 @@ App::get('/v1/account/sessions/oauth2/:provider/redirect')
;
});
App::post('/v1/account/sessions/anonymous')
->desc('Create Anonymous Session')
->groups(['api', 'account'])
->label('event', 'account.sessions.create')
->label('scope', 'public')
->label('sdk.platform', [APP_PLATFORM_CLIENT])
->label('sdk.namespace', 'account')
->label('sdk.method', 'createAnonymousSession')
->label('sdk.description', '/docs/references/account/create-session-anonymous.md')
->label('sdk.response.code', Response::STATUS_CODE_CREATED)
->label('sdk.response.type', Response::CONTENT_TYPE_JSON)
->label('sdk.response.model', Response::MODEL_SESSION)
->label('abuse-limit', 50)
->label('abuse-key', 'ip:{ip}')
->inject('request')
->inject('response')
->inject('locale')
->inject('user')
->inject('project')
->inject('projectDB')
->inject('geodb')
->inject('audits')
->action(function ($request, $response, $locale, $user, $project, $projectDB, $geodb, $audits) {
/** @var Utopia\Swoole\Request $request */
/** @var Appwrite\Utopia\Response $response */
/** @var Utopia\Locale\Locale $locale */
/** @var Appwrite\Database\Document $user */
/** @var Appwrite\Database\Document $project */
/** @var Appwrite\Database\Database $projectDB */
/** @var MaxMind\Db\Reader $geodb */
/** @var Appwrite\Event\Event $audits */
$protocol = $request->getProtocol();
if ($user->getId() || 'console' === $project->getId()) {
throw new Exception('Failed to create anonymous user.', 401);
}
Authorization::disable();
try {
$user = $projectDB->createDocument([
'$collection' => Database::SYSTEM_COLLECTION_USERS,
'$permissions' => [
'read' => ['*'],
'write' => ['user:{self}']
],
'email' => null,
'emailVerification' => false,
'status' => Auth::USER_STATUS_UNACTIVATED,
'password' => null,
'passwordUpdate' => \time(),
'registration' => \time(),
'reset' => false,
'name' => null
]);
} catch (Exception $th) {
throw new Exception('Failed saving user to DB', 500);
}
Authorization::reset();
if (false === $user) {
throw new Exception('Failed saving user to DB', 500);
}
// Create session token
$detector = new Detector($request->getUserAgent('UNKNOWN'));
$record = $geodb->get($request->getIP());
$secret = Auth::tokenGenerator();
$expiry = \time() + Auth::TOKEN_EXPIRATION_LOGIN_LONG;
$session = new Document(array_merge(
[
'$collection' => Database::SYSTEM_COLLECTION_SESSIONS,
'$permissions' => ['read' => ['user:' . $user['$id']], 'write' => ['user:' . $user['$id']]],
'userId' => $user->getId(),
'provider' => Auth::SESSION_PROVIDER_ANONYMOUS,
'secret' => Auth::hash($secret), // One way hash encryption to protect DB leak
'expire' => $expiry,
'userAgent' => $request->getUserAgent('UNKNOWN'),
'ip' => $request->getIP(),
'countryCode' => ($record) ? \strtolower($record['country']['iso_code']) : '--',
],
$detector->getOS(),
$detector->getClient(),
$detector->getDevice()
));
$user->setAttribute('sessions', $session, Document::SET_TYPE_APPEND);
Authorization::setRole('user:'.$user->getId());
$user = $projectDB->updateDocument($user->getArrayCopy());
if (false === $user) {
throw new Exception('Failed saving user to DB', 500);
}
$audits
->setParam('userId', $user->getId())
->setParam('event', 'account.sessions.create')
->setParam('resource', 'users/'.$user->getId())
;
if (!Config::getParam('domainVerification')) {
$response
->addHeader('X-Fallback-Cookies', \json_encode([Auth::$cookieName => Auth::encodeSession($user->getId(), $secret)]))
;
}
$response
->addCookie(Auth::$cookieName.'_legacy', Auth::encodeSession($user->getId(), $secret), $expiry, '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, null)
->addCookie(Auth::$cookieName, Auth::encodeSession($user->getId(), $secret), $expiry, '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, Config::getParam('cookieSamesite'))
->setStatusCode(Response::STATUS_CODE_CREATED)
;
$session
->setAttribute('current', true)
->setAttribute('countryName', (isset($countries[$session->getAttribute('countryCode')])) ? $countries[$session->getAttribute('countryCode')] : $locale->getText('locale.country.unknown'))
;
$response->dynamic($session, Response::MODEL_SESSION);
});
App::post('/v1/account/jwt')
->desc('Create Account JWT')
->groups(['api', 'account'])
@ -583,16 +718,18 @@ App::post('/v1/account/jwt')
/** @var Appwrite\Utopia\Response $response */
/** @var Appwrite\Database\Document $user */
$tokens = $user->getAttribute('tokens', []);
$session = new Document();
$sessions = $user->getAttribute('sessions', []);
$current = new Document();
foreach ($tokens as $token) { /** @var Appwrite\Database\Document $token */
if ($token->getAttribute('secret') == Auth::hash(Auth::$secret)) { // If current session delete the cookies too
$session = $token;
foreach ($sessions as $session) {
/** @var Appwrite\Database\Document $session */
if ($session->getAttribute('secret') == Auth::hash(Auth::$secret)) { // If current session delete the cookies too
$current = $session;
}
}
if($session->isEmpty()) {
if($current->isEmpty()) {
throw new Exception('No valid session found', 401);
}
@ -606,7 +743,7 @@ App::post('/v1/account/jwt')
// 'scopes' => ['user'],
// 'iss' => 'http://api.mysite.com',
'userId' => $user->getId(),
'sessionId' => $session->getId(),
'sessionId' => $current->getId(),
])]), Response::MODEL_JWT);
});
@ -671,22 +808,19 @@ App::get('/v1/account/sessions')
/** @var Appwrite\Database\Document $user */
/** @var Utopia\Locale\Locale $locale */
$tokens = $user->getAttribute('tokens', []);
$sessions = [];
$sessions = $user->getAttribute('sessions', []);
$countries = $locale->getText('countries');
$current = Auth::tokenVerify($tokens, Auth::TOKEN_TYPE_LOGIN, Auth::$secret);
$current = Auth::sessionVerify($sessions, Auth::$secret);
foreach ($tokens as $token) { /* @var $token Document */
if (Auth::TOKEN_TYPE_LOGIN != $token->getAttribute('type')) {
continue;
}
foreach ($sessions as $key => $session) {
/** @var Document $session */
$token->setAttribute('countryName', (isset($countries[strtoupper($token->getAttribute('countryCode'))]))
? $countries[strtoupper($token->getAttribute('countryCode'))]
$session->setAttribute('countryName', (isset($countries[strtoupper($session->getAttribute('countryCode'))]))
? $countries[strtoupper($session->getAttribute('countryCode'))]
: $locale->getText('locale.country.unknown'));
$token->setAttribute('current', ($current == $token->getId()) ? true : false);
$session->setAttribute('current', ($current == $session->getId()) ? true : false);
$sessions[] = $token;
$sessions[$key] = $session;
}
$response->dynamic(new Document([
@ -880,7 +1014,12 @@ App::patch('/v1/account/email')
/** @var Appwrite\Database\Database $projectDB */
/** @var Appwrite\Event\Event $audits */
if (!Auth::passwordVerify($password, $user->getAttribute('password'))) { // Double check user password
$isAnonymousUser = is_null($user->getAttribute('email')) && is_null($user->getAttribute('password')); // Check if request is from an anonymous account for converting
if (
!$isAnonymousUser &&
!Auth::passwordVerify($password, $user->getAttribute('password'))
) { // Double check user password
throw new Exception('Invalid credentials', 401);
}
@ -898,10 +1037,14 @@ App::patch('/v1/account/email')
// TODO after this user needs to confirm mail again
$user = $projectDB->updateDocument(\array_merge($user->getArrayCopy(), [
'email' => $email,
'emailVerification' => false,
]));
$user = $projectDB->updateDocument(\array_merge(
$user->getArrayCopy(),
($isAnonymousUser ? [ 'password' => Auth::passwordHash($password) ] : []),
[
'email' => $email,
'emailVerification' => false,
]
));
if (false === $user) {
throw new Exception('Failed saving user to DB', 500);
@ -1050,14 +1193,16 @@ App::delete('/v1/account/sessions/:sessionId')
$protocol = $request->getProtocol();
$sessionId = ($sessionId === 'current')
? Auth::tokenVerify($user->getAttribute('tokens'), Auth::TOKEN_TYPE_LOGIN, Auth::$secret)
? Auth::sessionVerify($user->getAttribute('sessions'), Auth::$secret)
: $sessionId;
$tokens = $user->getAttribute('tokens', []);
$sessions = $user->getAttribute('sessions', []);
foreach ($tokens as $token) { /* @var $token Document */
if (($sessionId == $token->getId()) && Auth::TOKEN_TYPE_LOGIN == $token->getAttribute('type')) {
if (!$projectDB->deleteDocument($token->getId())) {
foreach ($sessions as $session) {
/** @var Document $session */
if (($sessionId == $session->getId())) {
if (!$projectDB->deleteDocument($session->getId())) {
throw new Exception('Failed to remove token from DB', 500);
}
@ -1073,10 +1218,10 @@ App::delete('/v1/account/sessions/:sessionId')
;
}
$token->setAttribute('current', false);
$session->setAttribute('current', false);
if ($token->getAttribute('secret') == Auth::hash(Auth::$secret)) { // If current session delete the cookies too
$token->setAttribute('current', true);
if ($session->getAttribute('secret') == Auth::hash(Auth::$secret)) { // If current session delete the cookies too
$session->setAttribute('current', true);
$response
->addCookie(Auth::$cookieName.'_legacy', '', \time() - 3600, '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, null)
@ -1085,7 +1230,7 @@ App::delete('/v1/account/sessions/:sessionId')
}
$events
->setParam('eventData', $response->output($token, Response::MODEL_SESSION))
->setParam('eventData', $response->output($session, Response::MODEL_SESSION))
;
return $response->noContent();
@ -1122,10 +1267,12 @@ App::delete('/v1/account/sessions')
/** @var Appwrite\Event\Event $events */
$protocol = $request->getProtocol();
$tokens = $user->getAttribute('tokens', []);
$sessions = $user->getAttribute('sessions', []);
foreach ($tokens as $token) { /* @var $token Document */
if (!$projectDB->deleteDocument($token->getId())) {
foreach ($sessions as $session) {
/** @var Document $session */
if (!$projectDB->deleteDocument($session->getId())) {
throw new Exception('Failed to remove token from DB', 500);
}
@ -1141,10 +1288,10 @@ App::delete('/v1/account/sessions')
;
}
$token->setAttribute('current', false);
$session->setAttribute('current', false);
if ($token->getAttribute('secret') == Auth::hash(Auth::$secret)) { // If current session delete the cookies too
$token->setAttribute('current', true);
if ($session->getAttribute('secret') == Auth::hash(Auth::$secret)) { // If current session delete the cookies too
$session->setAttribute('current', true);
$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'))
@ -1154,8 +1301,8 @@ App::delete('/v1/account/sessions')
$events
->setParam('eventData', $response->output(new Document([
'sum' => count($tokens),
'sessions' => $tokens
'sum' => count($sessions),
'sessions' => $sessions
]), Response::MODEL_SESSION_LIST))
;

View file

@ -169,8 +169,8 @@ App::put('/v1/database/collections/:collectionId')
->label('sdk.response.model', Response::MODEL_COLLECTION)
->param('collectionId', '', new UID(), 'Collection unique ID.')
->param('name', null, new Text(128), 'Collection name. Max length: 128 chars.')
->param('read', [], new ArrayList(new Text(64)), 'An array of strings with read permissions. By default no user is granted with any read permissions. [learn more about permissions(/docs/permissions) and get a full list of available permissions.')
->param('write', [], new ArrayList(new Text(64)), 'An array of strings with write permissions. By default no user is granted with any write permissions. [learn more about permissions](/docs/permissions) and get a full list of available permissions.')
->param('read', null, new ArrayList(new Text(64)), 'An array of strings with read permissions. By default inherits the existing read permissions. [learn more about permissions](/docs/permissions) and get a full list of available permissions.', true)
->param('write', null, new ArrayList(new Text(64)), 'An array of strings with write permissions. By default inherits the existing write permissions. [learn more about permissions](/docs/permissions) and get a full list of available permissions.', true)
->param('rules', [], function ($projectDB) { return new ArrayList(new Collection($projectDB, [Database::SYSTEM_COLLECTION_RULES], ['$collection' => Database::SYSTEM_COLLECTION_RULES, '$permissions' => ['read' => [], 'write' => []]])); }, 'Array of [rule objects](/docs/rules). Each rule define a collection field name, data type and validation.', true, ['projectDB'])
->inject('response')
->inject('projectDB')
@ -187,6 +187,8 @@ App::put('/v1/database/collections/:collectionId')
}
$parsedRules = [];
$read = (is_null($read)) ? ($collection->getPermissions()['read'] ?? []) : $read; // By default inherit read permissions
$write = (is_null($write)) ? ($collection->getPermissions()['write'] ?? []) : $write; // By default inherit write permissions
foreach ($rules as &$rule) {
$parsedRules[] = \array_merge([
@ -295,17 +297,19 @@ App::post('/v1/database/collections/:collectionId/documents')
->label('sdk.response.model', Response::MODEL_ANY)
->param('collectionId', null, new UID(), 'Collection unique ID. You can create a new collection with validation rules using the Database service [server integration](/docs/server/database#createCollection).')
->param('data', [], new JSON(), 'Document data as JSON object.')
->param('read', [], new ArrayList(new Text(64)), 'An array of strings with read permissions. By default no user is granted with any read permissions. [learn more about permissions](/docs/permissions) and get a full list of available permissions.')
->param('write', [], new ArrayList(new Text(64)), 'An array of strings with write permissions. By default no user is granted with any write permissions. [learn more about permissions](/docs/permissions) and get a full list of available permissions.')
->param('read', null, new ArrayList(new Text(64)), 'An array of strings with read permissions. By default only the current user is granted with read permissions. [learn more about permissions](/docs/permissions) and get a full list of available permissions.', true)
->param('write', null, new ArrayList(new Text(64)), 'An array of strings with write permissions. By default only the current user is granted with write permissions. [learn more about permissions](/docs/permissions) and get a full list of available permissions.', true)
->param('parentDocument', '', new UID(), 'Parent document unique ID. Use when you want your new document to be a child of a parent document.', true)
->param('parentProperty', '', new Key(), 'Parent document property name. Use when you want your new document to be a child of a parent document.', true)
->param('parentPropertyType', Document::SET_TYPE_ASSIGN, new WhiteList([Document::SET_TYPE_ASSIGN, Document::SET_TYPE_APPEND, Document::SET_TYPE_PREPEND], true), 'Parent document property connection type. You can set this value to **assign**, **append** or **prepend**, default value is assign. Use when you want your new document to be a child of a parent document.', true)
->inject('response')
->inject('projectDB')
->inject('user')
->inject('audits')
->action(function ($collectionId, $data, $read, $write, $parentDocument, $parentProperty, $parentPropertyType, $response, $projectDB, $audits) {
->action(function ($collectionId, $data, $read, $write, $parentDocument, $parentProperty, $parentPropertyType, $response, $projectDB, $user, $audits) {
/** @var Appwrite\Utopia\Response $response */
/** @var Appwrite\Database\Database $projectDB */
/** @var Appwrite\Database\Document $user */
/** @var Appwrite\Event\Event $audits */
$data = (\is_string($data)) ? \json_decode($data, true) : $data; // Cast to JSON array
@ -326,8 +330,8 @@ App::post('/v1/database/collections/:collectionId/documents')
$data['$collection'] = $collectionId; // Adding this param to make API easier for developers
$data['$permissions'] = [
'read' => $read,
'write' => $write,
'read' => (is_null($read) && !$user->isEmpty()) ? ['user:'.$user->getId()] : $read ?? [], // By default set read permissions for user
'write' => (is_null($write) && !$user->isEmpty()) ? ['user:'.$user->getId()] : $write ?? [], // By default set write permissions for user
];
// Read parent document + validate not 404 + validate read / write permission like patch method
@ -508,8 +512,8 @@ App::patch('/v1/database/collections/:collectionId/documents/:documentId')
->param('collectionId', null, new UID(), 'Collection unique ID. You can create a new collection with validation rules using the Database service [server integration](/docs/server/database#createCollection).')
->param('documentId', null, new UID(), 'Document unique ID.')
->param('data', [], new JSON(), 'Document data as JSON object.')
->param('read', [], new ArrayList(new Text(64)), 'An array of strings with read permissions. By default no user is granted with any read permissions. [learn more about permissions](/docs/permissions) and get a full list of available permissions.')
->param('write', [], new ArrayList(new Text(64)), 'An array of strings with write permissions. By default no user is granted with any write permissions. [learn more about permissions](/docs/permissions) and get a full list of available permissions.')
->param('read', null, new ArrayList(new Text(64)), 'An array of strings with read permissions. By default inherits the existing read permissions. [learn more about permissions](/docs/permissions) and get a full list of available permissions.', true)
->param('write', null, new ArrayList(new Text(64)), 'An array of strings with write permissions. By default inherits the existing write permissions. [learn more about permissions](/docs/permissions) and get a full list of available permissions.', true)
->inject('response')
->inject('projectDB')
->inject('audits')
@ -522,7 +526,7 @@ App::patch('/v1/database/collections/:collectionId/documents/:documentId')
$document = $projectDB->getDocument($documentId, false);
$data = (\is_string($data)) ? \json_decode($data, true) : $data; // Cast to JSON array
if (!\is_array($data)) {
throw new Exception('Data param should be a valid JSON object', 400);
}
@ -539,8 +543,8 @@ App::patch('/v1/database/collections/:collectionId/documents/:documentId')
$data['$collection'] = $collection->getId(); // Make sure user don't switch collectionID
$data['$id'] = $document->getId(); // Make sure user don't switch document unique ID
$data['$permissions']['read'] = $read;
$data['$permissions']['write'] = $write;
$data['$permissions']['read'] = (is_null($read)) ? ($document->getPermissions()['read'] ?? []) : $read; // By default inherit read permissions
$data['$permissions']['write'] = (is_null($write)) ? ($document->getPermissions()['write'] ?? []) : $write; // By default inherit write permissions
if (empty($data)) {
throw new Exception('Missing payload', 400);

View file

@ -38,17 +38,19 @@ App::post('/v1/storage/files')
->label('sdk.response.type', Response::CONTENT_TYPE_JSON)
->label('sdk.response.model', Response::MODEL_FILE)
->param('file', [], new File(), 'Binary file.', false)
->param('read', [], new ArrayList(new Text(64)), 'An array of strings with read permissions. By default no user is granted with any read permissions. [learn more about permissions](/docs/permissions) and get a full list of available permissions.')
->param('write', [], new ArrayList(new Text(64)), 'An array of strings with write permissions. By default no user is granted with any write permissions. [learn more about permissions](/docs/permissions) and get a full list of available permissions.')
->param('read', null, new ArrayList(new Text(64)), 'An array of strings with read permissions. By default only the current user is granted with read permissions. [learn more about permissions](/docs/permissions) and get a full list of available permissions.', true)
->param('write', null, new ArrayList(new Text(64)), 'An array of strings with write permissions. By default only the current user is granted with write permissions. [learn more about permissions](/docs/permissions) and get a full list of available permissions.', true)
->inject('request')
->inject('response')
->inject('projectDB')
->inject('user')
->inject('audits')
->inject('usage')
->action(function ($file, $read, $write, $request, $response, $projectDB, $audits, $usage) {
->action(function ($file, $read, $write, $request, $response, $projectDB, $user, $audits, $usage) {
/** @var Utopia\Swoole\Request $request */
/** @var Appwrite\Utopia\Response $response */
/** @var Appwrite\Database\Database $projectDB */
/** @var Appwrite\Database\Document $user */
/** @var Appwrite\Event\Event $audits */
/** @var Appwrite\Event\Event $usage */
@ -122,8 +124,8 @@ App::post('/v1/storage/files')
$file = $projectDB->createDocument([
'$collection' => Database::SYSTEM_COLLECTION_FILES,
'$permissions' => [
'read' => $read,
'write' => $write,
'read' => (is_null($read) && !$user->isEmpty()) ? ['user:'.$user->getId()] : $read ?? [], // By default set read permissions for user
'write' => (is_null($write) && !$user->isEmpty()) ? ['user:'.$user->getId()] : $write ?? [], // By default set write permissions for user
],
'dateCreated' => \time(),
'folderId' => '',

View file

@ -327,6 +327,7 @@ App::post('/v1/teams/:teamId/memberships')
'registration' => \time(),
'reset' => false,
'name' => $name,
'sessions' => [],
'tokens' => [],
], ['email' => $email]);
} catch (Duplicate $th) {
@ -595,10 +596,11 @@ App::patch('/v1/teams/:teamId/memberships/:inviteId/status')
$expiry = \time() + Auth::TOKEN_EXPIRATION_LOGIN_LONG;
$secret = Auth::tokenGenerator();
$session = new Document(array_merge([
'$collection' => Database::SYSTEM_COLLECTION_TOKENS,
'$collection' => Database::SYSTEM_COLLECTION_SESSIONS,
'$permissions' => ['read' => ['user:'.$user->getId()], 'write' => ['user:'.$user->getId()]],
'userId' => $user->getId(),
'type' => Auth::TOKEN_TYPE_LOGIN,
'provider' => Auth::SESSION_PROVIDER_EMAIL,
'providerUid' => $user->getAttribute('email'),
'secret' => Auth::hash($secret), // One way hash encryption to protect DB leak
'expire' => $expiry,
'userAgent' => $request->getUserAgent('UNKNOWN'),
@ -606,7 +608,7 @@ App::patch('/v1/teams/:teamId/memberships/:inviteId/status')
'countryCode' => ($record) ? \strtolower($record['country']['iso_code']) : '--',
], $detector->getOS(), $detector->getClient(), $detector->getDevice()));
$user->setAttribute('tokens', $session, Document::SET_TYPE_APPEND);
$user->setAttribute('sessions', $session, Document::SET_TYPE_APPEND);
Authorization::setRole('user:'.$userId);

View file

@ -196,21 +196,18 @@ App::get('/v1/users/:userId/sessions')
throw new Exception('User not found', 404);
}
$tokens = $user->getAttribute('tokens', []);
$sessions = [];
$sessions = $user->getAttribute('sessions', []);
$countries = $locale->getText('countries');
foreach ($tokens as $token) { /* @var $token Document */
if (Auth::TOKEN_TYPE_LOGIN != $token->getAttribute('type')) {
continue;
}
foreach ($sessions as $key => $session) {
/** @var Document $session */
$token->setAttribute('countryName', (isset($countries[strtoupper($token->getAttribute('countryCode'))]))
? $countries[strtoupper($token->getAttribute('countryCode'))]
$session->setAttribute('countryName', (isset($countries[strtoupper($session->getAttribute('countryCode'))]))
? $countries[strtoupper($session->getAttribute('countryCode'))]
: $locale->getText('locale.country.unknown'));
$token->setAttribute('current', false);
$session->setAttribute('current', false);
$sessions[] = $token;
$sessions[$key] = $session;
}
$response->dynamic(new Document([
@ -434,11 +431,13 @@ App::delete('/v1/users/:userId/sessions/:sessionId')
throw new Exception('User not found', 404);
}
$tokens = $user->getAttribute('tokens', []);
$sessions = $user->getAttribute('sessions', []);
foreach ($tokens as $token) { /* @var $token Document */
if ($sessionId == $token->getId()) {
if (!$projectDB->deleteDocument($token->getId())) {
foreach ($sessions as $session) {
/** @var Document $session */
if ($sessionId == $session->getId()) {
if (!$projectDB->deleteDocument($session->getId())) {
throw new Exception('Failed to remove token from DB', 500);
}
@ -478,10 +477,12 @@ App::delete('/v1/users/:userId/sessions')
throw new Exception('User not found', 404);
}
$tokens = $user->getAttribute('tokens', []);
$sessions = $user->getAttribute('sessions', []);
foreach ($tokens as $token) { /* @var $token Document */
if (!$projectDB->deleteDocument($token->getId())) {
foreach ($sessions as $session) {
/** @var Document $session */
if (!$projectDB->deleteDocument($session->getId())) {
throw new Exception('Failed to remove token from DB', 500);
}
}

View file

@ -256,6 +256,8 @@ App::error(function ($error, $utopia, $request, $response, $layout, $project) {
$template = ($route) ? $route->getLabel('error', null) : null;
if (php_sapi_name() === 'cli') {
Console::error('[Error] Timestamp: '.date('c', time()));
if($route) {
Console::error('[Error] Method: '.$route->getMethod());
Console::error('[Error] URL: '.$route->getURL());

View file

@ -40,7 +40,7 @@ const APP_MODE_DEFAULT = 'default';
const APP_MODE_ADMIN = 'admin';
const APP_PAGING_LIMIT = 12;
const APP_CACHE_BUSTER = 145;
const APP_VERSION_STABLE = '0.7.1';
const APP_VERSION_STABLE = '0.8.0';
const APP_STORAGE_UPLOADS = '/storage/uploads';
const APP_STORAGE_FUNCTIONS = '/storage/functions';
const APP_STORAGE_CACHE = '/storage/cache';
@ -419,7 +419,7 @@ App::setResource('user', function($mode, $project, $console, $request, $response
if (empty($user->getId()) // Check a document has been found in the DB
|| Database::SYSTEM_COLLECTION_USERS !== $user->getCollection() // Validate returned document is really a user document
|| !Auth::tokenVerify($user->getAttribute('tokens', []), Auth::TOKEN_TYPE_LOGIN, Auth::$secret)) { // Validate user has valid login token
|| !Auth::sessionVerify($user->getAttribute('sessions', []), Auth::$secret)) { // Validate user has valid login token
$user = new Document(['$id' => '', '$collection' => Database::SYSTEM_COLLECTION_USERS]);
}

View file

@ -352,7 +352,7 @@ services:
- appwrite-redis:/data:rw
clamav:
image: appwrite/clamav:1.3.0
image: appwrite/clamav:1.2.0
container_name: appwrite-clamav
restart: unless-stopped
networks:

View file

@ -124,7 +124,7 @@ class CertificatesV1
." -w ".APP_STORAGE_CERTIFICATES
." -d {$domain->get()}", '', $stdout, $stderr);
if($stderr || $exit !== 0) {
if($exit !== 0) {
throw new Exception('Failed to issue a certificate with message: '.$stderr);
}

View file

@ -112,13 +112,21 @@ class DeletesV1
protected function deleteUser(Document $document, $projectId)
{
$tokens = $document->getAttribute('tokens', []);
foreach ($tokens as $token) {
if (!$this->getProjectDB($projectId)->deleteDocument($token->getId())) {
throw new Exception('Failed to remove token from DB');
}
}
$sessions = $document->getAttribute('sessions', []);
foreach ($sessions as $session) {
if (!$this->getProjectDB($projectId)->deleteDocument($session->getId())) {
throw new Exception('Failed to remove session from DB');
}
}
// Delete Memberships
$this->deleteByGroup([
'$collection='.Database::SYSTEM_COLLECTION_MEMBERSHIPS,

View file

@ -1,6 +1,6 @@
#!/bin/sh
if [ -z "$_APP_REDIS_USER" ] || [ -z "$_APP_REDIS_PASS" ]
if [ -z "$_APP_REDIS_USER" ] && [ -z "$_APP_REDIS_PASS" ]
then
REDIS_BACKEND="${_APP_REDIS_HOST}:${_APP_REDIS_PORT}"
else

View file

@ -1,6 +1,6 @@
#!/bin/sh
if [ -z "$_APP_REDIS_USER" ] || [ -z "$_APP_REDIS_PASS" ]
if [ -z "$_APP_REDIS_USER" ] && [ -z "$_APP_REDIS_PASS" ]
then
REDIS_BACKEND="${_APP_REDIS_HOST}:${_APP_REDIS_PORT}"
else

View file

@ -1,6 +1,6 @@
#!/bin/sh
if [ -z "$_APP_REDIS_USER" ] || [ -z "$_APP_REDIS_PASS" ]
if [ -z "$_APP_REDIS_USER" ] && [ -z "$_APP_REDIS_PASS" ]
then
REDIS_BACKEND="${_APP_REDIS_HOST}:${_APP_REDIS_PORT}"
else

View file

@ -1,6 +1,6 @@
#!/bin/sh
if [ -z "$_APP_REDIS_USER" ] || [ -z "$_APP_REDIS_PASS" ]
if [ -z "$_APP_REDIS_USER" ] && [ -z "$_APP_REDIS_PASS" ]
then
REDIS_BACKEND="${_APP_REDIS_HOST}:${_APP_REDIS_PORT}"
else

View file

@ -1,6 +1,6 @@
#!/bin/sh
if [ -z "$_APP_REDIS_USER" ] || [ -z "$_APP_REDIS_PASS" ]
if [ -z "$_APP_REDIS_USER" ] && [ -z "$_APP_REDIS_PASS" ]
then
REDIS_BACKEND="${_APP_REDIS_HOST}:${_APP_REDIS_PORT}"
else

View file

@ -1,6 +1,6 @@
#!/bin/sh
if [ -z "$_APP_REDIS_USER" ] || [ -z "$_APP_REDIS_PASS" ]
if [ -z "$_APP_REDIS_USER" ] && [ -z "$_APP_REDIS_PASS" ]
then
REDIS_BACKEND="${_APP_REDIS_HOST}:${_APP_REDIS_PORT}"
else

View file

@ -1,6 +1,6 @@
#!/bin/sh
if [ -z "$_APP_REDIS_USER" ] || [ -z "$_APP_REDIS_PASS" ]
if [ -z "$_APP_REDIS_USER" ] && [ -z "$_APP_REDIS_PASS" ]
then
REDIS_BACKEND="${_APP_REDIS_HOST}:${_APP_REDIS_PORT}"
else

View file

@ -1,6 +1,6 @@
#!/bin/sh
if [ -z "$_APP_REDIS_USER" ] || [ -z "$_APP_REDIS_PASS" ]
if [ -z "$_APP_REDIS_USER" ] && [ -z "$_APP_REDIS_PASS" ]
then
REDIS_BACKEND="${_APP_REDIS_HOST}:${_APP_REDIS_PORT}"
else

View file

@ -1,6 +1,6 @@
#!/bin/sh
if [ -z "$_APP_REDIS_USER" ] || [ -z "$_APP_REDIS_PASS" ]
if [ -z "$_APP_REDIS_USER" ] && [ -z "$_APP_REDIS_PASS" ]
then
REDIS_BACKEND="${_APP_REDIS_HOST}:${_APP_REDIS_PORT}"
else

View file

@ -15,7 +15,10 @@
}
},
"autoload-dev": {
"psr-4": {"Tests\\E2E\\": "tests/e2e"}
"psr-4": {
"Tests\\E2E\\": "tests/e2e",
"Appwrite\\Tests\\": "tests/extensions"
}
},
"require": {
"php": ">=7.4.0",
@ -35,8 +38,8 @@
"appwrite/php-clamav": "1.0.*",
"utopia-php/framework": "0.12.*",
"utopia-php/abuse": "0.3.*",
"utopia-php/analytics": "0.1.*",
"utopia-php/abuse": "0.4.*",
"utopia-php/analytics": "0.2.*",
"utopia-php/audit": "0.5.*",
"utopia-php/cache": "0.2.*",
"utopia-php/cli": "0.10.0",
@ -60,7 +63,7 @@
"slickdeals/statsd": "~3.0"
},
"require-dev": {
"appwrite/sdk-generator": "0.6.3",
"appwrite/sdk-generator": "0.7.0",
"phpunit/phpunit": "9.4.2",
"swoole/ide-helper": "4.5.5",
"vimeo/psalm": "4.1.1"

202
composer.lock generated
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": "00a80774fb5a4984181b29f2f037a0e5",
"content-hash": "a5a066bf0b739b7b412149aeb0e9a396",
"packages": [
{
"name": "adhocore/jwt",
@ -364,18 +364,18 @@
"source": {
"type": "git",
"url": "https://github.com/guzzle/guzzle.git",
"reference": "01129f635f45659fd4764a533777d069a978bc9d"
"reference": "de6f1e58e735754b888649495ed4cb9ae3b19589"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/guzzle/guzzle/zipball/01129f635f45659fd4764a533777d069a978bc9d",
"reference": "01129f635f45659fd4764a533777d069a978bc9d",
"url": "https://api.github.com/repos/guzzle/guzzle/zipball/de6f1e58e735754b888649495ed4cb9ae3b19589",
"reference": "de6f1e58e735754b888649495ed4cb9ae3b19589",
"shasum": ""
},
"require": {
"ext-json": "*",
"guzzlehttp/promises": "^1.4",
"guzzlehttp/psr7": "^1.7",
"guzzlehttp/psr7": "^1.7 || ^2.0",
"php": "^7.2.5 || ^8.0",
"psr/http-client": "^1.0"
},
@ -383,6 +383,7 @@
"psr/http-client-implementation": "1.0"
},
"require-dev": {
"bamarni/composer-bin-plugin": "^1.4.1",
"ext-curl": "*",
"php-http/client-integration-tests": "^3.0",
"phpunit/phpunit": "^8.5.5 || ^9.3.5",
@ -397,7 +398,7 @@
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "7.3-dev"
"dev-master": "7.4-dev"
}
},
"autoload": {
@ -459,7 +460,7 @@
"type": "github"
}
],
"time": "2021-03-15T07:56:29+00:00"
"time": "2021-03-23T14:07:59+00:00"
},
{
"name": "guzzlehttp/promises",
@ -519,46 +520,47 @@
},
{
"name": "guzzlehttp/psr7",
"version": "1.x-dev",
"version": "dev-master",
"source": {
"type": "git",
"url": "https://github.com/guzzle/psr7.git",
"reference": "a67cdbf85690e54a7b92fe91c297b20d2607c0b2"
"reference": "c0dcda9f54d145bd4d062a6d15f54931a67732f9"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/guzzle/psr7/zipball/a67cdbf85690e54a7b92fe91c297b20d2607c0b2",
"reference": "a67cdbf85690e54a7b92fe91c297b20d2607c0b2",
"url": "https://api.github.com/repos/guzzle/psr7/zipball/c0dcda9f54d145bd4d062a6d15f54931a67732f9",
"reference": "c0dcda9f54d145bd4d062a6d15f54931a67732f9",
"shasum": ""
},
"require": {
"php": ">=5.4.0",
"psr/http-message": "~1.0",
"ralouphie/getallheaders": "^2.0.5 || ^3.0.0"
"php": "^7.2.5 || ^8.0",
"psr/http-factory": "^1.0",
"psr/http-message": "^1.0",
"ralouphie/getallheaders": "^3.0"
},
"provide": {
"psr/http-factory-implementation": "1.0",
"psr/http-message-implementation": "1.0"
},
"require-dev": {
"ext-zlib": "*",
"phpunit/phpunit": "~4.8.36 || ^5.7.27 || ^6.5.14 || ^7.5.20 || ^8.5.8 || ^9.3.10"
"bamarni/composer-bin-plugin": "^1.4.1",
"http-interop/http-factory-tests": "^0.9",
"phpunit/phpunit": "^8.5.8 || ^9.3.10"
},
"suggest": {
"laminas/laminas-httphandlerrunner": "Emit PSR-7 responses"
},
"default-branch": true,
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.7-dev"
"dev-master": "2.0-dev"
}
},
"autoload": {
"psr-4": {
"GuzzleHttp\\Psr7\\": "src/"
},
"files": [
"src/functions_include.php"
]
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
@ -573,6 +575,11 @@
{
"name": "Tobias Schultze",
"homepage": "https://github.com/Tobion"
},
{
"name": "Márk Sági-Kazár",
"email": "mark.sagikazar@gmail.com",
"homepage": "https://sagikazarmark.hu"
}
],
"description": "PSR-7 message implementation that also provides common utility methods",
@ -588,9 +595,9 @@
],
"support": {
"issues": "https://github.com/guzzle/psr7/issues",
"source": "https://github.com/guzzle/psr7/tree/1.x"
"source": "https://github.com/guzzle/psr7/tree/2.0.0-beta1"
},
"time": "2021-03-15T11:15:53+00:00"
"time": "2021-03-21T17:21:36+00:00"
},
{
"name": "influxdb/influxdb-php",
@ -906,6 +913,62 @@
},
"time": "2020-09-19T09:12:31+00:00"
},
{
"name": "psr/http-factory",
"version": "dev-master",
"source": {
"type": "git",
"url": "https://github.com/php-fig/http-factory.git",
"reference": "36fa03d50ff82abcae81860bdaf4ed9a1510c7cd"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/http-factory/zipball/36fa03d50ff82abcae81860bdaf4ed9a1510c7cd",
"reference": "36fa03d50ff82abcae81860bdaf4ed9a1510c7cd",
"shasum": ""
},
"require": {
"php": ">=7.0.0",
"psr/http-message": "^1.0"
},
"default-branch": true,
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"autoload": {
"psr-4": {
"Psr\\Http\\Message\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "https://www.php-fig.org/"
}
],
"description": "Common interfaces for PSR-7 HTTP message factories",
"keywords": [
"factory",
"http",
"message",
"psr",
"psr-17",
"psr-7",
"request",
"response"
],
"support": {
"source": "https://github.com/php-fig/http-factory/tree/master"
},
"time": "2020-09-17T16:52:55+00:00"
},
{
"name": "psr/http-message",
"version": "dev-master",
@ -1273,21 +1336,21 @@
},
{
"name": "utopia-php/abuse",
"version": "0.3.1",
"version": "0.4.0",
"source": {
"type": "git",
"url": "https://github.com/utopia-php/abuse.git",
"reference": "23c2eb533bca8f3ef5548ae265398fa7d4d39a1c"
"reference": "2b8cc40a67c045c137b44d1a11326f494acf50a4"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/utopia-php/abuse/zipball/23c2eb533bca8f3ef5548ae265398fa7d4d39a1c",
"reference": "23c2eb533bca8f3ef5548ae265398fa7d4d39a1c",
"url": "https://api.github.com/repos/utopia-php/abuse/zipball/2b8cc40a67c045c137b44d1a11326f494acf50a4",
"reference": "2b8cc40a67c045c137b44d1a11326f494acf50a4",
"shasum": ""
},
"require": {
"ext-pdo": "*",
"php": ">=7.1"
"php": ">=7.4"
},
"require-dev": {
"phpunit/phpunit": "^9.4",
@ -1319,22 +1382,22 @@
],
"support": {
"issues": "https://github.com/utopia-php/abuse/issues",
"source": "https://github.com/utopia-php/abuse/tree/0.3.1"
"source": "https://github.com/utopia-php/abuse/tree/0.4.0"
},
"time": "2020-12-21T17:28:03+00:00"
"time": "2021-03-17T20:21:24+00:00"
},
{
"name": "utopia-php/analytics",
"version": "0.1.0",
"version": "0.2.0",
"source": {
"type": "git",
"url": "https://github.com/utopia-php/analytics.git",
"reference": "a1f2a1672a927bef8cd4d9b47e5cfbc856a3c72f"
"reference": "adfc2d057a7f6ab618a77c8a20ed3e35485ff416"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/utopia-php/analytics/zipball/a1f2a1672a927bef8cd4d9b47e5cfbc856a3c72f",
"reference": "a1f2a1672a927bef8cd4d9b47e5cfbc856a3c72f",
"url": "https://api.github.com/repos/utopia-php/analytics/zipball/adfc2d057a7f6ab618a77c8a20ed3e35485ff416",
"reference": "adfc2d057a7f6ab618a77c8a20ed3e35485ff416",
"shasum": ""
},
"require": {
@ -1374,9 +1437,9 @@
],
"support": {
"issues": "https://github.com/utopia-php/analytics/issues",
"source": "https://github.com/utopia-php/analytics/tree/0.1.0"
"source": "https://github.com/utopia-php/analytics/tree/0.2.0"
},
"time": "2021-02-03T17:07:09+00:00"
"time": "2021-03-23T21:33:07+00:00"
},
{
"name": "utopia-php/audit",
@ -1643,16 +1706,16 @@
},
{
"name": "utopia-php/framework",
"version": "0.12.1",
"version": "0.12.3",
"source": {
"type": "git",
"url": "https://github.com/utopia-php/framework.git",
"reference": "ba17789a16527d24b4fb11ddc359901a295fbf2f"
"reference": "78be43a0eb711f3677769dfb445e5111bfafaa88"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/utopia-php/framework/zipball/ba17789a16527d24b4fb11ddc359901a295fbf2f",
"reference": "ba17789a16527d24b4fb11ddc359901a295fbf2f",
"url": "https://api.github.com/repos/utopia-php/framework/zipball/78be43a0eb711f3677769dfb445e5111bfafaa88",
"reference": "78be43a0eb711f3677769dfb445e5111bfafaa88",
"shasum": ""
},
"require": {
@ -1686,9 +1749,9 @@
],
"support": {
"issues": "https://github.com/utopia-php/framework/issues",
"source": "https://github.com/utopia-php/framework/tree/0.12.1"
"source": "https://github.com/utopia-php/framework/tree/0.12.3"
},
"time": "2021-03-17T22:14:05+00:00"
"time": "2021-03-22T22:02:23+00:00"
},
{
"name": "utopia-php/image",
@ -1953,16 +2016,16 @@
},
{
"name": "utopia-php/swoole",
"version": "0.2.2",
"version": "0.2.3",
"source": {
"type": "git",
"url": "https://github.com/utopia-php/swoole.git",
"reference": "17510e90499e73273245c534a05bca522d4ffb37"
"reference": "45c42aae7e7d3f9f82bf194c2cfa5499b674aefe"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/utopia-php/swoole/zipball/17510e90499e73273245c534a05bca522d4ffb37",
"reference": "17510e90499e73273245c534a05bca522d4ffb37",
"url": "https://api.github.com/repos/utopia-php/swoole/zipball/45c42aae7e7d3f9f82bf194c2cfa5499b674aefe",
"reference": "45c42aae7e7d3f9f82bf194c2cfa5499b674aefe",
"shasum": ""
},
"require": {
@ -2003,9 +2066,9 @@
],
"support": {
"issues": "https://github.com/utopia-php/swoole/issues",
"source": "https://github.com/utopia-php/swoole/tree/0.2.2"
"source": "https://github.com/utopia-php/swoole/tree/0.2.3"
},
"time": "2021-03-17T22:51:07+00:00"
"time": "2021-03-22T22:39:24+00:00"
},
{
"name": "utopia-php/system",
@ -2287,11 +2350,11 @@
},
{
"name": "appwrite/sdk-generator",
"version": "0.6.3",
"version": "0.7.0",
"source": {
"type": "git",
"url": "https://github.com/appwrite/sdk-generator",
"reference": "583248c57c5bcbd9c74f8312cc7fc3ab6cda51a3"
"reference": "12a6a4b723137d5449c84ee2915b1ab3586e2162"
},
"require": {
"ext-curl": "*",
@ -2304,7 +2367,6 @@
"require-dev": {
"phpunit/phpunit": "^7.0"
},
"default-branch": true,
"type": "library",
"autoload": {
"psr-4": {
@ -2322,7 +2384,7 @@
}
],
"description": "Appwrite PHP library for generating API SDKs for multiple programming languages and platforms",
"time": "2021-03-07T08:45:05+00:00"
"time": "2021-03-23T09:26:18+00:00"
},
{
"name": "composer/package-versions-deprecated",
@ -4934,12 +4996,12 @@
"source": {
"type": "git",
"url": "https://github.com/symfony/console.git",
"reference": "36e4ff2188cb5af6e6e94560b4aaa8042933aa58"
"reference": "5da8b675121f9f4419b7052caa0cc6118a3ccd47"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/console/zipball/36e4ff2188cb5af6e6e94560b4aaa8042933aa58",
"reference": "36e4ff2188cb5af6e6e94560b4aaa8042933aa58",
"url": "https://api.github.com/repos/symfony/console/zipball/5da8b675121f9f4419b7052caa0cc6118a3ccd47",
"reference": "5da8b675121f9f4419b7052caa0cc6118a3ccd47",
"shasum": ""
},
"require": {
@ -5025,7 +5087,7 @@
"type": "tidelift"
}
],
"time": "2021-03-17T16:56:09+00:00"
"time": "2021-03-23T14:20:07+00:00"
},
{
"name": "symfony/deprecation-contracts",
@ -5033,12 +5095,12 @@
"source": {
"type": "git",
"url": "https://github.com/symfony/deprecation-contracts.git",
"reference": "49dc45a74cbac5fffc6417372a9f5ae1682ca0b4"
"reference": "5f38c8804a9e97d23e0c8d63341088cd8a22d627"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/49dc45a74cbac5fffc6417372a9f5ae1682ca0b4",
"reference": "49dc45a74cbac5fffc6417372a9f5ae1682ca0b4",
"url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/5f38c8804a9e97d23e0c8d63341088cd8a22d627",
"reference": "5f38c8804a9e97d23e0c8d63341088cd8a22d627",
"shasum": ""
},
"require": {
@ -5093,7 +5155,7 @@
"type": "tidelift"
}
],
"time": "2021-02-25T16:38:04+00:00"
"time": "2021-03-23T23:28:01+00:00"
},
{
"name": "symfony/polyfill-intl-grapheme",
@ -5513,12 +5575,12 @@
"source": {
"type": "git",
"url": "https://github.com/symfony/service-contracts.git",
"reference": "3d72b4bfab3e991aa66906aa301aa479de4ca6ee"
"reference": "1309413986521646bb0ba91140afdc2a61ed8cfe"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/service-contracts/zipball/3d72b4bfab3e991aa66906aa301aa479de4ca6ee",
"reference": "3d72b4bfab3e991aa66906aa301aa479de4ca6ee",
"url": "https://api.github.com/repos/symfony/service-contracts/zipball/1309413986521646bb0ba91140afdc2a61ed8cfe",
"reference": "1309413986521646bb0ba91140afdc2a61ed8cfe",
"shasum": ""
},
"require": {
@ -5585,7 +5647,7 @@
"type": "tidelift"
}
],
"time": "2021-03-16T09:10:58+00:00"
"time": "2021-03-23T23:28:01+00:00"
},
{
"name": "symfony/string",
@ -5727,12 +5789,12 @@
"source": {
"type": "git",
"url": "https://github.com/twigphp/Twig.git",
"reference": "37e48403c21e06f63bc27d7ccd997fbb72b0ae2a"
"reference": "116bfb0bc9ec2a39db93431b7fe67144164d251e"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/twigphp/Twig/zipball/37e48403c21e06f63bc27d7ccd997fbb72b0ae2a",
"reference": "37e48403c21e06f63bc27d7ccd997fbb72b0ae2a",
"url": "https://api.github.com/repos/twigphp/Twig/zipball/116bfb0bc9ec2a39db93431b7fe67144164d251e",
"reference": "116bfb0bc9ec2a39db93431b7fe67144164d251e",
"shasum": ""
},
"require": {
@ -5798,7 +5860,7 @@
"type": "tidelift"
}
],
"time": "2021-03-10T10:07:14+00:00"
"time": "2021-03-22T08:23:49+00:00"
},
{
"name": "vimeo/psalm",
@ -5959,9 +6021,7 @@
],
"aliases": [],
"minimum-stability": "dev",
"stability-flags": {
"appwrite/sdk-generator": 20
},
"stability-flags": [],
"prefer-stable": false,
"prefer-lowest": false,
"platform": {

View file

@ -414,7 +414,7 @@ services:
- appwrite-redis:/data:rw
clamav:
image: appwrite/clamav:1.3.0
image: appwrite/clamav:1.2.0
container_name: appwrite-clamav
networks:
- appwrite

View file

@ -0,0 +1 @@
Use this endpoint to allow a new user to register an anonymous account in your project. This route will also create a new session for the user. To allow the new user to convert an anonymous account to a normal account account, you need to update its [email and password](/docs/client/account#accountUpdateEmail).

View file

@ -1 +1,2 @@
Update currently logged in user account email address. After changing user address, user confirmation status is being reset and a new confirmation mail is sent. For security measures, user password is required to complete this request.
Update currently logged in user account email address. After changing user address, user confirmation status is being reset and a new confirmation mail is sent. For security measures, user password is required to complete this request.
This endpoint can also be used to convert an anonymous account to a normal one, by passing an email address and a new password.

View file

@ -23,6 +23,21 @@ void main() async {
}
```
### Error handling
The Appwrite Dart SDK raises `AppwriteException` object with `message`, `code` and `response` properties. You can handle any errors by catching `AppwriteException` and present the `message` to the user or handle it yourself based on the provided error information. Below is an example.
```dart
Users users = Users(client);
try {
final response = await users.create(email: email@example.com,password: password, name: name);
print(response.data);
} on AppwriteException catch(e) {
//show message to user or do other operation based on error as required
print(e.message);
}
```
### Learn more
You can use followng resources to learn more and get help
- 🚀 [Getting Started Tutorial](https://appwrite.io/docs/getting-started-for-server)

View file

@ -52,6 +52,19 @@ promise.then(function (response) {
});
```
### Error Handling
The Appwrite Deno SDK raises `AppwriteException` object with `message`, `code` and `response` properties. You can handle any errors by catching `AppwriteException` and present the `message` to the user or handle it yourself based on the provided error information. Below is an example.
```typescript
let users = new sdk.Users(client);
try {
let res = await users.create('email@example.com', 'password');
} catch(e) {
console.log(e.message);
}
```
### Learn more
You can use followng resources to learn more and get help
- 🚀 [Getting Started Tutorial](https://appwrite.io/docs/getting-started-for-server)

View file

@ -0,0 +1 @@
# Change Log

View file

@ -0,0 +1,51 @@
## Getting Started
### Initialize & Make API Request
Once you add the dependencies, its extremely easy to get started with the SDK; All you need to do is import the package in your code, set your Appwrite credentials, and start making API calls. Below is a simple example:
```csharp
using Appwrite;
static async Task Main(string[] args)
{
var client = Client();
client
.setEndpoint('http://[HOSTNAME_OR_IP]/v1') // Make sure your endpoint is accessible
.setProject('5ff3379a01d25') // Your project ID
.setKey('cd868c7af8bdc893b4...93b7535db89')
;
var users = Users(client);
try {
var request = await users.create('email@example.com', 'password', 'name');
var response = await request.Content.ReadAsStringAsync();
Console.WriteLine(response);
} catch (AppwriteException e) {
Console.WriteLine(e.Message);
}
}
```
### Error Handling
The Appwrite .NET SDK raises `AppwriteException` object with `message`, `code` and `response` properties. You can handle any errors by catching `AppwriteException` and present the `message` to the user or handle it yourself based on the provided error information. Below is an example.
```csharp
var users = Users(client);
try {
var request = await users.create('email@example.com', 'password', 'name');
var response = await request.Content.ReadAsStringAsync();
Console.WriteLine(response);
} catch (AppwriteException e) {
Console.WriteLine(e.Message);
}
```
### Learn more
You can use followng resources to learn more and get help
- 🚀 [Getting Started Tutorial](https://appwrite.io/docs/getting-started-for-server)
- 📜 [Appwrite Docs](https://appwrite.io/docs)
- 💬 [Discord Community](https://appwrite.io/discord)
- 🚂 [Appwrite Dart Playground](https://github.com/appwrite/playground-for-dotnet)

View file

@ -1,3 +1,11 @@
## 0.4.0
- Improved code quality
- Enabled access to private storage files
- Easier integration for preview images with the image widget
- Added custom Appwrite exceptions
- Breaking: getFilePreview, getFileDownload and getFileView now return Future instead of String
## 0.4.0-dev.3
- Added code formatting as part of the CI

View file

@ -106,6 +106,21 @@ Response user = await account
);
```
### Error Handling
The Appwrite Flutter SDK raises `AppwriteException` object with `message`, `code` and `response` properties. You can handle any errors by catching `AppwriteException` and present the `message` to the user or handle it yourself based on the provided error information. Below is an example.
```dart
Users users = Users(client);
try {
final response = await users.create(email: email@example.com,password: password, name: name);
print(response.data);
} on AppwriteException catch(e) {
//show message to user or do other operation based on error as required
print(e.message);
}
```
### Learn more
You can use followng resources to learn more and get help
- 🚀 [Getting Started Tutorial](https://appwrite.io/docs/getting-started-for-flutter)

View file

@ -52,6 +52,19 @@ promise.then(function (response) {
});
```
### Error Handling
The Appwrite Node SDK raises `AppwriteException` object with `message`, `code` and `response` properties. You can handle any errors by catching `AppwriteException` and present the `message` to the user or handle it yourself based on the provided error information. Below is an example.
```js
let users = new sdk.Users(client);
try {
let res = await users.create('email@example.com', 'password');
} catch(e) {
console.log(e.message);
}
```
### Learn more
You can use followng resources to learn more and get help
- 🚀 [Getting Started Tutorial](https://appwrite.io/docs/getting-started-for-server)

View file

@ -40,6 +40,19 @@ $users = new Users($client);
$result = $users->create('email@example.com', 'password');
```
### Error Handling
The Appwrite PHP SDK raises `AppwriteException` object with `message`, `code` and `response` properties. You can handle any errors by catching `AppwriteException` and present the `message` to the user or handle it yourself based on the provided error information. Below is an example.
```php
$users = new Users($client);
try {
$result = $users->create('email@example.com', 'password');
} catch(AppwriteException $error) {
echo $error->message;
}
```
### Learn more
You can use followng resources to learn more and get help
- 🚀 [Getting Started Tutorial](https://appwrite.io/docs/getting-started-for-server)

View file

@ -43,6 +43,17 @@ users = Users(client)
result = users.create('email@example.com', 'password')
```
### Error Handling
The Appwrite Python SDK raises `AppwriteException` object with `message`, `code` and `response` properties. You can handle any errors by catching `AppwriteException` and present the `message` to the user or handle it yourself based on the provided error information. Below is an example.
```python
users = Users(client)
try:
result = users.create('email@example.com', 'password')
except AppwriteException as e:
print(e.message)
```
### Learn more
You can use followng resources to learn more and get help
- 🚀 [Getting Started Tutorial](https://appwrite.io/docs/getting-started-for-server)

View file

@ -0,0 +1,62 @@
## Getting Started
### Init your SDK
Initialize your SDK code with your project ID which can be found in your project settings page and your new API secret Key from project's API keys section.
```ruby
require 'appwrite'
client = Appwrite::Client.new()
client
.set_endpoint(ENV["APPWRITE_ENDPOINT"]) # Your API Endpoint
.set_project(ENV["APPWRITE_PROJECT"]) # Your project ID
.set_key(ENV["APPWRITE_SECRET"]) # Your secret API key
;
```
### Make Your First Request
Once your SDK object is set, create any of the Appwrite service objects and choose any request to send. Full documentation for any service method you would like to use can be found in your SDK documentation or in the API References section.
```ruby
users = Appwrite::Users.new(client);
result = users.create(email: 'email@example.com', password: 'password');
```
### Full Example
```ruby
require 'appwrite'
client = Appwrite::Client.new()
client
.set_endpoint(ENV["APPWRITE_ENDPOINT"]) # Your API Endpoint
.set_project(ENV["APPWRITE_PROJECT"]) # Your project ID
.set_key(ENV["APPWRITE_SECRET"]) # Your secret API key
;
users = Appwrite::Users.new(client);
result = users.create(email: 'email@example.com', password: 'password');
```
### Error Handling
The Appwrite Ruby SDK raises `Appwrite::Exception` object with `message`, `code` and `response` properties. You can handle any errors by catching `Appwrite::Exception` and present the `message` to the user or handle it yourself based on the provided error information. Below is an example.
```ruby
users = Appwrite::Users.new(client);
begin
result = users.create(email: 'email@example.com', password: 'password');
rescue Appwrite::Exception => error
puts error.message
end
```
### Learn more
You can use followng resources to learn more and get help
- 🚀 [Getting Started Tutorial](https://appwrite.io/docs/getting-started-for-server)
- 📜 [Appwrite Docs](https://appwrite.io/docs)
- 💬 [Discord Community](https://appwrite.io/discord)
- 🚂 [Appwrite Ruby Playground](https://github.com/appwrite/playground-for-ruby)

View file

@ -0,0 +1,61 @@
## Getting Started
### Add your Web Platform
For you to init your SDK and interact with Appwrite services you need to add a web platform to your project. To add a new platform, go to your Appwrite console, choose the project you created in the step before and click the 'Add Platform' button.
From the options, choose to add a **Web** platform and add your client app hostname. By adding your hostname to your project platform you are allowing cross-domain communication between your project and the Appwrite API.
### Init your SDK
Initialize your SDK code with your project ID which can be found in your project settings page.
```js
// Init your Web SDK
const appwrite = new Appwrite();
appwrite
.setEndpoint('http://localhost/v1') // Your Appwrite Endpoint
.setProject('455x34dfkj') // Your project ID
;
```
### Make Your First Request
Once your SDK object is set, access any of the Appwrite services and choose any request to send. Full documentation for any service method you would like to use can be found in your SDK documentation or in the API References section.
```js
// Register User
appwrite
.account.create('me@example.com', 'password', 'Jane Doe')
.then(function (response) {
console.log(response);
}, function (error) {
console.log(error);
});
```
### Full Example
```js
// Init your Web SDK
const appwrite = new Appwrite();
appwrite
.setEndpoint('http://localhost/v1') // Your Appwrite Endpoint
.setProject('455x34dfkj')
;
// Register User
appwrite
.account.create('me@example.com', 'password', 'Jane Doe')
.then(function (response) {
console.log(response);
}, function (error) {
console.log(error);
});
```
### Learn more
You can use followng resources to learn more and get help
- 🚀 [Getting Started Tutorial](https://appwrite.io/docs/getting-started-for-flutter)
- 📜 [Appwrite Docs](https://appwrite.io/docs)
- 💬 [Discord Community](https://appwrite.io/discord)
- 🚂 [Appwrite Flutter Playground](https://github.com/appwrite/playground-for-flutter)

View file

@ -10,7 +10,7 @@ Adding new features may require various configurations options to be set by the
This tutorial will cover, how to properly add a new environment variable in Appwrite.
### Naming environment varialbe
The environment variables in Appwrite are prefixed with `_APP_`. If it belongs to a specific cateogry, the category name is appended as `_APP_REDIS` for the redis category. The available categories are General, Redis, MariaDB, InfluxDB, StatsD, SMTP, Storage and Functions. Finally a properly describing name is given to the variable. For example `_APP_REDIS_HOST` is an environment variable for redis connection host. You can find more information on available categories and existing environment variables in the [environment variables doc](https://appwrite.io/docs/environment-variables).
The environment variables in Appwrite are prefixed with `_APP_`. If it belongs to a specific category, the category name is appended as `_APP_REDIS` for the redis category. The available categories are General, Redis, MariaDB, InfluxDB, StatsD, SMTP, Storage and Functions. Finally a properly describing name is given to the variable. For example `_APP_REDIS_HOST` is an environment variable for redis connection host. You can find more information on available categories and existing environment variables in the [environment variables doc](https://appwrite.io/docs/environment-variables).
### Describe new environment variable
First of all, we add the new environment variable to `app/config/variables.php` in the designated category. If none of the categories fit, add it to the General category. Copy the existing variables description to create a new one, so that you will not miss any required fields.

View file

@ -37,7 +37,7 @@ In this phase we will add support to the new storage adapter in Appwrite.
* Note for this to happen, your PR in the first phase should have been merged and new version of [utopia-php/storage](https://github.com/utopia-php/storage) library released.
### Upgrade the utopia-php/storage dependency
Upgrade the utopia-php/sotrage dependency in `composer.json` file.
Upgrade the utopia-php/storage dependency in `composer.json` file.
### Introduce new environment variables
If required for the new adapter, may be for credentials, introduce new environment variables. The storage envorinment variables are prefixed as `_APP_STORAGE_DEVICE`. Please read [Adding Environment Variables]() guidelines in order to properly introduce new environment variables.

View file

@ -8,6 +8,9 @@
processIsolation="false"
stopOnFailure="false"
>
<extensions>
<extension class="Appwrite\Tests\TestHook" />
</extensions>
<testsuites>
<testsuite name="Application Test Suite">
<file>./tests/e2e/Client.php</file>

View file

@ -28,11 +28,17 @@ class Auth
/**
* Token Types.
*/
const TOKEN_TYPE_LOGIN = 1;
const TOKEN_TYPE_LOGIN = 1; // Deprecated
const TOKEN_TYPE_VERIFICATION = 2;
const TOKEN_TYPE_RECOVERY = 3;
const TOKEN_TYPE_INVITE = 4;
/**
* Session Providers.
*/
const SESSION_PROVIDER_EMAIL = 'email';
const SESSION_PROVIDER_ANONYMOUS = 'anonymous';
/**
* Token Expiration times.
*/
@ -207,6 +213,29 @@ class Auth
return false;
}
/**
* Verify session and check that its not expired.
*
* @param array $sessions
* @param string $secret
*
* @return bool|string
*/
public static function sessionVerify(array $sessions, string $secret)
{
foreach ($sessions as $session) { /** @var Document $session */
if ($session->isSet('secret') &&
$session->isSet('expire') &&
$session->isSet('provider') &&
$session->getAttribute('secret') === self::hash($secret) &&
$session->getAttribute('expire') >= \time()) {
return (string)$session->getId();
}
}
return false;
}
/**
* Is Previligged User?
*

View file

@ -27,6 +27,7 @@ class Database
// Auth, Account and Users (private to user)
const SYSTEM_COLLECTION_USERS = 'users';
const SYSTEM_COLLECTION_SESSIONS = 'sessions';
const SYSTEM_COLLECTION_TOKENS = 'tokens';
// Teams (shared among team members)

View file

@ -0,0 +1,70 @@
<?php
namespace Appwrite\Migration\Version;
use Appwrite\Migration\Migration;
use Utopia\Config\Config;
use Utopia\CLI\Console;
use Appwrite\Auth\Auth;
use Appwrite\Database\Database;
use Appwrite\Database\Document;
class V07 extends Migration
{
public function execute(): void
{
$db = $this->db;
$project = $this->project;
Console::log('Migrating project: ' . $project->getAttribute('name') . ' (' . $project->getId() . ')');
$this->forEachDocument([$this, 'fixDocument']);
}
protected function fixDocument(Document $document)
{
$providers = Config::getParam('providers');
switch ($document->getAttribute('$collection')) {
case Database::SYSTEM_COLLECTION_USERS:
foreach ($providers as $key => $provider) {
/**
* Remove deprecated OAuth2 properties in the Users Documents.
*/
if (!empty($document->getAttribute('oauth2' . \ucfirst($key)))) {
$document->removeAttribute('oauth2' . \ucfirst($key));
}
if (!empty($document->getAttribute('oauth2' . \ucfirst($key) . 'AccessToken'))) {
$document->removeAttribute('oauth2' . \ucfirst($key) . 'AccessToken');
}
/**
* Invalidate all Login Tokens, since they can't be migrated to the new structure.
* Reason for it is the missing distinction between E-Mail and OAuth2 tokens.
*/
$tokens = array_filter($document->getAttribute('tokens', []), function($token) {
return ($token->getAttribute('type') != Auth::TOKEN_TYPE_LOGIN);
});
$document->setAttribute('tokens', array_values($tokens));
}
break;
}
foreach ($document as &$attr) { // Handle child documents
if ($attr instanceof Document) {
$attr = $this->fixDocument($attr);
}
if (\is_array($attr)) {
foreach ($attr as &$child) {
if ($child instanceof Document) {
$child = $this->fixDocument($child);
}
}
}
}
return $document;
}
}

View file

@ -28,6 +28,24 @@ class Session extends Model
'default' => 0,
'example' => 1592981250,
])
->addRule('provider', [
'type' => self::TYPE_STRING,
'description' => 'Session Provider.',
'default' => '',
'example' => 'email',
])
->addRule('providerUid', [
'type' => self::TYPE_STRING,
'description' => 'Session Provider User ID.',
'default' => '',
'example' => 'user@example.com',
])
->addRule('providerToken', [
'type' => self::TYPE_STRING,
'description' => 'Session Provider Token.',
'default' => '',
'example' => 'MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3',
])
->addRule('ip', [
'type' => self::TYPE_STRING,
'description' => 'IP in use when the session was created.',

View file

@ -49,6 +49,39 @@ trait AccountBase
$this->assertEquals($response['headers']['status-code'], 409);
$response = $this->client->call(Client::METHOD_POST, '/account', array_merge([
'origin' => 'http://localhost',
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
]), [
'email' => '',
'password' => '',
]);
$this->assertEquals($response['headers']['status-code'], 400);
$response = $this->client->call(Client::METHOD_POST, '/account', array_merge([
'origin' => 'http://localhost',
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
]), [
'email' => $email,
'password' => '',
]);
$this->assertEquals($response['headers']['status-code'], 400);
$response = $this->client->call(Client::METHOD_POST, '/account', array_merge([
'origin' => 'http://localhost',
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
]), [
'email' => '',
'password' => $password,
]);
$this->assertEquals($response['headers']['status-code'], 400);
return [
'id' => $id,
'email' => $email,
@ -372,7 +405,6 @@ trait AccountBase
$this->assertEquals($response['headers']['status-code'], 200);
$this->assertIsArray($response['body']);
$this->assertNotEmpty($response['body']);
$this->assertNotEmpty($response['body']);
$this->assertNotEmpty($response['body']['$id']);
$this->assertIsNumeric($response['body']['registration']);
$this->assertEquals($response['body']['email'], $email);
@ -440,7 +472,6 @@ trait AccountBase
$this->assertEquals($response['headers']['status-code'], 200);
$this->assertIsArray($response['body']);
$this->assertNotEmpty($response['body']);
$this->assertNotEmpty($response['body']);
$this->assertNotEmpty($response['body']['$id']);
$this->assertIsNumeric($response['body']['registration']);
$this->assertEquals($response['body']['email'], $email);
@ -507,7 +538,6 @@ trait AccountBase
$this->assertEquals($response['headers']['status-code'], 200);
$this->assertIsArray($response['body']);
$this->assertNotEmpty($response['body']);
$this->assertNotEmpty($response['body']);
$this->assertNotEmpty($response['body']['$id']);
$this->assertIsNumeric($response['body']['registration']);
$this->assertEquals($response['body']['email'], $newEmail);
@ -565,7 +595,6 @@ trait AccountBase
$this->assertEquals($response['headers']['status-code'], 200);
$this->assertIsArray($response['body']);
$this->assertNotEmpty($response['body']);
$this->assertNotEmpty($response['body']);
$this->assertEquals('prefValue1', $response['body']['prefs']['prefKey1']);
$this->assertEquals('prefValue2', $response['body']['prefs']['prefKey2']);

View file

@ -6,6 +6,7 @@ use Tests\E2E\Client;
use Tests\E2E\Scopes\Scope;
use Tests\E2E\Scopes\ProjectCustom;
use Tests\E2E\Scopes\SideClient;
use Utopia\App;
class AccountCustomClientTest extends Scope
{
@ -226,4 +227,198 @@ class AccountCustomClientTest extends Scope
return [];
}
public function testCreateAnonymousAccount()
{
/**
* Test for SUCCESS
*/
$response = $this->client->call(Client::METHOD_POST, '/account/sessions/anonymous', [
'origin' => 'http://localhost',
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
]);
$this->assertEquals(201, $response['headers']['status-code']);
$session = $this->client->parseCookie((string)$response['headers']['set-cookie'])['a_session_'.$this->getProject()['$id']];
/**
* Test for FAILURE
*/
$response = $this->client->call(Client::METHOD_POST, '/account/sessions/anonymous', [
'origin' => 'http://localhost',
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
'cookie' => 'a_session_'.$this->getProject()['$id'].'=' . $session,
]);
$this->assertEquals(401, $response['headers']['status-code']);
return $session;
}
/**
* @depends testCreateAnonymousAccount
*/
public function testUpdateAnonymousAccountPassword($session):array
{
/**
* Test for FAILURE
*/
$response = $this->client->call(Client::METHOD_PATCH, '/account/password', array_merge([
'origin' => 'http://localhost',
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
'cookie' => 'a_session_'.$this->getProject()['$id'].'=' . $session,
]), [
'password' => 'new-password',
'oldPassword' => '',
]);
$this->assertEquals($response['headers']['status-code'], 400);
return [];
}
/**
* @depends testUpdateAnonymousAccountPassword
*/
public function testUpdateAnonymousAccountEmail($session):array
{
$email = uniqid().'new@localhost.test';
/**
* Test for FAILURE
*/
$response = $this->client->call(Client::METHOD_PATCH, '/account/email', array_merge([
'origin' => 'http://localhost',
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
'cookie' => 'a_session_'.$this->getProject()['$id'].'=' . $session,
]), [
'email' => $email,
'password' => '',
]);
$this->assertEquals($response['headers']['status-code'], 401);
return [];
}
public function testConvertAnonymousAccount():array
{
$session = $this->testCreateAnonymousAccount();
$email = uniqid().'new@localhost.test';
$password = 'new-password';
/**
* Test for FAILURE
*/
$response = $this->client->call(Client::METHOD_POST, '/account', array_merge([
'origin' => 'http://localhost',
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
]), [
'email' => $email,
'password' => $password
]);
$response = $this->client->call(Client::METHOD_PATCH, '/account/email', array_merge([
'origin' => 'http://localhost',
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
'cookie' => 'a_session_'.$this->getProject()['$id'].'=' . $session,
]), [
'email' => $email,
'password' => $password,
]);
$this->assertEquals($response['headers']['status-code'], 400);
/**
* Test for SUCCESS
*/
$email = uniqid().'new@localhost.test';
$response = $this->client->call(Client::METHOD_PATCH, '/account/email', array_merge([
'origin' => 'http://localhost',
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
'cookie' => 'a_session_'.$this->getProject()['$id'].'=' . $session,
]), [
'email' => $email,
'password' => $password,
]);
$this->assertEquals($response['headers']['status-code'], 200);
$this->assertIsArray($response['body']);
$this->assertNotEmpty($response['body']);
$this->assertNotEmpty($response['body']['$id']);
$this->assertIsNumeric($response['body']['registration']);
$this->assertEquals($response['body']['email'], $email);
$response = $this->client->call(Client::METHOD_POST, '/account/sessions', array_merge([
'origin' => 'http://localhost',
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
]), [
'email' => $email,
'password' => $password,
]);
$this->assertEquals($response['headers']['status-code'], 201);
return [];
}
public function testConvertAnonymousAccountOAuth2():array
{
$session = $this->testCreateAnonymousAccount();
$provider = 'mock';
$appId = '1';
$secret = '123456';
/**
* Test for SUCCESS
*/
$response = $this->client->call(Client::METHOD_PATCH, '/projects/'.$this->getProject()['$id'].'/oauth2', array_merge([
'origin' => 'http://localhost',
'content-type' => 'application/json',
'x-appwrite-project' => 'console',
'cookie' => 'a_session_console=' . $this->getRoot()['session'],
]), [
'provider' => $provider,
'appId' => $appId,
'secret' => $secret,
]);
$this->assertEquals($response['headers']['status-code'], 200);
$response = $this->client->call(Client::METHOD_GET, '/account/sessions/oauth2/'.$provider, array_merge([
'origin' => 'http://localhost',
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
'cookie' => 'a_session_'.$this->getProject()['$id'].'=' . $session,
]), [
'success' => 'http://localhost/v1/mock/tests/general/oauth2/success',
'failure' => 'http://localhost/v1/mock/tests/general/oauth2/failure',
]);
$this->assertEquals(200, $response['headers']['status-code']);
$this->assertEquals('success', $response['body']['result']);
$response = $this->client->call(Client::METHOD_GET, '/account', array_merge([
'origin' => 'http://localhost',
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
'cookie' => 'a_session_'.$this->getProject()['$id'].'=' . $session,
]));
$this->assertEquals($response['headers']['status-code'], 200);
$this->assertEquals($response['body']['name'], 'User Name');
$this->assertEquals($response['body']['email'], 'user@localhost.test');
return [];
}
}

View file

@ -501,6 +501,133 @@ trait DatabaseBase
$this->assertEquals($document['headers']['status-code'], 404);
return [];
return $data;
}
/**
* @depends testDeleteDocument
*/
public function testDefaultPermissions(array $data):array
{
$document = $this->client->call(Client::METHOD_POST, '/database/collections/' . $data['moviesId'] . '/documents', array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getHeaders()), [
'data' => [
'name' => 'Captain America',
'releaseYear' => 1944,
'actors' => [],
],
]);
$id = $document['body']['$id'];
$this->assertEquals($document['headers']['status-code'], 201);
$this->assertEquals($document['body']['$collection'], $data['moviesId']);
$this->assertEquals($document['body']['name'], 'Captain America');
$this->assertEquals($document['body']['releaseYear'], 1944);
$this->assertIsArray($document['body']['$permissions']);
$this->assertIsArray($document['body']['$permissions']['read']);
$this->assertIsArray($document['body']['$permissions']['write']);
if($this->getSide() == 'client') {
$this->assertCount(1, $document['body']['$permissions']['read']);
$this->assertCount(1, $document['body']['$permissions']['write']);
$this->assertEquals(['user:'.$this->getUser()['$id']], $document['body']['$permissions']['read']);
$this->assertEquals(['user:'.$this->getUser()['$id']], $document['body']['$permissions']['write']);
}
if($this->getSide() == 'server') {
$this->assertCount(0, $document['body']['$permissions']['read']);
$this->assertCount(0, $document['body']['$permissions']['write']);
$this->assertEquals([], $document['body']['$permissions']['read']);
$this->assertEquals([], $document['body']['$permissions']['write']);
}
// Updated and Inherit Permissions
$document = $this->client->call(Client::METHOD_PATCH, '/database/collections/' . $data['moviesId'] . '/documents/' . $id, array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getHeaders()), [
'data' => [
'name' => 'Captain America 2',
'releaseYear' => 1945,
'actors' => [],
],
'read' => ['*'],
]);
$this->assertEquals($document['headers']['status-code'], 200);
$this->assertEquals($document['body']['name'], 'Captain America 2');
$this->assertEquals($document['body']['releaseYear'], 1945);
if($this->getSide() == 'client') {
$this->assertCount(1, $document['body']['$permissions']['read']);
$this->assertCount(1, $document['body']['$permissions']['write']);
$this->assertEquals(['*'], $document['body']['$permissions']['read']);
$this->assertEquals(['user:'.$this->getUser()['$id']], $document['body']['$permissions']['write']);
}
if($this->getSide() == 'server') {
$this->assertCount(1, $document['body']['$permissions']['read']);
$this->assertCount(0, $document['body']['$permissions']['write']);
$this->assertEquals(['*'], $document['body']['$permissions']['read']);
$this->assertEquals([], $document['body']['$permissions']['write']);
}
$document = $this->client->call(Client::METHOD_GET, '/database/collections/' . $data['moviesId'] . '/documents/' . $id, array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getHeaders()));
$this->assertEquals($document['headers']['status-code'], 200);
$this->assertEquals($document['body']['name'], 'Captain America 2');
$this->assertEquals($document['body']['releaseYear'], 1945);
if($this->getSide() == 'client') {
$this->assertCount(1, $document['body']['$permissions']['read']);
$this->assertCount(1, $document['body']['$permissions']['write']);
$this->assertEquals(['*'], $document['body']['$permissions']['read']);
$this->assertEquals(['user:'.$this->getUser()['$id']], $document['body']['$permissions']['write']);
}
if($this->getSide() == 'server') {
$this->assertCount(1, $document['body']['$permissions']['read']);
$this->assertCount(0, $document['body']['$permissions']['write']);
$this->assertEquals(['*'], $document['body']['$permissions']['read']);
$this->assertEquals([], $document['body']['$permissions']['write']);
}
// Reset Permissions
$document = $this->client->call(Client::METHOD_PATCH, '/database/collections/' . $data['moviesId'] . '/documents/' . $id, array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getHeaders()), [
'data' => [
'name' => 'Captain America 3',
'releaseYear' => 1946,
'actors' => [],
],
'read' => [],
'write' => [],
]);
if($this->getSide() == 'client') {
$this->assertEquals($document['headers']['status-code'], 401);
}
if($this->getSide() == 'server') {
$this->assertEquals($document['headers']['status-code'], 200);
$this->assertEquals($document['body']['name'], 'Captain America 3');
$this->assertEquals($document['body']['releaseYear'], 1946);
$this->assertCount(0, $document['body']['$permissions']['read']);
$this->assertCount(0, $document['body']['$permissions']['write']);
$this->assertEquals([], $document['body']['$permissions']['read']);
$this->assertEquals([], $document['body']['$permissions']['write']);
}
return $data;
}
}

View file

@ -0,0 +1,15 @@
<?php
namespace Appwrite\Tests;
use PHPUnit\Runner\AfterTestHook;
class TestHook implements AfterTestHook
{
public function executeAfterTest(string $test, float $time): void
{
printf("%s ended in %s seconds\n",
$test,
$time
);
}
}

View file

@ -327,7 +327,7 @@ services:
- appwrite-redis:/data:rw
clamav:
image: appwrite/clamav:1.3.0
image: appwrite/clamav:1.2.0
container_name: appwrite-clamav
restart: unless-stopped
networks:

View file

@ -62,41 +62,55 @@ class AuthTest extends TestCase
$this->assertEquals(\mb_strlen(Auth::tokenGenerator(5)), 10);
}
public function testTokenVerify()
public function testSessionVerify()
{
$secret = 'secret1';
$hash = Auth::hash($secret);
$tokens1 = [
new Document([
'$id' => 'token1',
'type' => Auth::TOKEN_TYPE_LOGIN,
'expire' => time() + 60 * 60 * 24,
'secret' => $hash,
'provider' => Auth::SESSION_PROVIDER_EMAIL,
'providerUid' => 'test@example.com',
]),
new Document([
'$id' => 'token2',
'type' => Auth::TOKEN_TYPE_LOGIN,
'expire' => time() - 60 * 60 * 24,
'secret' => 'secret2',
'provider' => Auth::SESSION_PROVIDER_EMAIL,
'providerUid' => 'test@example.com',
]),
];
$tokens2 = [
new Document([ // Correct secret and type time, wrong expire time
'$id' => 'token1',
'type' => Auth::TOKEN_TYPE_LOGIN,
'expire' => time() - 60 * 60 * 24,
'secret' => $hash,
'provider' => Auth::SESSION_PROVIDER_EMAIL,
'providerUid' => 'test@example.com',
]),
new Document([
'$id' => 'token2',
'type' => Auth::TOKEN_TYPE_LOGIN,
'expire' => time() - 60 * 60 * 24,
'secret' => 'secret2',
'provider' => Auth::SESSION_PROVIDER_EMAIL,
'providerUid' => 'test@example.com',
]),
];
$tokens3 = [ // Correct secret and expire time, wrong type
$this->assertEquals(Auth::sessionVerify($tokens1, $secret), 'token1');
$this->assertEquals(Auth::sessionVerify($tokens1, 'false-secret'), false);
$this->assertEquals(Auth::sessionVerify($tokens2, $secret), false);
$this->assertEquals(Auth::sessionVerify($tokens2, 'false-secret'), false);
}
public function testTokenVerify()
{
$secret = 'secret1';
$hash = Auth::hash($secret);
$tokens1 = [
new Document([
'$id' => 'token1',
'type' => Auth::TOKEN_TYPE_RECOVERY,
@ -105,20 +119,51 @@ class AuthTest extends TestCase
]),
new Document([
'$id' => 'token2',
'type' => Auth::TOKEN_TYPE_LOGIN,
'type' => Auth::TOKEN_TYPE_RECOVERY,
'expire' => time() - 60 * 60 * 24,
'secret' => 'secret2',
]),
];
$this->assertEquals(Auth::tokenVerify($tokens1, Auth::TOKEN_TYPE_LOGIN, $secret), 'token1');
$this->assertEquals(Auth::tokenVerify($tokens1, Auth::TOKEN_TYPE_LOGIN, 'false-secret'), false);
$this->assertEquals(Auth::tokenVerify($tokens2, Auth::TOKEN_TYPE_LOGIN, $secret), false);
$this->assertEquals(Auth::tokenVerify($tokens2, Auth::TOKEN_TYPE_LOGIN, 'false-secret'), false);
$this->assertEquals(Auth::tokenVerify($tokens3, Auth::TOKEN_TYPE_LOGIN, $secret), false);
$this->assertEquals(Auth::tokenVerify($tokens3, Auth::TOKEN_TYPE_LOGIN, 'false-secret'), false);
$tokens2 = [
new Document([ // Correct secret and type time, wrong expire time
'$id' => 'token1',
'type' => Auth::TOKEN_TYPE_RECOVERY,
'expire' => time() - 60 * 60 * 24,
'secret' => $hash,
]),
new Document([
'$id' => 'token2',
'type' => Auth::TOKEN_TYPE_RECOVERY,
'expire' => time() - 60 * 60 * 24,
'secret' => 'secret2',
]),
];
$tokens3 = [ // Correct secret and expire time, wrong type
new Document([
'$id' => 'token1',
'type' => Auth::TOKEN_TYPE_INVITE,
'expire' => time() + 60 * 60 * 24,
'secret' => $hash,
]),
new Document([
'$id' => 'token2',
'type' => Auth::TOKEN_TYPE_RECOVERY,
'expire' => time() - 60 * 60 * 24,
'secret' => 'secret2',
]),
];
$this->assertEquals(Auth::tokenVerify($tokens1, Auth::TOKEN_TYPE_RECOVERY, $secret), 'token1');
$this->assertEquals(Auth::tokenVerify($tokens1, Auth::TOKEN_TYPE_RECOVERY, 'false-secret'), false);
$this->assertEquals(Auth::tokenVerify($tokens2, Auth::TOKEN_TYPE_RECOVERY, $secret), false);
$this->assertEquals(Auth::tokenVerify($tokens2, Auth::TOKEN_TYPE_RECOVERY, 'false-secret'), false);
$this->assertEquals(Auth::tokenVerify($tokens3, Auth::TOKEN_TYPE_RECOVERY, $secret), false);
$this->assertEquals(Auth::tokenVerify($tokens3, Auth::TOKEN_TYPE_RECOVERY, 'false-secret'), false);
}
public function testIsPreviliggedUser()
{
$this->assertEquals(false, Auth::isPreviliggedUser([]));

View file

@ -0,0 +1,36 @@
<?php
namespace Appwrite\Tests;
use PHPUnit\Framework\TestCase;
class CollectionsTest extends TestCase
{
protected $collections;
public function setUp(): void
{
$this->collections = require('app/config/collections.php');
}
public function tearDown(): void
{
}
public function testDuplicateRules()
{
foreach ($this->collections as $collection) {
if ($collection['rules']) {
foreach ($collection['rules'] as $check) {
$occurences = 0;
foreach ($collection['rules'] as $rule) {
if ($rule['key'] == $check['key']) {
$occurences++;
}
}
$this->assertEquals(1, $occurences);
}
}
}
}
}

View file

@ -0,0 +1,69 @@
<?php
namespace Appwrite\Tests;
use ReflectionClass;
use Appwrite\Migration\Version\V07;
use Appwrite\Database\Database;
use Appwrite\Database\Document;
use Appwrite\Auth\Auth;
use Utopia\Config\Config;
class MigrationV07Test extends MigrationTest
{
public function setUp(): void
{
Config::load('providers', __DIR__ . '/../../../app/config/providers.php');
$this->pdo = new \PDO('sqlite::memory:');
$this->migration = new V07($this->pdo);
$reflector = new ReflectionClass('Appwrite\Migration\Version\V07');
$this->method = $reflector->getMethod('fixDocument');
$this->method->setAccessible(true);
}
public function testMigration()
{
$document = $this->fixDocument(new Document([
'$id' => 'unique',
'$collection' => Database::SYSTEM_COLLECTION_USERS,
'oauth2Github' => 123,
'oauth2GithubAccessToken' => 456,
'tokens' => [
new Document([
'$collection' => Database::SYSTEM_COLLECTION_TOKENS,
'userId' => 'unique',
'type' => Auth::TOKEN_TYPE_LOGIN,
'secret' => 'login',
]),
new Document([
'$collection' => Database::SYSTEM_COLLECTION_TOKENS,
'userId' => 'unique',
'type' => Auth::TOKEN_TYPE_INVITE,
'secret' => 'invite',
]),
new Document([
'$collection' => Database::SYSTEM_COLLECTION_TOKENS,
'userId' => 'unique',
'type' => Auth::TOKEN_TYPE_RECOVERY,
'secret' => 'recovery',
]),
new Document([
'$collection' => Database::SYSTEM_COLLECTION_TOKENS,
'userId' => 'unique',
'type' => Auth::TOKEN_TYPE_VERIFICATION,
'secret' => 'verification',
]),
]
]));
$this->assertEquals($document->getAttribute('oauth2Github', null), null);
$this->assertEquals($document->getAttribute('oauth2GithubAccessToken', null), null);
$this->assertCount(3, $document->getAttribute('tokens', []));
$this->assertEquals(Auth::TOKEN_TYPE_INVITE, $document->getAttribute('tokens', [])[0]['type']);
$this->assertEquals(Auth::TOKEN_TYPE_RECOVERY, $document->getAttribute('tokens', [])[1]['type']);
$this->assertEquals(Auth::TOKEN_TYPE_VERIFICATION, $document->getAttribute('tokens', [])[2]['type']);
}
}