1
0
Fork 0
mirror of synced 2024-06-02 10:54:44 +12:00

Merge branch '0.8.x' of https://github.com/appwrite/appwrite into feat-265-realtime

This commit is contained in:
Torsten Dittmann 2021-03-29 17:52:42 +02:00
commit c31ffdcae3
26 changed files with 585 additions and 34 deletions

View file

@ -1,16 +1,21 @@
# Version 0.8.0 (Not Released Yet)
## Features
- Realtime Integration (#948)
- Anonymous login (#914)
- Realtime Integration ([RFC-014](https://github.com/appwrite/rfc/blob/main/014-realtime-api.md), #948)
- 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 (Not Released Yet)
# Version 0.7.2
## Features

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)
@ -367,6 +367,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.2
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.2
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.2
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,
],
[

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());
@ -487,7 +487,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);
@ -517,6 +517,15 @@ 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)
@ -566,6 +575,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_TOKENS,
'$permissions' => ['read' => ['user:' . $user['$id']], 'write' => ['user:' . $user['$id']]],
'userId' => $user->getId(),
'type' => Auth::TOKEN_TYPE_LOGIN,
'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('tokens', $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'])
@ -880,7 +1013,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 +1036,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);

View file

@ -47,7 +47,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.2';
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';

View file

@ -63,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",
"textalk/websocket": "1.5.2",

8
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": "69222438c59581b58de7052befa6ac00",
"content-hash": "a5a066bf0b739b7b412149aeb0e9a396",
"packages": [
{
"name": "adhocore/jwt",
@ -2351,11 +2351,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": "*",
@ -2385,7 +2385,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",

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

@ -28,6 +28,21 @@ static async Task Main(string[] args)
}
```
### 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)

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

@ -41,6 +41,19 @@ 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)

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

@ -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 [];
}
}