Add public mocks API for phones

This commit is contained in:
Matej Bačo
2026-04-22 11:30:39 +02:00
parent af531ee4f9
commit 2e42633e12
13 changed files with 520 additions and 14 deletions
+10
View File
@@ -1408,4 +1408,14 @@ return [
'description' => 'When using project API key, make sure to pass x-appwrite-project header with your project ID.',
'code' => 403,
],
Exception::MOCK_NUMBER_ALREADY_EXISTS => [
'name' => Exception::MOCK_NUMBER_ALREADY_EXISTS,
'description' => 'Mock number with the requested number already exists. Try again with a different number. or update OTP of existing mock number.',
'code' => 409,
],
Exception::MOCK_NUMBER_NOT_FOUND => [
'name' => Exception::MOCK_NUMBER_NOT_FOUND,
'description' => 'Mock number with the requested number could not be found.',
'code' => 404,
],
];
+1 -13
View File
@@ -170,23 +170,11 @@ Http::patch('/v1/projects/:projectId/auth/:method')
$response->dynamic($project, Response::MODEL_PROJECT);
});
// Backwards compatibility
Http::patch('/v1/projects/:projectId/auth/mock-numbers')
->desc('Update the mock numbers for the project')
->groups(['api', 'projects'])
->label('scope', 'projects.write')
->label('sdk', new Method(
namespace: 'projects',
group: 'auth',
name: 'updateMockNumbers',
description: '/docs/references/projects/update-mock-numbers.md',
auth: [AuthType::ADMIN],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_OK,
model: Response::MODEL_PROJECT,
)
]
))
->param('projectId', '', fn (Database $dbForPlatform) => new UID($dbForPlatform->getAdapter()->getMaxUIDLength()), 'Project unique ID.', false, ['dbForPlatform'])
->param('numbers', '', new ArrayList(new MockNumber(), 10), 'An array of mock numbers and their corresponding verification codes (OTPs). Each number should be a valid E.164 formatted phone number. Maximum of 10 numbers are allowed.')
->inject('response')
+1
View File
@@ -210,6 +210,7 @@ Response::setModel(new BaseList('Currencies List', Response::MODEL_CURRENCY_LIST
Response::setModel(new BaseList('Phones List', Response::MODEL_PHONE_LIST, 'phones', Response::MODEL_PHONE));
Response::setModel(new BaseList('Metric List', Response::MODEL_METRIC_LIST, 'metrics', Response::MODEL_METRIC, true, false));
Response::setModel(new BaseList('Variables List', Response::MODEL_VARIABLE_LIST, 'variables', Response::MODEL_VARIABLE));
Response::setModel(new BaseList('Mock Numbers List', Response::MODEL_MOCK_NUMBER_LIST, 'mockNumbers', Response::MODEL_MOCK_NUMBER));
Response::setModel(new BaseList('Status List', Response::MODEL_HEALTH_STATUS_LIST, 'statuses', Response::MODEL_HEALTH_STATUS));
Response::setModel(new BaseList('Rule List', Response::MODEL_PROXY_RULE_LIST, 'rules', Response::MODEL_PROXY_RULE));
Response::setModel(new BaseList('Schedules List', Response::MODEL_SCHEDULE_LIST, 'schedules', Response::MODEL_SCHEDULE));
+4
View File
@@ -384,6 +384,10 @@ class Exception extends \Exception
public const string MESSAGE_TARGET_NOT_PUSH = 'message_target_not_push';
public const string MESSAGE_MISSING_SCHEDULE = 'message_missing_schedule';
/** Mocks */
public const string MOCK_NUMBER_ALREADY_EXISTS = 'mock_number_already_exists';
public const string MOCK_NUMBER_NOT_FOUND = 'mock_number_not_found';
/** Targets */
public const string TARGET_PROVIDER_INVALID_TYPE = 'target_provider_invalid_type';
@@ -0,0 +1,107 @@
<?php
namespace Appwrite\Platform\Modules\Project\Http\Project\MockPhone;
use Appwrite\Auth\Validator\Phone;
use Appwrite\Event\Event as QueueEvent;
use Appwrite\Extend\Exception;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
use Appwrite\Utopia\Response;
use Utopia\Database\Database;
use Utopia\Database\DateTime;
use Utopia\Database\Document;
use Utopia\Database\Validator\Authorization;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
use Utopia\Validator\Text;
class Create extends Action
{
use HTTP;
public static function getName()
{
return 'createProjectMockPhone';
}
public function __construct()
{
$this
->setHttpMethod(Action::HTTP_REQUEST_METHOD_POST)
->setHttpPath('/v1/project/mock-phones')
->desc('Create project mock phone')
->groups(['api', 'project'])
->label('scope', 'mocks.write')
->label('event', 'mock-phones.[number].create')
->label('audits.event', 'project.mock-phone.create')
->label('audits.resource', 'project.mock-phone/{response.number}')
->label('sdk', new Method(
namespace: 'project',
group: 'mocks',
name: 'createMockPhone',
description: <<<EOT
Create a new mock phone for your project. Use this endpoint to register a mock phone number and its sign-in OTP for your testers.
EOT,
auth: [AuthType::ADMIN, AuthType::KEY],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_CREATED,
model: Response::MODEL_MOCK_NUMBER,
)
],
))
->param('number', null, new Phone(), 'Phone number to associate with the mock phone. Must be a valid E.164 formatted phone number.')
->param('otp', '', new Text(6, 6, Text::NUMBERS), 'One-time password (OTP) to associate with the mock phone. Must be a 6-digit numeric code.')
->inject('response')
->inject('queueForEvents')
->inject('project')
->inject('dbForPlatform')
->inject('authorization')
->callback($this->action(...));
}
public function action(
string $number,
string $otp,
Response $response,
QueueEvent $queueForEvents,
Document $project,
Database $dbForPlatform,
Authorization $authorization,
) {
$auths = $project->getAttribute('auths', []);
$mockNumbers = $auths['mockNumbers'] ?? [];
foreach ($mockNumbers as $mockNumber) {
if ($mockNumber['number'] === $number) {
throw new Exception(Exception::MOCK_NUMBER_ALREADY_EXISTS);
}
}
// Set to now date
$mockNumber = [
'number' => $number,
'otp' => $otp,
'$createdAt' => DateTime::now(),
'$updatedAt' => DateTime::now(),
];
$mockNumbers[] = $mockNumber;
$auths['mockNumbers'] = $mockNumbers;
$updates = new Document([
'auths' => $auths,
]);
$authorization->skip(fn () => $dbForPlatform->updateDocument('projects', $project->getId(), $updates));
$queueForEvents->setParam('number', $number);
$response
->setStatusCode(Response::STATUS_CODE_CREATED)
->dynamic(new Document($mockNumber), Response::MODEL_MOCK_NUMBER);
}
}
@@ -0,0 +1,103 @@
<?php
namespace Appwrite\Platform\Modules\Project\Http\Project\MockPhone;
use Appwrite\Auth\Validator\Phone;
use Appwrite\Event\Event as QueueEvent;
use Appwrite\Extend\Exception;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\ContentType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
use Appwrite\Utopia\Response;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Validator\Authorization;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
class Delete extends Action
{
use HTTP;
public static function getName()
{
return 'deleteProjectMockPhone';
}
public function __construct()
{
$this
->setHttpMethod(Action::HTTP_REQUEST_METHOD_DELETE)
->setHttpPath('/v1/project/mock-phones/:number')
->desc('Delete project mock phone')
->groups(['api', 'project'])
->label('scope', 'mocks.write')
->label('event', 'mock-phones.[number].delete')
->label('audits.event', 'project.mock-phone.delete')
->label('audits.resource', 'project.mock-phone/{request.number}')
->label('sdk', new Method(
namespace: 'project',
group: 'mocks',
name: 'deleteMockPhone',
description: <<<EOT
Delete a mock phone by its unique number. This endpoint removes the mock phone and its OTP configuration from the project.
EOT,
auth: [AuthType::ADMIN, AuthType::KEY],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_NOCONTENT,
model: Response::MODEL_NONE,
)
],
contentType: ContentType::NONE
))
->param('number', null, new Phone(), 'Phone number associated with the mock phone. Must be a valid E.164 formatted phone number.')
->inject('response')
->inject('queueForEvents')
->inject('project')
->inject('dbForPlatform')
->inject('authorization')
->callback($this->action(...));
}
public function action(
string $number,
Response $response,
QueueEvent $queueForEvents,
Document $project,
Database $dbForPlatform,
Authorization $authorization,
) {
$auths = $project->getAttribute('auths', []);
$mockNumbers = $auths['mockNumbers'] ?? [];
$mockNumberIndex = null;
foreach ($mockNumbers as $index => $mock) {
if ($mock['number'] === $number) {
$mockNumberIndex = $index;
break;
}
}
if (\is_null($mockNumberIndex)) {
throw new Exception(Exception::MOCK_NUMBER_NOT_FOUND);
}
unset($mockNumbers[$mockNumberIndex]);
$mockNumbers = array_values($mockNumbers);
$auths['mockNumbers'] = $mockNumbers;
$updates = new Document([
'auths' => $auths,
]);
$authorization->skip(fn () => $dbForPlatform->updateDocument('projects', $project->getId(), $updates));
$queueForEvents->setParam('number', $number);
$response->noContent();
}
}
@@ -0,0 +1,78 @@
<?php
namespace Appwrite\Platform\Modules\Project\Http\Project\MockPhone;
use Appwrite\Auth\Validator\Phone;
use Appwrite\Extend\Exception;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
use Appwrite\Utopia\Response;
use Utopia\Database\Document;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
class Get extends Action
{
use HTTP;
public static function getName()
{
return 'getProjectMockPhone';
}
public function __construct()
{
$this
->setHttpMethod(Action::HTTP_REQUEST_METHOD_GET)
->setHttpPath('/v1/project/mock-phones/:number')
->desc('Get project mock phone')
->groups(['api', 'project'])
->label('scope', 'mocks.read')
->label('sdk', new Method(
namespace: 'project',
group: 'mocks',
name: 'getMockPhone',
description: <<<EOT
Get a mock phone by its unique number. This endpoint returns the mock phone's OTP.
EOT,
auth: [AuthType::ADMIN, AuthType::KEY],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_OK,
model: Response::MODEL_MOCK_NUMBER
)
]
))
->param('number', null, new Phone(), 'Phone number associated with the mock phone. Must be a valid E.164 formatted phone number.')
->inject('response')
->inject('project')
->callback($this->action(...));
}
public function action(
string $number,
Response $response,
Document $project
) {
$auths = $project->getAttribute('auths', []);
$mockNumbers = $auths['mockNumbers'] ?? [];
$mockNumberIndex = null;
foreach ($mockNumbers as $index => $mock) {
if ($mock['number'] === $number) {
$mockNumberIndex = $index;
break;
}
}
if (\is_null($mockNumberIndex)) {
throw new Exception(Exception::MOCK_NUMBER_NOT_FOUND);
}
$response
->setStatusCode(Response::STATUS_CODE_OK)
->dynamic(new Document($mockNumbers[$mockNumberIndex]), Response::MODEL_MOCK_NUMBER);
}
}
@@ -0,0 +1,107 @@
<?php
namespace Appwrite\Platform\Modules\Project\Http\Project\MockPhone;
use Appwrite\Auth\Validator\Phone;
use Appwrite\Event\Event as QueueEvent;
use Appwrite\Extend\Exception;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
use Appwrite\Utopia\Response;
use Utopia\Database\Database;
use Utopia\Database\DateTime;
use Utopia\Database\Document;
use Utopia\Database\Validator\Authorization;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
use Utopia\Validator\Text;
class Update extends Action
{
use HTTP;
public static function getName()
{
return 'updateProjectMockPhone';
}
public function __construct()
{
$this
->setHttpMethod(Action::HTTP_REQUEST_METHOD_PUT)
->setHttpPath('/v1/project/mock-phones/:number')
->desc('Update project mock phone')
->groups(['api', 'project'])
->label('scope', 'mocks.write')
->label('event', 'mock-phones.[number].update')
->label('audits.event', 'project.mock-phone.update')
->label('audits.resource', 'project.mock-phone/{response.number}')
->label('sdk', new Method(
namespace: 'project',
group: 'mocks',
name: 'updateMockPhone',
description: <<<EOT
Update a mock phone by its unique number. Use this endpoint to update the mock phone's OTP.
EOT,
auth: [AuthType::ADMIN, AuthType::KEY],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_OK,
model: Response::MODEL_MOCK_NUMBER
)
]
))
->param('number', null, new Phone(), 'Phone number associated with the mock phone. Must be a valid E.164 formatted phone number.')
->param('otp', '', new Text(6, 6, Text::NUMBERS), 'One-time password (OTP) to associate with the mock phone. Must be a 6-digit numeric code.')
->inject('response')
->inject('queueForEvents')
->inject('project')
->inject('dbForPlatform')
->inject('authorization')
->callback($this->action(...));
}
public function action(
string $number,
string $otp,
Response $response,
QueueEvent $queueForEvents,
Document $project,
Database $dbForPlatform,
Authorization $authorization,
) {
$auths = $project->getAttribute('auths', []);
$mockNumbers = $auths['mockNumbers'] ?? [];
$mockNumberIndex = null;
foreach ($mockNumbers as $index => $mock) {
if ($mock['number'] === $number) {
$mockNumberIndex = $index;
break;
}
}
if (\is_null($mockNumberIndex)) {
throw new Exception(Exception::MOCK_NUMBER_NOT_FOUND);
}
$mockNumbers[$mockNumberIndex]['otp'] = $otp;
$mockNumbers[$mockNumberIndex]['$updatedAt'] = DateTime::now();
$auths['mockNumbers'] = $mockNumbers;
$updates = new Document([
'auths' => $auths,
]);
$authorization->skip(fn () => $dbForPlatform->updateDocument('projects', $project->getId(), $updates));
$queueForEvents->setParam('number', $number);
$response
->setStatusCode(Response::STATUS_CODE_OK)
->dynamic(new Document($mockNumbers[$mockNumberIndex]), Response::MODEL_MOCK_NUMBER);
}
}
@@ -0,0 +1,69 @@
<?php
namespace Appwrite\Platform\Modules\Project\Http\Project\MockPhone;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
use Appwrite\Utopia\Response;
use Utopia\Database\Document;
use Utopia\Platform\Action;
use Utopia\Platform\Scope\HTTP;
use Utopia\Validator\Boolean;
class XList extends Action
{
use HTTP;
public static function getName()
{
return 'listProjectMockPhones';
}
public function __construct()
{
$this
->setHttpMethod(Action::HTTP_REQUEST_METHOD_GET)
->setHttpPath('/v1/project/mock-phones')
->desc('List project mock phones')
->groups(['api', 'project'])
->label('scope', 'mocks.read')
->label('sdk', new Method(
namespace: 'project',
group: 'mocks',
name: 'listMockPhones',
description: <<<EOT
Get a list of all mock phones in the project. This endpoint returns an array of all mock phones and their OTPs.
EOT,
auth: [AuthType::ADMIN, AuthType::KEY],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_OK,
model: Response::MODEL_MOCK_NUMBER_LIST,
)
]
))
->param('total', true, new Boolean(true), 'When set to false, the total count returned will be 0 and will not be calculated.', true)
->inject('response')
->inject('project')
->callback($this->action(...));
}
public function action(
bool $includeTotal,
Response $response,
Document $project,
) {
$auths = $project->getAttribute('auths', []);
$mockNumbers = $auths['mockNumbers'] ?? [];
$total = $includeTotal ? \count($mockNumbers) : 0;
$mockNumbers = \array_map(fn ($mockNumber) => new Document($mockNumber), $mockNumbers);
$response->dynamic(new Document([
'mockNumbers' => $mockNumbers,
'total' => $total,
]), Response::MODEL_MOCK_NUMBER_LIST);
}
}
@@ -9,6 +9,11 @@ use Appwrite\Platform\Modules\Project\Http\Project\Keys\Get as GetKey;
use Appwrite\Platform\Modules\Project\Http\Project\Keys\Update as UpdateKey;
use Appwrite\Platform\Modules\Project\Http\Project\Keys\XList as ListKeys;
use Appwrite\Platform\Modules\Project\Http\Project\Labels\Update as UpdateProjectLabels;
use Appwrite\Platform\Modules\Project\Http\Project\MockPhone\Create as CreateMockPhone;
use Appwrite\Platform\Modules\Project\Http\Project\MockPhone\Delete as DeleteMockPhone;
use Appwrite\Platform\Modules\Project\Http\Project\MockPhone\Get as GetMockPhone;
use Appwrite\Platform\Modules\Project\Http\Project\MockPhone\Update as UpdateMockPhone;
use Appwrite\Platform\Modules\Project\Http\Project\MockPhone\XList as ListMockPhones;
use Appwrite\Platform\Modules\Project\Http\Project\Platforms\Android\Create as CreateAndroidPlatform;
use Appwrite\Platform\Modules\Project\Http\Project\Platforms\Android\Update as UpdateAndroidPlatform;
use Appwrite\Platform\Modules\Project\Http\Project\Platforms\Apple\Create as CreateApplePlatform;
@@ -95,6 +100,13 @@ class Http extends Service
$this->addAction(GetPlatform::getName(), new GetPlatform());
$this->addAction(ListPlatforms::getName(), new ListPlatforms());
// Mock Phones
$this->addAction(CreateMockPhone::getName(), new CreateMockPhone());
$this->addAction(ListMockPhones::getName(), new ListMockPhones());
$this->addAction(GetMockPhone::getName(), new GetMockPhone());
$this->addAction(UpdateMockPhone::getName(), new UpdateMockPhone());
$this->addAction(DeleteMockPhone::getName(), new DeleteMockPhone());
// Policies
$this->addAction(UpdateMembershipPrivacyPolicy::getName(), new UpdateMembershipPrivacyPolicy());
$this->addAction(UpdatePasswordDictionaryPolicy::getName(), new UpdatePasswordDictionaryPolicy());
+1
View File
@@ -254,6 +254,7 @@ class Response extends SwooleResponse
public const MODEL_DEV_KEY = 'devKey';
public const MODEL_DEV_KEY_LIST = 'devKeyList';
public const MODEL_MOCK_NUMBER = 'mockNumber';
public const MODEL_MOCK_NUMBER_LIST = 'mockNumberList';
public const MODEL_AUTH_PROVIDER = 'authProvider';
public const MODEL_AUTH_PROVIDER_LIST = 'authProviderList';
public const MODEL_PLATFORM_APPLE = 'platformApple';
@@ -16,10 +16,24 @@ class V23 extends Filter
Response::MODEL_PROJECT => $this->parseProject($content),
Response::MODEL_PROJECT_LIST => $this->handleList($content, 'projects', fn ($item) => $this->parseProject($item)),
Response::MODEL_EMAIL_TEMPLATE => $this->parseEmailTemplate($content),
Response::MODEL_MOCK_NUMBER => $this->parseMockNumber($content),
default => $content,
};
}
private function parseMockNumber(array $content): array
{
unset($content['$createdAt']);
unset($content['$updatedAt']);
if (isset($content['number'])) {
$content['phone'] = $content['number'];
unset($content['number']);
}
return $content;
}
private function parseMembership(array $content): array
{
unset($content['userPhone']);
@@ -10,7 +10,7 @@ class MockNumber extends Model
public function __construct()
{
$this
->addRule('phone', [
->addRule('number', [
'type' => self::TYPE_STRING,
'description' => 'Mock phone number for testing phone authentication. Useful for testing phone authentication without sending an SMS.',
'default' => '',
@@ -22,6 +22,18 @@ class MockNumber extends Model
'default' => '',
'example' => '123456',
])
->addRule('$createdAt', [
'type' => self::TYPE_DATETIME,
'description' => 'Attribute creation date in ISO 8601 format.',
'default' => '',
'example' => self::TYPE_DATETIME_EXAMPLE,
])
->addRule('$updatedAt', [
'type' => self::TYPE_DATETIME,
'description' => 'Attribute update date in ISO 8601 format.',
'default' => '',
'example' => self::TYPE_DATETIME_EXAMPLE,
]);
;
}