2019-05-09 18:54:39 +12:00
< ? php
2021-06-13 07:37:19 +12:00
use Ahc\Jwt\JWT ;
2020-03-25 06:56:32 +13:00
use Appwrite\Auth\Auth ;
2023-07-15 12:28:45 +12:00
use Appwrite\Auth\OAuth2\Exception as OAuth2Exception ;
2020-03-25 06:56:32 +13:00
use Appwrite\Auth\Validator\Password ;
2022-08-15 03:10:12 +12:00
use Appwrite\Auth\Validator\Phone ;
2021-02-15 06:28:54 +13:00
use Appwrite\Detector\Detector ;
2022-05-19 04:14:21 +12:00
use Appwrite\Event\Event ;
use Appwrite\Event\Mail ;
2024-02-02 03:13:30 +13:00
use Appwrite\Auth\Phrase ;
2022-08-12 11:53:52 +12:00
use Appwrite\Extend\Exception ;
2021-05-07 10:31:05 +12:00
use Appwrite\Network\Validator\Email ;
2023-01-14 04:28:04 +13:00
use Utopia\Validator\Host ;
use Utopia\Validator\URL ;
2024-01-11 03:52:32 +13:00
use Utopia\Validator\Boolean ;
2021-08-05 17:06:38 +12:00
use Appwrite\OpenSSL\OpenSSL ;
use Appwrite\Template\Template ;
use Appwrite\URL\URL as URLParser ;
2022-08-12 11:53:52 +12:00
use Appwrite\Utopia\Database\Validator\CustomId ;
2023-05-18 13:11:45 +12:00
use Appwrite\Utopia\Database\Validator\Queries\Identities ;
2023-04-25 23:35:49 +12:00
use Utopia\Database\Validator\Queries ;
use Utopia\Database\Validator\Query\Limit ;
use Utopia\Database\Validator\Query\Offset ;
2022-05-19 04:14:21 +12:00
use Appwrite\Utopia\Request ;
2021-08-05 17:06:38 +12:00
use Appwrite\Utopia\Response ;
2022-05-19 04:14:21 +12:00
use MaxMind\Db\Reader ;
2021-05-07 10:31:05 +12:00
use Utopia\App ;
2022-05-26 01:49:32 +12:00
use Utopia\Audit\Audit as EventAudit ;
2021-08-05 17:06:38 +12:00
use Utopia\Config\Config ;
2022-05-19 04:14:21 +12:00
use Utopia\Database\Database ;
2021-05-07 10:31:05 +12:00
use Utopia\Database\Document ;
2022-07-13 01:32:39 +12:00
use Utopia\Database\DateTime ;
2021-05-07 10:31:05 +12:00
use Utopia\Database\Exception\Duplicate ;
2022-12-15 04:42:25 +13:00
use Utopia\Database\Helpers\ID ;
2022-12-15 05:04:06 +13:00
use Utopia\Database\Helpers\Permission ;
2021-05-07 10:31:05 +12:00
use Utopia\Database\Query ;
2022-12-15 05:04:06 +13:00
use Utopia\Database\Helpers\Role ;
2021-05-07 10:31:05 +12:00
use Utopia\Database\Validator\Authorization ;
use Utopia\Database\Validator\UID ;
2022-05-19 04:14:21 +12:00
use Utopia\Locale\Locale ;
2021-08-05 17:06:38 +12:00
use Utopia\Validator\ArrayList ;
use Utopia\Validator\Assoc ;
use Utopia\Validator\Text ;
use Utopia\Validator\WhiteList ;
2022-12-18 22:08:51 +13:00
use Appwrite\Auth\Validator\PasswordHistory ;
2022-12-26 23:22:49 +13:00
use Appwrite\Auth\Validator\PasswordDictionary ;
2023-04-14 08:20:03 +12:00
use Appwrite\Auth\Validator\PersonalData ;
2024-01-23 06:29:10 +13:00
use Appwrite\Event\Delete ;
2023-09-06 05:10:48 +12:00
use Appwrite\Event\Messaging ;
2023-12-16 11:19:43 +13:00
use Appwrite\Hooks\Hooks ;
2019-05-09 18:54:39 +12:00
2022-11-19 09:24:04 +13:00
$oauthDefaultSuccess = '/auth/oauth2/success' ;
$oauthDefaultFailure = '/auth/oauth2/failure' ;
2020-04-09 01:38:36 +12:00
2020-06-29 05:31:21 +12:00
App :: post ( '/v1/account' )
2023-08-02 03:26:48 +12:00
-> desc ( 'Create account' )
2021-03-01 07:36:13 +13:00
-> groups ([ 'api' , 'account' , 'auth' ])
2022-04-04 18:30:07 +12:00
-> label ( 'event' , 'users.[userId].create' )
2024-01-18 00:17:03 +13:00
-> label ( 'scope' , 'sessions.write' )
2021-03-01 07:36:13 +13:00
-> label ( 'auth.type' , 'emailPassword' )
2022-09-09 01:06:16 +12:00
-> label ( 'audits.event' , 'user.create' )
2022-08-09 02:32:54 +12:00
-> label ( 'audits.resource' , 'user/{response.$id}' )
2022-08-17 02:56:05 +12:00
-> label ( 'audits.userId' , '{response.$id}' )
2021-04-16 19:22:17 +12:00
-> label ( 'sdk.auth' , [])
2020-01-04 10:00:53 +13:00
-> label ( 'sdk.namespace' , 'account' )
2020-01-31 05:18:46 +13:00
-> label ( 'sdk.method' , 'create' )
2020-01-06 00:29:42 +13:00
-> label ( 'sdk.description' , '/docs/references/account/create.md' )
2020-11-12 10:02:24 +13:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_CREATED )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
2023-02-15 13:10:54 +13:00
-> label ( 'sdk.response.model' , Response :: MODEL_USER )
2020-01-04 10:00:53 +13:00
-> label ( 'abuse-limit' , 10 )
2024-01-13 06:26:01 +13:00
-> param ( 'userId' , '' , new CustomId (), 'User ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can\'t start with a special char. Max length is 36 chars.' )
2020-09-11 02:40:14 +12:00
-> param ( 'email' , '' , new Email (), 'User email.' )
2024-01-02 23:59:35 +13:00
-> param ( 'password' , '' , fn ( $project , $passwordsDictionary ) => new PasswordDictionary ( $passwordsDictionary , $project -> getAttribute ( 'auths' , [])[ 'passwordDictionary' ] ? ? false ), 'New user password. Must be between 8 and 256 chars.' , false , [ 'project' , 'passwordsDictionary' ])
2020-09-11 02:40:14 +12:00
-> param ( 'name' , '' , new Text ( 128 ), 'User name. Max length: 128 chars.' , true )
2020-12-27 03:31:53 +13:00
-> inject ( 'request' )
-> inject ( 'response' )
2023-07-07 12:12:39 +12:00
-> inject ( 'user' )
2020-12-27 03:31:53 +13:00
-> inject ( 'project' )
2021-12-28 01:45:23 +13:00
-> inject ( 'dbForProject' )
2022-12-21 05:11:30 +13:00
-> inject ( 'queueForEvents' )
2023-12-16 11:19:43 +13:00
-> inject ( 'hooks' )
-> action ( function ( string $userId , string $email , string $password , string $name , Request $request , Response $response , Document $user , Document $project , Database $dbForProject , Event $queueForEvents , Hooks $hooks ) {
2020-06-30 09:43:34 +12:00
2021-06-04 00:58:40 +12:00
$email = \strtolower ( $email );
2020-06-30 09:43:34 +12:00
if ( 'console' === $project -> getId ()) {
2021-06-04 00:58:40 +12:00
$whitelistEmails = $project -> getAttribute ( 'authWhitelistEmails' );
$whitelistIPs = $project -> getAttribute ( 'authWhitelistIPs' );
2020-06-30 09:43:34 +12:00
2023-02-23 00:39:22 +13:00
if ( ! empty ( $whitelistEmails ) && ! \in_array ( $email , $whitelistEmails ) && ! \in_array ( strtoupper ( $email ), $whitelistEmails )) {
2022-07-23 02:38:06 +12:00
throw new Exception ( Exception :: USER_EMAIL_NOT_WHITELISTED );
2020-01-04 10:00:53 +13:00
}
2021-06-04 00:58:40 +12:00
if ( ! empty ( $whitelistIPs ) && ! \in_array ( $request -> getIP (), $whitelistIPs )) {
2022-07-23 02:38:06 +12:00
throw new Exception ( Exception :: USER_IP_NOT_WHITELISTED );
2020-01-04 10:00:53 +13:00
}
2020-06-30 09:43:34 +12:00
}
2020-01-04 10:00:53 +13:00
2021-08-06 20:34:17 +12:00
$limit = $project -> getAttribute ( 'auths' , [])[ 'limit' ] ? ? 0 ;
2021-03-01 07:36:13 +13:00
if ( $limit !== 0 ) {
2022-05-16 21:58:17 +12:00
$total = $dbForProject -> count ( 'users' , max : APP_LIMIT_USERS );
2021-03-01 07:36:13 +13:00
2022-02-27 22:57:09 +13:00
if ( $total >= $limit ) {
2022-07-23 02:38:06 +12:00
throw new Exception ( Exception :: USER_COUNT_EXCEEDED );
2021-03-01 07:36:13 +13:00
}
}
2023-05-18 13:11:45 +12:00
// Makes sure this email is not already used in another identity
$identityWithMatchingEmail = $dbForProject -> findOne ( 'identities' , [
Query :: equal ( 'providerEmail' , [ $email ]),
]);
if ( $identityWithMatchingEmail !== false && ! $identityWithMatchingEmail -> isEmpty ()) {
throw new Exception ( Exception :: USER_EMAIL_ALREADY_EXISTS );
}
2023-07-20 10:24:32 +12:00
if ( $project -> getAttribute ( 'auths' , [])[ 'personalDataCheck' ] ? ? false ) {
2023-04-14 08:20:03 +12:00
$personalDataValidator = new PersonalData ( $userId , $email , $name , null );
if ( ! $personalDataValidator -> isValid ( $password )) {
throw new Exception ( Exception :: USER_PASSWORD_PERSONAL_DATA );
}
}
2024-01-06 00:31:38 +13:00
$hooks -> trigger ( 'passwordValidator' , [ $dbForProject , $project , $password , & $user , true ]);
2023-12-16 11:19:43 +13:00
2022-12-18 19:31:14 +13:00
$passwordHistory = $project -> getAttribute ( 'auths' , [])[ 'passwordHistory' ] ? ? 0 ;
2022-12-18 19:27:41 +13:00
$password = Auth :: passwordHash ( $password , Auth :: DEFAULT_ALGO , Auth :: DEFAULT_ALGO_OPTIONS );
2020-06-30 09:43:34 +12:00
try {
2022-08-15 02:22:38 +12:00
$userId = $userId == 'unique()' ? ID :: unique () : $userId ;
2023-07-07 12:12:39 +12:00
$user -> setAttributes ([
2022-08-15 23:24:31 +12:00
'$id' => $userId ,
2022-08-02 21:21:53 +12:00
'$permissions' => [
2022-08-14 17:21:11 +12:00
Permission :: read ( Role :: any ()),
2022-08-15 23:24:31 +12:00
Permission :: update ( Role :: user ( $userId )),
Permission :: delete ( Role :: user ( $userId )),
2022-08-02 21:21:53 +12:00
],
2020-06-30 09:43:34 +12:00
'email' => $email ,
'emailVerification' => false ,
2021-07-14 23:02:12 +12:00
'status' => true ,
2022-12-18 19:27:41 +13:00
'password' => $password ,
2023-02-20 14:51:56 +13:00
'passwordHistory' => $passwordHistory > 0 ? [ $password ] : [],
'passwordUpdate' => DateTime :: now (),
2022-06-14 00:53:28 +12:00
'hash' => Auth :: DEFAULT_ALGO ,
'hashOptions' => Auth :: DEFAULT_ALGO_OPTIONS ,
2022-07-14 02:02:49 +12:00
'registration' => DateTime :: now (),
2020-06-30 09:43:34 +12:00
'reset' => false ,
'name' => $name ,
2021-12-28 23:48:50 +13:00
'prefs' => new \stdClass (),
2022-04-26 22:36:49 +12:00
'sessions' => null ,
2022-04-27 23:06:53 +12:00
'tokens' => null ,
2022-04-28 00:44:47 +12:00
'memberships' => null ,
2023-07-07 12:12:39 +12:00
'search' => implode ( ' ' , [ $userId , $email , $name ]),
2023-08-23 13:34:23 +12:00
'accessedAt' => DateTime :: now (),
2023-07-07 12:12:39 +12:00
]);
2023-09-14 07:18:50 +12:00
$user -> removeAttribute ( '$internalId' );
2023-11-15 08:54:55 +13:00
$user = Authorization :: skip ( fn () => $dbForProject -> createDocument ( 'users' , $user ));
2023-11-29 02:12:34 +13:00
try {
$target = Authorization :: skip ( fn () => $dbForProject -> createDocument ( 'targets' , new Document ([
'userId' => $user -> getId (),
'userInternalId' => $user -> getInternalId (),
2023-11-29 22:31:47 +13:00
'providerType' => MESSAGE_TYPE_EMAIL ,
2023-11-29 02:12:34 +13:00
'identifier' => $email ,
])));
$user -> setAttribute ( 'targets' , [ ... $user -> getAttribute ( 'targets' , []), $target ]);
} catch ( Duplicate ) {
$existingTarget = $dbForProject -> findOne ( 'targets' , [
Query :: equal ( 'identifier' , [ $email ]),
]);
$user -> setAttribute ( 'targets' , [ ... $user -> getAttribute ( 'targets' , []), $existingTarget ]);
}
2023-12-15 18:24:37 +13:00
2023-12-15 17:45:25 +13:00
$dbForProject -> purgeCachedDocument ( 'users' , $user -> getId ());
2023-08-23 13:34:23 +12:00
} catch ( Duplicate ) {
2022-07-23 02:38:06 +12:00
throw new Exception ( Exception :: USER_ALREADY_EXISTS );
2020-06-30 09:43:34 +12:00
}
2020-01-04 10:00:53 +13:00
2022-08-19 16:04:33 +12:00
Authorization :: unsetRole ( Role :: guests () -> toString ());
Authorization :: setRole ( Role :: user ( $user -> getId ()) -> toString ());
Authorization :: setRole ( Role :: users () -> toString ());
2020-11-21 10:02:26 +13:00
2022-12-21 05:11:30 +13:00
$queueForEvents -> setParam ( 'userId' , $user -> getId ());
2022-04-04 18:30:07 +12:00
2022-09-07 23:02:36 +12:00
$response
-> setStatusCode ( Response :: STATUS_CODE_CREATED )
2022-09-07 23:07:40 +12:00
-> dynamic ( $user , Response :: MODEL_ACCOUNT );
2020-12-27 03:31:53 +13:00
});
2020-01-05 04:45:28 +13:00
2022-06-14 20:17:50 +12:00
App :: post ( '/v1/account/sessions/email' )
2022-07-08 10:23:52 +12:00
-> alias ( '/v1/account/sessions' )
2024-01-13 06:39:44 +13:00
-> desc ( 'Create email password session' )
2022-12-11 21:33:52 +13:00
-> groups ([ 'api' , 'account' , 'auth' , 'session' ])
2022-04-04 18:30:07 +12:00
-> label ( 'event' , 'users.[userId].sessions.[sessionId].create' )
2024-01-18 00:17:03 +13:00
-> label ( 'scope' , 'sessions.write' )
2021-03-01 10:22:03 +13:00
-> label ( 'auth.type' , 'emailPassword' )
2022-09-05 20:00:08 +12:00
-> label ( 'audits.event' , 'session.create' )
2022-08-13 01:21:32 +12:00
-> label ( 'audits.resource' , 'user/{response.userId}' )
-> label ( 'audits.userId' , '{response.userId}' )
2021-04-16 19:22:17 +12:00
-> label ( 'sdk.auth' , [])
2020-01-05 04:45:28 +13:00
-> label ( 'sdk.namespace' , 'account' )
2023-12-22 22:38:52 +13:00
-> label ( 'sdk.method' , [ 'createEmailPasswordSession' , 'createEmailSession' ])
2024-01-16 23:33:54 +13:00
-> label ( 'sdk.description' , '/docs/references/account/create-session-email-password.md' )
2020-11-12 10:02:24 +13:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_CREATED )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
-> label ( 'sdk.response.model' , Response :: MODEL_SESSION )
2020-01-05 04:45:28 +13:00
-> label ( 'abuse-limit' , 10 )
-> label ( 'abuse-key' , 'url:{url},email:{param-email}' )
2020-09-11 02:40:14 +12:00
-> param ( 'email' , '' , new Email (), 'User email.' )
2021-11-26 09:07:54 +13:00
-> param ( 'password' , '' , new Password (), 'User password. Must be at least 8 chars.' )
2020-12-27 03:31:53 +13:00
-> inject ( 'request' )
-> inject ( 'response' )
2023-07-07 12:12:39 +12:00
-> inject ( 'user' )
2021-12-28 01:45:23 +13:00
-> inject ( 'dbForProject' )
2022-11-01 03:54:15 +13:00
-> inject ( 'project' )
2020-12-27 03:31:53 +13:00
-> inject ( 'locale' )
-> inject ( 'geodb' )
2022-12-21 05:11:30 +13:00
-> inject ( 'queueForEvents' )
2024-01-06 00:31:38 +13:00
-> inject ( 'hooks' )
-> action ( function ( string $email , string $password , Request $request , Response $response , Document $user , Database $dbForProject , Document $project , Locale $locale , Reader $geodb , Event $queueForEvents , Hooks $hooks ) {
2020-06-30 09:43:34 +12:00
2021-06-04 01:03:51 +12:00
$email = \strtolower ( $email );
2020-06-30 23:09:28 +12:00
$protocol = $request -> getProtocol ();
2021-08-05 17:06:38 +12:00
2022-05-13 04:25:36 +12:00
$profile = $dbForProject -> findOne ( 'users' , [
2022-08-12 11:53:52 +12:00
Query :: equal ( 'email' , [ $email ]),
]);
2020-06-30 09:43:34 +12:00
2023-05-26 09:06:08 +12:00
if ( ! $profile || empty ( $profile -> getAttribute ( 'passwordUpdate' )) || ! Auth :: passwordVerify ( $password , $profile -> getAttribute ( 'password' ), $profile -> getAttribute ( 'hash' ), $profile -> getAttribute ( 'hashOptions' ))) {
2022-08-15 04:23:30 +12:00
throw new Exception ( Exception :: USER_INVALID_CREDENTIALS );
2020-06-30 09:43:34 +12:00
}
2020-01-04 10:00:53 +13:00
2021-07-14 23:02:12 +12:00
if ( false === $profile -> getAttribute ( 'status' )) { // Account is blocked
2022-08-15 19:13:24 +12:00
throw new Exception ( Exception :: USER_BLOCKED ); // User is in status blocked
2020-12-28 00:57:42 +13:00
}
2023-10-13 02:38:32 +13:00
$roles = Authorization :: getRoles ();
$isPrivilegedUser = Auth :: isPrivilegedUser ( $roles );
$isAppUser = Auth :: isAppUser ( $roles );
2023-07-07 12:12:39 +12:00
$user -> setAttributes ( $profile -> getArrayCopy ());
2024-01-06 00:31:38 +13:00
$hooks -> trigger ( 'passwordValidator' , [ $dbForProject , $project , $password , & $user , false ]);
2022-11-01 03:54:15 +13:00
2022-11-14 22:42:18 +13:00
$duration = $project -> getAttribute ( 'auths' , [])[ 'duration' ] ? ? Auth :: TOKEN_EXPIRATION_LOGIN_LONG ;
2021-02-15 06:28:54 +13:00
$detector = new Detector ( $request -> getUserAgent ( 'UNKNOWN' ));
$record = $geodb -> get ( $request -> getIP ());
2024-01-18 00:03:04 +13:00
$secret = Auth :: tokenGenerator ( Auth :: TOKEN_LENGTH_SESSION );
2021-02-15 06:28:54 +13:00
$session = new Document ( array_merge (
[
2022-08-15 02:22:38 +12:00
'$id' => ID :: unique (),
2023-07-07 12:12:39 +12:00
'userId' => $user -> getId (),
'userInternalId' => $user -> getInternalId (),
2021-02-20 01:12:47 +13:00
'provider' => Auth :: SESSION_PROVIDER_EMAIL ,
2021-02-19 23:02:02 +13:00
'providerUid' => $email ,
2021-02-15 06:28:54 +13:00
'secret' => Auth :: hash ( $secret ), // One way hash encryption to protect DB leak
'userAgent' => $request -> getUserAgent ( 'UNKNOWN' ),
'ip' => $request -> getIP (),
'countryCode' => ( $record ) ? \strtolower ( $record [ 'country' ][ 'iso_code' ]) : '--' ,
2024-01-16 02:43:21 +13:00
'expire' => DateTime :: addSeconds ( new \DateTime (), $duration )
2022-05-24 02:54:50 +12:00
],
$detector -> getOS (),
$detector -> getClient (),
$detector -> getDevice ()
2021-02-15 06:28:54 +13:00
));
2020-10-31 08:53:27 +13:00
2023-07-07 12:12:39 +12:00
Authorization :: setRole ( Role :: user ( $user -> getId ()) -> toString ());
2020-01-04 10:00:53 +13:00
2022-05-06 20:58:36 +12:00
// Re-hash if not using recommended algo
2023-07-07 12:12:39 +12:00
if ( $user -> getAttribute ( 'hash' ) !== Auth :: DEFAULT_ALGO ) {
$user
2022-05-06 20:58:36 +12:00
-> setAttribute ( 'password' , Auth :: passwordHash ( $password , Auth :: DEFAULT_ALGO , Auth :: DEFAULT_ALGO_OPTIONS ))
-> setAttribute ( 'hash' , Auth :: DEFAULT_ALGO )
-> setAttribute ( 'hashOptions' , Auth :: DEFAULT_ALGO_OPTIONS );
2023-07-07 12:12:39 +12:00
$dbForProject -> updateDocument ( 'users' , $user -> getId (), $user );
2022-05-06 20:58:36 +12:00
}
2023-12-15 02:32:06 +13:00
$dbForProject -> purgeCachedDocument ( 'users' , $user -> getId ());
2020-01-05 04:45:28 +13:00
2022-08-02 21:21:53 +12:00
$session = $dbForProject -> createDocument ( 'sessions' , $session -> setAttribute ( '$permissions' , [
2023-07-07 12:12:39 +12:00
Permission :: read ( Role :: user ( $user -> getId ())),
Permission :: update ( Role :: user ( $user -> getId ())),
Permission :: delete ( Role :: user ( $user -> getId ())),
2022-08-02 21:21:53 +12:00
]));
2020-01-12 02:58:02 +13:00
2020-06-30 09:43:34 +12:00
if ( ! Config :: getParam ( 'domainVerification' )) {
2020-01-04 10:00:53 +13:00
$response
2023-07-07 12:12:39 +12:00
-> addHeader ( 'X-Fallback-Cookies' , \json_encode ([ Auth :: $cookieName => Auth :: encodeSession ( $user -> getId (), $secret )]))
2020-01-12 02:58:02 +13:00
;
2020-01-04 10:00:53 +13:00
}
2021-08-05 17:06:38 +12:00
2024-01-18 02:20:47 +13:00
$expire = DateTime :: formatTz ( DateTime :: addSeconds ( new \DateTime (), $duration ));
2020-06-30 09:43:34 +12:00
$response
2023-07-07 12:12:39 +12:00
-> addCookie ( Auth :: $cookieName . '_legacy' , Auth :: encodeSession ( $user -> getId (), $secret ), ( new \DateTime ( $expire )) -> getTimestamp (), '/' , Config :: getParam ( 'cookieDomain' ), ( 'https' == $protocol ), true , null )
-> addCookie ( Auth :: $cookieName , Auth :: encodeSession ( $user -> getId (), $secret ), ( new \DateTime ( $expire )) -> getTimestamp (), '/' , Config :: getParam ( 'cookieDomain' ), ( 'https' == $protocol ), true , Config :: getParam ( 'cookieSamesite' ))
2020-06-30 09:43:34 +12:00
-> setStatusCode ( Response :: STATUS_CODE_CREATED )
2020-07-03 09:48:02 +12:00
;
2020-10-31 08:53:27 +13:00
2022-05-24 02:54:50 +12:00
$countryName = $locale -> getText ( 'countries.' . strtolower ( $session -> getAttribute ( 'countryCode' )), $locale -> getText ( 'locale.country.unknown' ));
2021-06-17 21:33:57 +12:00
2020-10-31 08:53:27 +13:00
$session
-> setAttribute ( 'current' , true )
2021-06-17 21:33:57 +12:00
-> setAttribute ( 'countryName' , $countryName )
2023-12-20 04:45:44 +13:00
-> setAttribute ( 'secret' , ( $isPrivilegedUser || $isAppUser ) ? Auth :: encodeSession ( $user -> getId (), $secret ) : '' )
2020-10-31 08:53:27 +13:00
;
2021-08-05 17:06:38 +12:00
2022-12-21 05:11:30 +13:00
$queueForEvents
2023-07-07 12:12:39 +12:00
-> setParam ( 'userId' , $user -> getId ())
2022-04-04 18:30:07 +12:00
-> setParam ( 'sessionId' , $session -> getId ())
;
2021-07-26 02:47:18 +12:00
$response -> dynamic ( $session , Response :: MODEL_SESSION );
2020-12-27 03:31:53 +13:00
});
2020-01-04 10:00:53 +13:00
2020-06-29 05:31:21 +12:00
App :: get ( '/v1/account/sessions/oauth2/:provider' )
2023-08-02 03:26:48 +12:00
-> desc ( 'Create OAuth2 session' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2021-08-05 17:06:38 +12:00
-> label ( 'error' , __DIR__ . '/../../views/general/error.phtml' )
2024-01-18 00:17:03 +13:00
-> label ( 'scope' , 'sessions.write' )
2021-04-16 19:22:17 +12:00
-> label ( 'sdk.auth' , [])
2024-01-13 23:09:02 +13:00
-> label ( 'sdk.hideServer' , true )
2020-01-06 00:29:42 +13:00
-> label ( 'sdk.namespace' , 'account' )
2020-02-17 00:41:03 +13:00
-> label ( 'sdk.method' , 'createOAuth2Session' )
-> label ( 'sdk.description' , '/docs/references/account/create-session-oauth2.md' )
2021-03-05 18:30:34 +13:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_MOVED_PERMANENTLY )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_HTML )
2020-04-11 06:59:14 +12:00
-> label ( 'sdk.methodType' , 'webAuth' )
2020-01-06 00:29:42 +13:00
-> label ( 'abuse-limit' , 50 )
-> label ( 'abuse-key' , 'ip:{ip}' )
2023-10-26 06:33:23 +13:00
-> param ( 'provider' , '' , new WhiteList ( \array_keys ( Config :: getParam ( 'oAuthProviders' )), true ), 'OAuth2 Provider. Currently, supported providers are: ' . \implode ( ', ' , \array_keys ( \array_filter ( Config :: getParam ( 'oAuthProviders' ), fn ( $node ) => ( ! $node [ 'mock' ])))) . '.' )
2023-08-23 08:30:00 +12:00
-> param ( 'success' , '' , fn ( $clients ) => new Host ( $clients ), 'URL to redirect back to your app after a successful login attempt. Only URLs from hostnames in your project\'s platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API.' , true , [ 'clients' ])
-> param ( 'failure' , '' , fn ( $clients ) => new Host ( $clients ), 'URL to redirect back to your app after a failed login attempt. Only URLs from hostnames in your project\'s platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API.' , true , [ 'clients' ])
2024-01-13 01:12:28 +13:00
-> param ( 'token' , false , new Boolean ( true ), 'Include token credentials in the final redirect, useful for server-side integrations, or when cookies are not available.' , true )
2022-06-16 00:07:14 +12:00
-> param ( 'scopes' , [], new ArrayList ( new Text ( APP_LIMIT_ARRAY_ELEMENT_SIZE ), APP_LIMIT_ARRAY_PARAMS_SIZE ), 'A list of custom OAuth2 scopes. Check each provider internal docs for a list of supported scopes. Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' scopes are allowed, each ' . APP_LIMIT_ARRAY_ELEMENT_SIZE . ' characters long.' , true )
2020-12-27 03:31:53 +13:00
-> inject ( 'request' )
-> inject ( 'response' )
-> inject ( 'project' )
2024-01-13 01:14:28 +13:00
-> action ( function ( string $provider , string $success , string $failure , mixed $token , array $scopes , Request $request , Response $response , Document $project ) use ( $oauthDefaultSuccess , $oauthDefaultFailure ) {
2024-01-13 01:12:28 +13:00
$token = in_array ( $token , [ 'true' , true ], true );
2020-01-06 00:29:42 +13:00
2020-06-30 23:09:28 +12:00
$protocol = $request -> getProtocol ();
2022-11-19 02:13:33 +13:00
2022-05-24 02:54:50 +12:00
$callback = $protocol . '://' . $request -> getHostname () . '/v1/account/sessions/oauth2/callback/' . $provider . '/' . $project -> getId ();
2023-10-26 06:33:23 +13:00
$providerEnabled = $project -> getAttribute ( 'oAuthProviders' , [])[ $provider . 'Enabled' ] ? ? false ;
2023-01-09 23:44:28 +13:00
2023-01-09 23:35:03 +13:00
if ( ! $providerEnabled ) {
throw new Exception ( Exception :: PROJECT_PROVIDER_DISABLED , 'This provider is disabled. Please enable the provider from your ' . APP_NAME . ' console to continue.' );
}
2023-01-09 23:44:28 +13:00
2023-10-26 06:33:23 +13:00
$appId = $project -> getAttribute ( 'oAuthProviders' , [])[ $provider . 'Appid' ] ? ? '' ;
$appSecret = $project -> getAttribute ( 'oAuthProviders' , [])[ $provider . 'Secret' ] ? ? '{}' ;
2020-01-06 00:29:42 +13:00
2020-06-30 09:43:34 +12:00
if ( ! empty ( $appSecret ) && isset ( $appSecret [ 'version' ])) {
2021-08-05 17:06:38 +12:00
$key = App :: getEnv ( '_APP_OPENSSL_KEY_V' . $appSecret [ 'version' ]);
2020-06-30 09:43:34 +12:00
$appSecret = OpenSSL :: decrypt ( $appSecret [ 'data' ], $appSecret [ 'method' ], $key , 0 , \hex2bin ( $appSecret [ 'iv' ]), \hex2bin ( $appSecret [ 'tag' ]));
}
2020-01-06 00:29:42 +13:00
2020-06-30 09:43:34 +12:00
if ( empty ( $appId ) || empty ( $appSecret )) {
2022-08-15 19:13:24 +12:00
throw new Exception ( Exception :: PROJECT_PROVIDER_DISABLED , 'This provider is disabled. Please configure the provider app ID and app secret key from your ' . APP_NAME . ' console to continue.' );
2020-06-30 09:43:34 +12:00
}
2020-01-06 00:29:42 +13:00
2022-05-24 02:54:50 +12:00
$className = 'Appwrite\\Auth\\OAuth2\\' . \ucfirst ( $provider );
2020-06-30 09:43:34 +12:00
2021-08-06 22:48:50 +12:00
if ( ! \class_exists ( $className )) {
2022-08-15 19:13:24 +12:00
throw new Exception ( Exception :: PROJECT_PROVIDER_UNSUPPORTED );
2020-01-06 00:29:42 +13:00
}
2020-06-30 09:43:34 +12:00
2022-05-24 02:54:50 +12:00
if ( empty ( $success )) {
2021-08-31 19:04:17 +12:00
$success = $protocol . '://' . $request -> getHostname () . $oauthDefaultSuccess ;
}
2022-05-24 02:54:50 +12:00
if ( empty ( $failure )) {
2021-08-31 19:04:17 +12:00
$failure = $protocol . '://' . $request -> getHostname () . $oauthDefaultFailure ;
}
2024-01-10 05:38:29 +13:00
$oauth2 = new $className ( $appId , $appSecret , $callback , [
'success' => $success ,
'failure' => $failure ,
'token' => $token ,
], $scopes );
2020-06-30 09:43:34 +12:00
$response
-> addHeader ( 'Cache-Control' , 'no-store, no-cache, must-revalidate, max-age=0' )
-> addHeader ( 'Pragma' , 'no-cache' )
-> redirect ( $oauth2 -> getLoginURL ());
2020-12-27 03:31:53 +13:00
});
2020-01-06 00:29:42 +13:00
2020-06-29 05:31:21 +12:00
App :: get ( '/v1/account/sessions/oauth2/callback/:provider/:projectId' )
2023-08-02 03:26:48 +12:00
-> desc ( 'OAuth2 callback' )
2023-07-25 13:38:54 +12:00
-> groups ([ 'account' ])
2021-08-05 17:06:38 +12:00
-> label ( 'error' , __DIR__ . '/../../views/general/error.phtml' )
2020-01-06 00:29:42 +13:00
-> label ( 'scope' , 'public' )
-> label ( 'docs' , false )
2021-12-11 01:27:11 +13:00
-> param ( 'projectId' , '' , new Text ( 1024 ), 'Project ID.' )
2023-10-26 06:33:23 +13:00
-> param ( 'provider' , '' , new WhiteList ( \array_keys ( Config :: getParam ( 'oAuthProviders' )), true ), 'OAuth2 provider.' )
2023-08-23 08:11:33 +12:00
-> param ( 'code' , '' , new Text ( 2048 , 0 ), 'OAuth2 code. This is a temporary code that the will be later exchanged for an access token.' , true )
2020-09-11 02:40:14 +12:00
-> param ( 'state' , '' , new Text ( 2048 ), 'Login state params.' , true )
2023-07-28 12:12:15 +12:00
-> param ( 'error' , '' , new Text ( 2048 , 0 ), 'Error code returned from the OAuth2 provider.' , true )
-> param ( 'error_description' , '' , new Text ( 2048 , 0 ), 'Human-readable text providing additional information about the error returned from the OAuth2 provider.' , true )
2020-12-27 03:31:53 +13:00
-> inject ( 'request' )
-> inject ( 'response' )
2023-07-28 12:12:15 +12:00
-> action ( function ( string $projectId , string $provider , string $code , string $state , string $error , string $error_description , Request $request , Response $response ) {
2020-06-30 23:09:28 +12:00
2020-07-03 09:48:02 +12:00
$domain = $request -> getHostname ();
2020-06-30 23:09:28 +12:00
$protocol = $request -> getProtocol ();
2021-08-05 17:06:38 +12:00
2020-06-30 09:43:34 +12:00
$response
-> addHeader ( 'Cache-Control' , 'no-store, no-cache, must-revalidate, max-age=0' )
-> addHeader ( 'Pragma' , 'no-cache' )
2021-08-05 17:06:38 +12:00
-> redirect ( $protocol . '://' . $domain . '/v1/account/sessions/oauth2/' . $provider . '/redirect?'
2023-07-28 12:12:15 +12:00
. \http_build_query ([
'project' => $projectId ,
'code' => $code ,
'state' => $state ,
'error' => $error ,
'error_description' => $error_description
]));
2020-12-27 03:31:53 +13:00
});
2020-01-06 00:29:42 +13:00
2020-06-29 05:31:21 +12:00
App :: post ( '/v1/account/sessions/oauth2/callback/:provider/:projectId' )
2023-08-02 03:26:48 +12:00
-> desc ( 'OAuth2 callback' )
2023-07-25 13:38:54 +12:00
-> groups ([ 'account' ])
2021-08-05 17:06:38 +12:00
-> label ( 'error' , __DIR__ . '/../../views/general/error.phtml' )
2020-05-30 00:02:53 +12:00
-> label ( 'scope' , 'public' )
-> label ( 'origin' , '*' )
-> label ( 'docs' , false )
2021-12-11 01:27:11 +13:00
-> param ( 'projectId' , '' , new Text ( 1024 ), 'Project ID.' )
2023-10-26 06:33:23 +13:00
-> param ( 'provider' , '' , new WhiteList ( \array_keys ( Config :: getParam ( 'oAuthProviders' )), true ), 'OAuth2 provider.' )
2023-08-23 08:11:33 +12:00
-> param ( 'code' , '' , new Text ( 2048 , 0 ), 'OAuth2 code. This is a temporary code that the will be later exchanged for an access token.' , true )
2020-09-11 02:40:14 +12:00
-> param ( 'state' , '' , new Text ( 2048 ), 'Login state params.' , true )
2023-07-28 12:12:15 +12:00
-> param ( 'error' , '' , new Text ( 2048 , 0 ), 'Error code returned from the OAuth2 provider.' , true )
-> param ( 'error_description' , '' , new Text ( 2048 , 0 ), 'Human-readable text providing additional information about the error returned from the OAuth2 provider.' , true )
2020-12-27 03:31:53 +13:00
-> inject ( 'request' )
-> inject ( 'response' )
2023-07-28 12:12:15 +12:00
-> action ( function ( string $projectId , string $provider , string $code , string $state , string $error , string $error_description , Request $request , Response $response ) {
2020-06-30 23:09:28 +12:00
2020-07-03 09:48:02 +12:00
$domain = $request -> getHostname ();
2020-06-30 23:09:28 +12:00
$protocol = $request -> getProtocol ();
2021-08-05 17:06:38 +12:00
2020-06-30 09:43:34 +12:00
$response
-> addHeader ( 'Cache-Control' , 'no-store, no-cache, must-revalidate, max-age=0' )
-> addHeader ( 'Pragma' , 'no-cache' )
2021-08-05 17:06:38 +12:00
-> redirect ( $protocol . '://' . $domain . '/v1/account/sessions/oauth2/' . $provider . '/redirect?'
2023-07-28 12:12:15 +12:00
. \http_build_query ([
'project' => $projectId ,
'code' => $code ,
'state' => $state ,
'error' => $error ,
'error_description' => $error_description
]));
2020-12-27 03:31:53 +13:00
});
2020-05-30 00:02:53 +12:00
2020-06-29 05:31:21 +12:00
App :: get ( '/v1/account/sessions/oauth2/:provider/redirect' )
2023-08-02 03:26:48 +12:00
-> desc ( 'OAuth2 redirect' )
2022-12-11 21:33:52 +13:00
-> groups ([ 'api' , 'account' , 'session' ])
2021-08-05 17:06:38 +12:00
-> label ( 'error' , __DIR__ . '/../../views/general/error.phtml' )
2022-04-04 18:30:07 +12:00
-> label ( 'event' , 'users.[userId].sessions.[sessionId].create' )
2020-01-06 00:29:42 +13:00
-> label ( 'scope' , 'public' )
2022-09-05 20:00:08 +12:00
-> label ( 'audits.event' , 'session.create' )
2022-08-16 05:04:23 +12:00
-> label ( 'audits.resource' , 'user/{user.$id}' )
2023-02-05 20:02:56 +13:00
-> label ( 'audits.userId' , '{user.$id}' )
2020-01-06 00:29:42 +13:00
-> label ( 'abuse-limit' , 50 )
-> label ( 'abuse-key' , 'ip:{ip}' )
-> label ( 'docs' , false )
2023-08-21 00:29:43 +12:00
-> label ( 'usage.metric' , 'sessions.{scope}.requests.create' )
-> label ( 'usage.params' , [ 'provider:{request.provider}' ])
2023-10-26 06:33:23 +13:00
-> param ( 'provider' , '' , new WhiteList ( \array_keys ( Config :: getParam ( 'oAuthProviders' )), true ), 'OAuth2 provider.' )
2023-08-23 08:11:33 +12:00
-> param ( 'code' , '' , new Text ( 2048 , 0 ), 'OAuth2 code. This is a temporary code that the will be later exchanged for an access token.' , true )
2020-09-11 02:40:14 +12:00
-> param ( 'state' , '' , new Text ( 2048 ), 'OAuth2 state params.' , true )
2023-07-28 12:12:15 +12:00
-> param ( 'error' , '' , new Text ( 2048 , 0 ), 'Error code returned from the OAuth2 provider.' , true )
-> param ( 'error_description' , '' , new Text ( 2048 , 0 ), 'Human-readable text providing additional information about the error returned from the OAuth2 provider.' , true )
2020-12-27 03:31:53 +13:00
-> inject ( 'request' )
-> inject ( 'response' )
-> inject ( 'project' )
-> inject ( 'user' )
2021-12-28 01:45:23 +13:00
-> inject ( 'dbForProject' )
2020-12-27 03:31:53 +13:00
-> inject ( 'geodb' )
2022-12-21 05:11:30 +13:00
-> inject ( 'queueForEvents' )
2023-10-04 05:50:48 +13:00
-> action ( function ( string $provider , string $code , string $state , string $error , string $error_description , Request $request , Response $response , Document $project , Document $user , Database $dbForProject , Reader $geodb , Event $queueForEvents ) use ( $oauthDefaultSuccess ) {
2021-08-05 17:06:38 +12:00
2020-06-30 23:09:28 +12:00
$protocol = $request -> getProtocol ();
2021-08-05 17:06:38 +12:00
$callback = $protocol . '://' . $request -> getHostname () . '/v1/account/sessions/oauth2/callback/' . $provider . '/' . $project -> getId ();
2020-06-30 09:43:34 +12:00
$defaultState = [ 'success' => $project -> getAttribute ( 'url' , '' ), 'failure' => '' ];
$validateURL = new URL ();
2023-10-26 06:33:23 +13:00
$appId = $project -> getAttribute ( 'oAuthProviders' , [])[ $provider . 'Appid' ] ? ? '' ;
$appSecret = $project -> getAttribute ( 'oAuthProviders' , [])[ $provider . 'Secret' ] ? ? '{}' ;
$providerEnabled = $project -> getAttribute ( 'oAuthProviders' , [])[ $provider . 'Enabled' ] ? ? false ;
2023-01-10 17:52:21 +13:00
2021-08-07 00:30:56 +12:00
$className = 'Appwrite\\Auth\\OAuth2\\' . \ucfirst ( $provider );
2020-01-06 00:29:42 +13:00
2021-08-06 22:48:50 +12:00
if ( ! \class_exists ( $className )) {
2022-08-15 19:13:24 +12:00
throw new Exception ( Exception :: PROJECT_PROVIDER_UNSUPPORTED );
2020-06-30 09:43:34 +12:00
}
2020-01-06 00:29:42 +13:00
2023-10-26 06:33:23 +13:00
$providers = Config :: getParam ( 'oAuthProviders' );
2023-07-15 12:28:45 +12:00
$providerName = $providers [ $provider ][ 'name' ] ? ? '' ;
/** @var Appwrite\Auth\OAuth2 $oauth2 */
2021-08-06 22:48:50 +12:00
$oauth2 = new $className ( $appId , $appSecret , $callback );
2020-01-06 00:29:42 +13:00
2020-06-30 09:43:34 +12:00
if ( ! empty ( $state )) {
try {
$state = \array_merge ( $defaultState , $oauth2 -> parseState ( $state ));
2023-07-15 12:28:45 +12:00
} catch ( \Exception $exception ) {
2022-08-15 19:13:24 +12:00
throw new Exception ( Exception :: GENERAL_SERVER_ERROR , 'Failed to parse login state params as passed from OAuth2 provider' );
2020-01-06 00:29:42 +13:00
}
2020-06-30 09:43:34 +12:00
} else {
$state = $defaultState ;
}
2020-01-06 00:29:42 +13:00
2020-06-30 09:43:34 +12:00
if ( ! $validateURL -> isValid ( $state [ 'success' ])) {
2022-08-15 19:13:24 +12:00
throw new Exception ( Exception :: PROJECT_INVALID_SUCCESS_URL );
2020-06-30 09:43:34 +12:00
}
2020-01-06 00:29:42 +13:00
2020-06-30 09:43:34 +12:00
if ( ! empty ( $state [ 'failure' ]) && ! $validateURL -> isValid ( $state [ 'failure' ])) {
2022-08-15 19:13:24 +12:00
throw new Exception ( Exception :: PROJECT_INVALID_FAILURE_URL );
2020-06-30 09:43:34 +12:00
}
2023-07-15 12:28:45 +12:00
$failure = [];
if ( ! empty ( $state [ 'failure' ])) {
$failure = URLParser :: parse ( $state [ 'failure' ]);
}
$failureRedirect = ( function ( string $type , ? string $message = null , ? int $code = null ) use ( $failure , $response ) {
$exception = new Exception ( $type , $message , $code );
if ( ! empty ( $failure )) {
$query = URLParser :: parseQuery ( $failure [ 'query' ]);
$query [ 'error' ] = json_encode ([
'message' => $exception -> getMessage (),
'type' => $exception -> getType (),
'code' => ! \is_null ( $code ) ? $code : $exception -> getCode (),
]);
$failure [ 'query' ] = URLParser :: unparseQuery ( $query );
$response -> redirect ( URLParser :: unparse ( $failure ), 301 );
}
2021-08-05 17:06:38 +12:00
2023-07-15 12:28:45 +12:00
throw $exception ;
});
2020-01-06 00:29:42 +13:00
2023-07-15 12:28:45 +12:00
if ( ! $providerEnabled ) {
$failureRedirect ( Exception :: PROJECT_PROVIDER_DISABLED , 'This provider is disabled. Please enable the provider from your ' . APP_NAME . ' console to continue.' );
}
2020-01-06 00:29:42 +13:00
2023-07-28 12:12:15 +12:00
if ( ! empty ( $error )) {
$message = 'The ' . $providerName . ' OAuth2 provider returned an error: ' . $error ;
if ( ! empty ( $error_description )) {
$message .= ': ' . $error_description ;
2020-01-06 00:29:42 +13:00
}
2023-07-28 12:12:15 +12:00
$failureRedirect ( Exception :: USER_OAUTH2_PROVIDER_ERROR , $message );
}
2020-01-06 00:29:42 +13:00
2023-07-28 12:12:15 +12:00
if ( empty ( $code )) {
$failureRedirect ( Exception :: USER_OAUTH2_PROVIDER_ERROR , 'Missing OAuth2 code. Please contact the Appwrite team for additional support.' );
2020-06-30 09:43:34 +12:00
}
2020-01-06 00:29:42 +13:00
2023-07-15 12:28:45 +12:00
if ( ! empty ( $appSecret ) && isset ( $appSecret [ 'version' ])) {
$key = App :: getEnv ( '_APP_OPENSSL_KEY_V' . $appSecret [ 'version' ]);
$appSecret = OpenSSL :: decrypt ( $appSecret [ 'data' ], $appSecret [ 'method' ], $key , 0 , \hex2bin ( $appSecret [ 'iv' ]), \hex2bin ( $appSecret [ 'tag' ]));
2020-06-30 09:43:34 +12:00
}
2021-08-05 17:06:38 +12:00
2023-07-15 12:28:45 +12:00
$accessToken = '' ;
$refreshToken = '' ;
$accessTokenExpiry = 0 ;
2020-01-06 00:29:42 +13:00
2023-07-15 12:28:45 +12:00
try {
$accessToken = $oauth2 -> getAccessToken ( $code );
$refreshToken = $oauth2 -> getRefreshToken ( $code );
$accessTokenExpiry = $oauth2 -> getAccessTokenExpiry ( $code );
} catch ( OAuth2Exception $ex ) {
$failureRedirect (
$ex -> getType (),
'Failed to obtain access token. The ' . $providerName . ' OAuth2 provider returned an error: ' . $ex -> getMessage (),
$ex -> getCode (),
);
}
2020-01-06 00:29:42 +13:00
2023-07-15 12:28:45 +12:00
$oauth2ID = $oauth2 -> getUserID ( $accessToken );
if ( empty ( $oauth2ID )) {
$failureRedirect ( Exception :: USER_MISSING_ID );
2020-06-30 09:43:34 +12:00
}
2020-01-06 00:29:42 +13:00
2023-05-18 13:11:45 +12:00
$name = $oauth2 -> getUserName ( $accessToken );
$email = $oauth2 -> getUserEmail ( $accessToken );
// Check if this identity is connected to a different user
if ( ! $user -> isEmpty ()) {
$userId = $user -> getId ();
2023-12-14 07:45:05 +13:00
$identityWithMatchingEmail = $dbForProject -> findOne ( 'identities' , [
2023-05-18 13:11:45 +12:00
Query :: equal ( 'providerEmail' , [ $email ]),
Query :: notEqual ( 'userId' , $userId ),
]);
2023-12-14 07:45:05 +13:00
if ( ! empty ( $identityWithMatchingEmail )) {
throw new Exception ( Exception :: USER_ALREADY_EXISTS );
}
$userWithMatchingEmail = $dbForProject -> find ( 'users' , [
Query :: equal ( 'email' , [ $email ]),
Query :: notEqual ( '$id' , $userId ),
]);
if ( ! empty ( $userWithMatchingEmail )) {
2023-05-18 13:11:45 +12:00
throw new Exception ( Exception :: USER_ALREADY_EXISTS );
}
}
2021-05-07 10:31:05 +12:00
$sessions = $user -> getAttribute ( 'sessions' , []);
2024-01-16 03:37:47 +13:00
$current = Auth :: sessionVerify ( $sessions , Auth :: $secret );
2020-01-06 00:29:42 +13:00
2021-08-05 17:06:38 +12:00
if ( $current ) { // Delete current session of new one.
2022-04-04 21:59:32 +12:00
$currentDocument = $dbForProject -> getDocument ( 'sessions' , $current );
2022-05-24 02:54:50 +12:00
if ( ! $currentDocument -> isEmpty ()) {
2022-04-04 21:59:32 +12:00
$dbForProject -> deleteDocument ( 'sessions' , $currentDocument -> getId ());
2023-12-15 02:32:06 +13:00
$dbForProject -> purgeCachedDocument ( 'users' , $user -> getId ());
2021-05-07 10:31:05 +12:00
}
2020-06-30 09:43:34 +12:00
}
2020-01-06 00:29:42 +13:00
2023-07-07 12:12:39 +12:00
if ( $user -> isEmpty ()) {
$session = $dbForProject -> findOne ( 'sessions' , [ // Get user by provider id
Query :: equal ( 'provider' , [ $provider ]),
Query :: equal ( 'providerUid' , [ $oauth2ID ]),
]);
if ( $session !== false && ! $session -> isEmpty ()) {
$user -> setAttributes ( $dbForProject -> getDocument ( 'users' , $session -> getAttribute ( 'userId' )) -> getArrayCopy ());
}
}
2020-01-06 00:29:42 +13:00
2021-07-18 09:21:33 +12:00
if ( $user === false || $user -> isEmpty ()) { // No user logged in or with OAuth2 provider ID, create new one or connect with account with same email
2023-05-02 03:51:31 +12:00
if ( empty ( $email )) {
2023-05-02 01:54:33 +12:00
throw new Exception ( Exception :: USER_UNAUTHORIZED , 'OAuth provider failed to return email.' );
}
2022-05-16 21:34:00 +12:00
/**
* Is verified is not used yet , since we don ' t know after an accout is created anymore if it was verified or not .
*/
2022-05-08 03:43:55 +12:00
$isVerified = $oauth2 -> isEmailVerified ( $accessToken );
2020-01-06 00:29:42 +13:00
2023-07-07 12:12:39 +12:00
$userWithEmail = $dbForProject -> findOne ( 'users' , [
2022-08-12 11:53:52 +12:00
Query :: equal ( 'email' , [ $email ]),
]);
2023-07-07 12:12:39 +12:00
if ( $userWithEmail !== false && ! $userWithEmail -> isEmpty ()) {
$user -> setAttributes ( $userWithEmail -> getArrayCopy ());
}
2020-01-06 00:29:42 +13:00
2023-05-18 13:11:45 +12:00
// If user is not found, check if there is an identity with the same provider user ID
if ( $user === false || $user -> isEmpty ()) {
$identity = $dbForProject -> findOne ( 'identities' , [
Query :: equal ( 'provider' , [ $provider ]),
Query :: equal ( 'providerUid' , [ $oauth2ID ]),
]);
if ( $identity !== false && ! $identity -> isEmpty ()) {
$user = $dbForProject -> getDocument ( 'users' , $identity -> getAttribute ( 'userId' ));
}
}
if ( $user === false || $user -> isEmpty ()) { // Last option -> create the user
2021-08-06 20:34:17 +12:00
$limit = $project -> getAttribute ( 'auths' , [])[ 'limit' ] ? ? 0 ;
2021-08-05 17:06:38 +12:00
2021-03-01 07:36:13 +13:00
if ( $limit !== 0 ) {
2022-05-16 21:58:17 +12:00
$total = $dbForProject -> count ( 'users' , max : APP_LIMIT_USERS );
2021-07-18 09:21:33 +12:00
2022-02-27 22:57:09 +13:00
if ( $total >= $limit ) {
2023-07-15 12:28:45 +12:00
$failureRedirect ( Exception :: USER_COUNT_EXCEEDED );
2021-03-01 07:36:13 +13:00
}
}
2021-08-05 17:06:38 +12:00
2023-05-18 13:11:45 +12:00
// Makes sure this email is not already used in another identity
$identityWithMatchingEmail = $dbForProject -> findOne ( 'identities' , [
Query :: equal ( 'providerEmail' , [ $email ]),
]);
if ( $identityWithMatchingEmail !== false && ! $identityWithMatchingEmail -> isEmpty ()) {
throw new Exception ( Exception :: USER_EMAIL_ALREADY_EXISTS );
}
2022-12-18 17:38:27 +13:00
2020-06-30 09:43:34 +12:00
try {
2022-08-15 02:22:38 +12:00
$userId = ID :: unique ();
2023-07-07 12:12:39 +12:00
$user -> setAttributes ([
2022-08-15 02:22:38 +12:00
'$id' => $userId ,
2022-08-02 21:21:53 +12:00
'$permissions' => [
2022-08-14 17:21:11 +12:00
Permission :: read ( Role :: any ()),
2022-08-15 02:22:38 +12:00
Permission :: update ( Role :: user ( $userId )),
Permission :: delete ( Role :: user ( $userId )),
2022-08-02 21:21:53 +12:00
],
2020-06-30 09:43:34 +12:00
'email' => $email ,
2022-05-16 21:34:00 +12:00
'emailVerification' => true ,
2021-07-14 23:02:12 +12:00
'status' => true , // Email should already be authenticated by OAuth2 provider
2023-07-15 11:17:05 +12:00
'password' => null ,
2022-05-05 02:37:37 +12:00
'hash' => Auth :: DEFAULT_ALGO ,
'hashOptions' => Auth :: DEFAULT_ALGO_OPTIONS ,
2022-07-04 21:55:11 +12:00
'passwordUpdate' => null ,
2022-07-14 02:02:49 +12:00
'registration' => DateTime :: now (),
2020-06-30 09:43:34 +12:00
'reset' => false ,
'name' => $name ,
2021-12-28 23:48:50 +13:00
'prefs' => new \stdClass (),
2022-04-26 22:36:49 +12:00
'sessions' => null ,
2022-04-27 23:06:53 +12:00
'tokens' => null ,
2022-04-28 00:44:47 +12:00
'memberships' => null ,
2023-08-23 13:34:23 +12:00
'search' => implode ( ' ' , [ $userId , $email , $name ]),
'accessedAt' => DateTime :: now (),
2023-07-07 12:12:39 +12:00
]);
2023-09-14 07:18:50 +12:00
$user -> removeAttribute ( '$internalId' );
2023-11-15 08:54:55 +13:00
$userDoc = Authorization :: skip ( fn () => $dbForProject -> createDocument ( 'users' , $user ));
$dbForProject -> createDocument ( 'targets' , new Document ([
'$permissions' => [
Permission :: read ( Role :: any ()),
Permission :: update ( Role :: user ( $user -> getId ())),
Permission :: delete ( Role :: user ( $user -> getId ())),
],
'userId' => $userDoc -> getId (),
'userInternalId' => $userDoc -> getInternalId (),
2023-11-29 17:05:37 +13:00
'providerType' => MESSAGE_TYPE_EMAIL ,
2023-11-15 08:54:55 +13:00
'identifier' => $email ,
]));
2023-08-23 13:34:23 +12:00
} catch ( Duplicate ) {
2023-07-15 12:28:45 +12:00
$failureRedirect ( Exception :: USER_ALREADY_EXISTS );
2020-06-30 09:43:34 +12:00
}
2020-01-06 00:29:42 +13:00
}
2020-06-30 09:43:34 +12:00
}
2020-01-06 00:29:42 +13:00
2023-05-18 13:11:45 +12:00
Authorization :: setRole ( Role :: user ( $user -> getId ()) -> toString ());
Authorization :: setRole ( Role :: users () -> toString ());
2021-07-14 23:02:12 +12:00
if ( false === $user -> getAttribute ( 'status' )) { // Account is blocked
2023-07-15 12:28:45 +12:00
$failureRedirect ( Exception :: USER_BLOCKED ); // User is in status blocked
2020-12-28 00:57:42 +13:00
}
2023-05-18 13:11:45 +12:00
$identity = $dbForProject -> findOne ( 'identities' , [
Query :: equal ( 'userInternalId' , [ $user -> getInternalId ()]),
Query :: equal ( 'provider' , [ $provider ]),
Query :: equal ( 'providerUid' , [ $oauth2ID ]),
]);
if ( $identity === false || $identity -> isEmpty ()) {
// Before creating the identity, check if the email is already associated with another user
$userId = $user -> getId ();
$identitiesWithMatchingEmail = $dbForProject -> find ( 'identities' , [
Query :: equal ( 'providerEmail' , [ $email ]),
Query :: notEqual ( 'userId' , $user -> getId ()),
]);
if ( ! empty ( $identitiesWithMatchingEmail )) {
throw new Exception ( Exception :: USER_EMAIL_ALREADY_EXISTS );
}
$dbForProject -> createDocument ( 'identities' , new Document ([
'$id' => ID :: unique (),
'$permissions' => [
Permission :: read ( Role :: any ()),
Permission :: update ( Role :: user ( $userId )),
Permission :: delete ( Role :: user ( $userId )),
],
'userInternalId' => $user -> getInternalId (),
'userId' => $userId ,
'provider' => $provider ,
'providerUid' => $oauth2ID ,
'providerEmail' => $email ,
'providerAccessToken' => $accessToken ,
'providerRefreshToken' => $refreshToken ,
'providerAccessTokenExpiry' => DateTime :: addSeconds ( new \DateTime (), ( int ) $accessTokenExpiry ),
]));
} else {
$identity
-> setAttribute ( 'providerAccessToken' , $accessToken )
-> setAttribute ( 'providerRefreshToken' , $refreshToken )
-> setAttribute ( 'providerAccessTokenExpiry' , DateTime :: addSeconds ( new \DateTime (), ( int ) $accessTokenExpiry ));
$dbForProject -> updateDocument ( 'identities' , $identity -> getId (), $identity );
}
2023-06-23 12:46:09 +12:00
if ( empty ( $user -> getAttribute ( 'email' ))) {
$user -> setAttribute ( 'email' , $oauth2 -> getUserEmail ( $accessToken ));
}
2021-02-17 04:51:08 +13:00
2023-06-23 12:46:09 +12:00
if ( empty ( $user -> getAttribute ( 'name' ))) {
$user -> setAttribute ( 'name' , $oauth2 -> getUserName ( $accessToken ));
2021-02-17 04:51:08 +13:00
}
2024-01-10 05:38:29 +13:00
$user -> setAttribute ( 'status' , true );
2020-06-30 09:43:34 +12:00
2022-04-26 22:46:35 +12:00
$dbForProject -> updateDocument ( 'users' , $user -> getId (), $user );
2020-06-30 09:43:34 +12:00
2022-08-19 16:04:33 +12:00
Authorization :: setRole ( Role :: user ( $user -> getId ()) -> toString ());
2020-06-30 09:43:34 +12:00
2024-01-10 05:38:29 +13:00
$state [ 'success' ] = URLParser :: parse ( $state [ 'success' ]);
$query = URLParser :: parseQuery ( $state [ 'success' ][ 'query' ]);
2022-04-26 22:46:35 +12:00
2024-01-10 05:38:29 +13:00
$duration = $project -> getAttribute ( 'auths' , [])[ 'duration' ] ? ? Auth :: TOKEN_EXPIRATION_LOGIN_LONG ;
$expire = DateTime :: formatTz ( DateTime :: addSeconds ( new \DateTime (), $duration ));
2021-07-18 09:21:33 +12:00
2024-01-10 05:38:29 +13:00
// If the `token` param is set, we will return the token in the query string
if ( $state [ 'token' ]) {
2024-01-11 23:51:26 +13:00
$secret = Auth :: tokenGenerator ( Auth :: TOKEN_LENGTH_OAUTH2 );
2024-01-10 05:38:29 +13:00
$token = new Document ([
'$id' => ID :: unique (),
'userId' => $user -> getId (),
'userInternalId' => $user -> getInternalId (),
'type' => Auth :: TOKEN_TYPE_OAUTH2 ,
'secret' => Auth :: hash ( $secret ), // One way hash encryption to protect DB leak
'expire' => $expire ,
'userAgent' => $request -> getUserAgent ( 'UNKNOWN' ),
'ip' => $request -> getIP (),
]);
2020-06-30 09:43:34 +12:00
2024-01-10 05:38:29 +13:00
Authorization :: setRole ( Role :: user ( $user -> getId ()) -> toString ());
2022-11-04 04:03:39 +13:00
2024-01-10 05:38:29 +13:00
$token = $dbForProject -> createDocument ( 'tokens' , $token
-> setAttribute ( '$permissions' , [
Permission :: read ( Role :: user ( $user -> getId ())),
Permission :: update ( Role :: user ( $user -> getId ())),
Permission :: delete ( Role :: user ( $user -> getId ())),
]));
2022-04-04 18:30:07 +12:00
2024-01-10 05:38:29 +13:00
$queueForEvents
-> setEvent ( 'users.[userId].tokens.[tokenId].create' )
-> setParam ( 'userId' , $user -> getId ())
-> setParam ( 'tokenId' , $token -> getId ())
;
2021-08-05 17:06:38 +12:00
2024-01-10 05:38:29 +13:00
$query [ 'secret' ] = $secret ;
$query [ 'userId' ] = $user -> getId ();
2023-09-29 01:45:52 +13:00
2024-01-10 05:38:29 +13:00
// If the `token` param is not set, we persist the session in a cookie
} else {
$detector = new Detector ( $request -> getUserAgent ( 'UNKNOWN' ));
$record = $geodb -> get ( $request -> getIP ());
2024-01-18 00:03:04 +13:00
$secret = Auth :: tokenGenerator ( Auth :: TOKEN_LENGTH_SESSION );
2024-01-10 05:41:42 +13:00
2024-01-10 05:38:29 +13:00
$session = new Document ( array_merge ([
'$id' => ID :: unique (),
'userId' => $user -> getId (),
'userInternalId' => $user -> getInternalId (),
'provider' => $provider ,
'providerUid' => $oauth2ID ,
'providerAccessToken' => $accessToken ,
'providerRefreshToken' => $refreshToken ,
'providerAccessTokenExpiry' => DateTime :: addSeconds ( new \DateTime (), ( int ) $accessTokenExpiry ),
'secret' => Auth :: hash ( $secret ), // One way hash encryption to protect DB leak
'userAgent' => $request -> getUserAgent ( 'UNKNOWN' ),
'ip' => $request -> getIP (),
'countryCode' => ( $record ) ? \strtolower ( $record [ 'country' ][ 'iso_code' ]) : '--' ,
2024-01-23 00:20:33 +13:00
'expire' => DateTime :: addSeconds ( new \DateTime (), $duration )
2024-01-10 05:38:29 +13:00
], $detector -> getOS (), $detector -> getClient (), $detector -> getDevice ()));
2023-09-29 01:45:52 +13:00
2024-01-10 05:38:29 +13:00
$session = $dbForProject -> createDocument ( 'sessions' , $session -> setAttribute ( '$permissions' , [
2023-09-29 01:45:52 +13:00
Permission :: read ( Role :: user ( $user -> getId ())),
Permission :: update ( Role :: user ( $user -> getId ())),
Permission :: delete ( Role :: user ( $user -> getId ())),
]));
2024-01-10 05:38:29 +13:00
$session -> setAttribute ( 'expire' , $expire );
2023-09-29 01:45:52 +13:00
2024-01-10 05:38:29 +13:00
if ( ! Config :: getParam ( 'domainVerification' )) {
$response -> addHeader ( 'X-Fallback-Cookies' , \json_encode ([ Auth :: $cookieName => Auth :: encodeSession ( $user -> getId (), $secret )]));
}
$queueForEvents
-> setParam ( 'userId' , $user -> getId ())
-> setParam ( 'sessionId' , $session -> getId ())
-> setPayload ( $response -> output ( $session , Response :: MODEL_SESSION ))
;
2021-08-05 17:06:38 +12:00
2024-01-10 05:38:29 +13:00
// TODO: Remove this deprecated, undocumented workaround
if ( $state [ 'success' ][ 'path' ] == $oauthDefaultSuccess ) {
$query [ 'project' ] = $project -> getId ();
$query [ 'domain' ] = Config :: getParam ( 'cookieDomain' );
$query [ 'key' ] = Auth :: $cookieName ;
$query [ 'secret' ] = $secret ;
}
$response
-> addCookie ( Auth :: $cookieName . '_legacy' , Auth :: encodeSession ( $user -> getId (), $secret ), ( new \DateTime ( $expire )) -> getTimestamp (), '/' , Config :: getParam ( 'cookieDomain' ), ( 'https' == $protocol ), true , null )
-> addCookie ( Auth :: $cookieName , Auth :: encodeSession ( $user -> getId (), $secret ), ( new \DateTime ( $expire )) -> getTimestamp (), '/' , Config :: getParam ( 'cookieDomain' ), ( 'https' == $protocol ), true , Config :: getParam ( 'cookieSamesite' ));
2020-06-30 09:43:34 +12:00
}
2024-01-26 04:44:05 +13:00
$dbForProject -> purgeCachedDocument ( 'users' , $user -> getId ());
2024-01-10 05:38:29 +13:00
2023-09-29 01:45:52 +13:00
$state [ 'success' ][ 'query' ] = URLParser :: unparseQuery ( $query );
$state [ 'success' ] = URLParser :: unparse ( $state [ 'success' ]);
2020-06-30 09:43:34 +12:00
2024-01-18 02:20:47 +13:00
$expire = DateTime :: formatTz ( DateTime :: addSeconds ( new \DateTime (), $duration ));
2020-06-30 09:43:34 +12:00
$response
-> addHeader ( 'Cache-Control' , 'no-store, no-cache, must-revalidate, max-age=0' )
-> addHeader ( 'Pragma' , 'no-cache' )
-> redirect ( $state [ 'success' ])
;
2020-12-27 03:31:53 +13:00
});
2020-01-06 00:29:42 +13:00
2023-05-18 13:11:45 +12:00
App :: get ( '/v1/account/identities' )
-> desc ( 'List Identities' )
-> groups ([ 'api' , 'account' ])
2024-01-18 00:17:03 +13:00
-> label ( 'scope' , 'accounts.read' )
2023-05-18 13:11:45 +12:00
-> label ( 'usage.metric' , 'users.{scope}.requests.read' )
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_SESSION , APP_AUTH_TYPE_JWT ])
-> label ( 'sdk.namespace' , 'account' )
-> label ( 'sdk.method' , 'listIdentities' )
-> label ( 'sdk.description' , '/docs/references/account/list-identities.md' )
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_OK )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
-> label ( 'sdk.response.model' , Response :: MODEL_IDENTITY_LIST )
-> label ( 'sdk.offline.model' , '/account/identities' )
-> param ( 'queries' , [], new Identities (), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' queries are allowed, each ' . APP_LIMIT_ARRAY_ELEMENT_SIZE . ' characters long. You may filter on the following attributes: ' . implode ( ', ' , Identities :: ALLOWED_ATTRIBUTES ), true )
-> inject ( 'response' )
-> inject ( 'user' )
-> inject ( 'dbForProject' )
-> action ( function ( array $queries , Response $response , Document $user , Database $dbForProject ) {
$queries = Query :: parseQueries ( $queries );
$queries [] = Query :: equal ( 'userInternalId' , [ $user -> getInternalId ()]);
// Get cursor document if there was a cursor query
2023-08-22 15:25:55 +12:00
$cursor = \array_filter ( $queries , function ( $query ) {
2023-12-07 03:10:40 +13:00
return \in_array ( $query -> getMethod (), [ Query :: TYPE_CURSOR_AFTER , Query :: TYPE_CURSOR_BEFORE ]);
2023-08-22 15:25:55 +12:00
});
2023-05-18 13:11:45 +12:00
$cursor = reset ( $cursor );
if ( $cursor ) {
/** @var Query $cursor */
$identityId = $cursor -> getValue ();
$cursorDocument = $dbForProject -> getDocument ( 'identities' , $identityId );
if ( $cursorDocument -> isEmpty ()) {
throw new Exception ( Exception :: GENERAL_CURSOR_NOT_FOUND , " Identity ' { $identityId } ' for the 'cursor' value not found. " );
}
$cursor -> setValue ( $cursorDocument );
}
$filterQueries = Query :: groupByType ( $queries )[ 'filters' ];
$results = $dbForProject -> find ( 'identities' , $queries );
$total = $dbForProject -> count ( 'identities' , $filterQueries , APP_LIMIT_COUNT );
$response -> dynamic ( new Document ([
'identities' => $results ,
'total' => $total ,
]), Response :: MODEL_IDENTITY_LIST );
});
App :: delete ( '/v1/account/identities/:identityId' )
2023-12-28 12:35:32 +13:00
-> desc ( 'Delete identity' )
2023-05-18 13:11:45 +12:00
-> groups ([ 'api' , 'account' ])
2024-01-18 00:17:03 +13:00
-> label ( 'scope' , 'accounts.write' )
2023-05-18 13:11:45 +12:00
-> label ( 'event' , 'users.[userId].identities.[identityId].delete' )
-> label ( 'audits.event' , 'identity.delete' )
-> label ( 'audits.resource' , 'identity/{request.$identityId}' )
-> label ( 'audits.userId' , '{user.$id}' )
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_SESSION , APP_AUTH_TYPE_JWT ])
-> label ( 'sdk.namespace' , 'account' )
-> label ( 'sdk.method' , 'deleteIdentity' )
-> label ( 'sdk.description' , '/docs/references/account/delete-identity.md' )
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_NOCONTENT )
-> label ( 'sdk.response.model' , Response :: MODEL_NONE )
2023-08-18 13:48:21 +12:00
-> param ( 'identityId' , '' , new UID (), 'Identity ID.' )
2023-05-18 13:11:45 +12:00
-> inject ( 'response' )
-> inject ( 'dbForProject' )
2023-12-28 12:35:32 +13:00
-> inject ( 'queueForEvents' )
-> action ( function ( string $identityId , Response $response , Database $dbForProject , Event $queueForEvents ) {
2023-05-18 13:11:45 +12:00
$identity = $dbForProject -> getDocument ( 'identities' , $identityId );
if ( $identity -> isEmpty ()) {
throw new Exception ( Exception :: USER_IDENTITY_NOT_FOUND );
}
$dbForProject -> deleteDocument ( 'identities' , $identityId );
2023-12-28 12:35:32 +13:00
$queueForEvents
-> setParam ( 'userId' , $identity -> getAttribute ( 'userId' ))
-> setParam ( 'identityId' , $identity -> getId ())
-> setPayload ( $response -> output ( $identity , Response :: MODEL_IDENTITY ));
2023-05-18 13:11:45 +12:00
return $response -> noContent ();
});
2023-12-01 00:35:52 +13:00
App :: post ( '/v1/account/tokens/magic-url' )
-> alias ( '/v1/account/sessions/magic-url' )
-> desc ( 'Create magic URL token' )
2021-08-30 22:44:52 +12:00
-> groups ([ 'api' , 'account' ])
2024-01-18 00:17:03 +13:00
-> label ( 'scope' , 'sessions.write' )
2021-08-31 21:22:48 +12:00
-> label ( 'auth.type' , 'magic-url' )
2022-09-05 20:00:08 +12:00
-> label ( 'audits.event' , 'session.create' )
2022-08-12 01:19:05 +12:00
-> label ( 'audits.resource' , 'user/{response.userId}' )
-> label ( 'audits.userId' , '{response.userId}' )
2021-08-30 22:44:52 +12:00
-> label ( 'sdk.auth' , [])
-> label ( 'sdk.namespace' , 'account' )
2023-12-13 00:24:50 +13:00
-> label ( 'sdk.method' , [ 'createMagicURLToken' , 'createMagicURLSession' ])
2024-01-16 23:33:54 +13:00
-> label ( 'sdk.description' , '/docs/references/account/create-token-magic-url.md' )
2021-08-30 22:44:52 +12:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_CREATED )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
-> label ( 'sdk.response.model' , Response :: MODEL_TOKEN )
-> label ( 'abuse-limit' , 10 )
2021-08-31 17:57:07 +12:00
-> label ( 'abuse-key' , 'url:{url},email:{param-email}' )
2024-01-13 06:26:01 +13:00
-> param ( 'userId' , '' , new CustomId (), 'User ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can\'t start with a special char. Max length is 36 chars.' )
2021-08-30 22:44:52 +12:00
-> param ( 'email' , '' , new Email (), 'User email.' )
2022-05-24 04:34:03 +12:00
-> param ( 'url' , '' , fn ( $clients ) => new Host ( $clients ), 'URL to redirect the user back to your app from the magic URL login. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API.' , true , [ 'clients' ])
2024-02-02 03:13:30 +13:00
-> param ( 'phrase' , false , new Boolean (), 'Toggle for security phrase. If enabled, email will be send with a randomly generated phrase and the phrase will also be included in the response. Confirming phrases match increases the security of your authentication flow.' , true )
2021-08-30 22:44:52 +12:00
-> inject ( 'request' )
-> inject ( 'response' )
2023-07-07 12:12:39 +12:00
-> inject ( 'user' )
2021-08-30 22:44:52 +12:00
-> inject ( 'project' )
2021-12-28 01:45:23 +13:00
-> inject ( 'dbForProject' )
2021-08-30 22:44:52 +12:00
-> inject ( 'locale' )
2022-12-21 05:11:30 +13:00
-> inject ( 'queueForEvents' )
2023-06-12 02:08:48 +12:00
-> inject ( 'queueForMails' )
2024-02-01 23:41:01 +13:00
-> action ( function ( string $userId , string $email , string $url , bool $phrase , Request $request , Response $response , Document $user , Document $project , Database $dbForProject , Locale $locale , Event $queueForEvents , Mail $queueForMails ) {
2021-08-30 22:44:52 +12:00
2022-05-24 02:54:50 +12:00
if ( empty ( App :: getEnv ( '_APP_SMTP_HOST' ))) {
2022-08-16 18:59:03 +12:00
throw new Exception ( Exception :: GENERAL_SMTP_DISABLED , 'SMTP disabled' );
2021-08-31 19:32:58 +12:00
}
2024-02-01 23:41:01 +13:00
if ( $phrase === true ) {
2024-02-02 03:13:30 +13:00
$phrase = Phrase :: generate ();
2024-01-11 03:52:32 +13:00
}
2021-12-11 06:52:33 +13:00
$roles = Authorization :: getRoles ();
$isPrivilegedUser = Auth :: isPrivilegedUser ( $roles );
$isAppUser = Auth :: isAppUser ( $roles );
2021-08-30 22:44:52 +12:00
2023-07-07 12:12:39 +12:00
$result = $dbForProject -> findOne ( 'users' , [ Query :: equal ( 'email' , [ $email ])]);
if ( $result !== false && ! $result -> isEmpty ()) {
$user -> setAttributes ( $result -> getArrayCopy ());
} else {
2021-10-08 08:10:43 +13:00
$limit = $project -> getAttribute ( 'auths' , [])[ 'limit' ] ? ? 0 ;
2021-08-30 22:44:52 +12:00
if ( $limit !== 0 ) {
2022-05-16 21:58:17 +12:00
$total = $dbForProject -> count ( 'users' , max : APP_LIMIT_USERS );
2021-08-30 22:44:52 +12:00
2022-02-27 22:57:09 +13:00
if ( $total >= $limit ) {
2022-08-16 18:59:03 +12:00
throw new Exception ( Exception :: USER_COUNT_EXCEEDED );
2021-08-30 22:44:52 +12:00
}
}
2023-05-18 13:11:45 +12:00
// Makes sure this email is not already used in another identity
$identityWithMatchingEmail = $dbForProject -> findOne ( 'identities' , [
Query :: equal ( 'providerEmail' , [ $email ]),
]);
if ( $identityWithMatchingEmail !== false && ! $identityWithMatchingEmail -> isEmpty ()) {
throw new Exception ( Exception :: USER_EMAIL_ALREADY_EXISTS );
}
2023-04-12 11:01:50 +12:00
$userId = $userId === 'unique()' ? ID :: unique () : $userId ;
2021-08-30 22:44:52 +12:00
2023-07-07 12:12:39 +12:00
$user -> setAttributes ([
2022-08-15 02:22:38 +12:00
'$id' => $userId ,
2022-08-02 21:21:53 +12:00
'$permissions' => [
2022-08-14 17:21:11 +12:00
Permission :: read ( Role :: any ()),
2022-08-15 23:24:31 +12:00
Permission :: update ( Role :: user ( $userId )),
Permission :: delete ( Role :: user ( $userId )),
2022-08-02 21:21:53 +12:00
],
2021-12-17 00:30:43 +13:00
'email' => $email ,
'emailVerification' => false ,
'status' => true ,
'password' => null ,
2022-05-05 02:37:37 +12:00
'hash' => Auth :: DEFAULT_ALGO ,
'hashOptions' => Auth :: DEFAULT_ALGO_OPTIONS ,
2022-07-04 21:55:11 +12:00
'passwordUpdate' => null ,
2022-07-14 02:02:49 +12:00
'registration' => DateTime :: now (),
2021-12-17 00:30:43 +13:00
'reset' => false ,
2021-12-28 23:48:50 +13:00
'prefs' => new \stdClass (),
2022-04-26 22:36:49 +12:00
'sessions' => null ,
2022-04-27 23:06:53 +12:00
'tokens' => null ,
2022-04-28 00:44:47 +12:00
'memberships' => null ,
2023-08-23 13:34:23 +12:00
'search' => implode ( ' ' , [ $userId , $email ]),
'accessedAt' => DateTime :: now (),
2023-07-07 12:12:39 +12:00
]);
2023-09-14 07:18:50 +12:00
$user -> removeAttribute ( '$internalId' );
2023-07-07 12:12:39 +12:00
Authorization :: skip ( fn () => $dbForProject -> createDocument ( 'users' , $user ));
2021-08-30 22:44:52 +12:00
}
2024-01-11 23:51:26 +13:00
$tokenSecret = Auth :: tokenGenerator ( Auth :: TOKEN_LENGTH_MAGIC_URL );
2023-05-23 00:22:25 +12:00
$expire = DateTime :: formatTz ( DateTime :: addSeconds ( new \DateTime (), Auth :: TOKEN_EXPIRATION_CONFIRM ));
2021-10-08 08:10:43 +13:00
2021-08-30 22:44:52 +12:00
$token = new Document ([
2022-08-15 02:22:38 +12:00
'$id' => ID :: unique (),
2021-08-30 22:44:52 +12:00
'userId' => $user -> getId (),
2022-06-07 21:37:09 +12:00
'userInternalId' => $user -> getInternalId (),
2021-08-30 22:44:52 +12:00
'type' => Auth :: TOKEN_TYPE_MAGIC_URL ,
2023-10-11 01:30:42 +13:00
'secret' => Auth :: hash ( $tokenSecret ), // One way hash encryption to protect DB leak
2022-11-05 03:48:29 +13:00
'expire' => $expire ,
2021-08-30 22:44:52 +12:00
'userAgent' => $request -> getUserAgent ( 'UNKNOWN' ),
'ip' => $request -> getIP (),
]);
2022-08-19 16:04:33 +12:00
Authorization :: setRole ( Role :: user ( $user -> getId ()) -> toString ());
2021-08-30 22:44:52 +12:00
2022-04-27 23:06:53 +12:00
$token = $dbForProject -> createDocument ( 'tokens' , $token
2022-08-02 21:21:53 +12:00
-> setAttribute ( '$permissions' , [
2022-08-15 23:24:31 +12:00
Permission :: read ( Role :: user ( $user -> getId ())),
Permission :: update ( Role :: user ( $user -> getId ())),
Permission :: delete ( Role :: user ( $user -> getId ())),
2022-08-02 21:21:53 +12:00
]));
2021-08-30 22:44:52 +12:00
2023-12-15 02:32:06 +13:00
$dbForProject -> purgeCachedDocument ( 'users' , $user -> getId ());
2021-08-30 22:44:52 +12:00
2022-05-24 02:54:50 +12:00
if ( empty ( $url )) {
$url = $request -> getProtocol () . '://' . $request -> getHostname () . '/auth/magic-url' ;
2021-08-31 21:22:48 +12:00
}
2021-08-30 22:44:52 +12:00
$url = Template :: parseURL ( $url );
2023-10-11 02:36:53 +13:00
$url [ 'query' ] = Template :: mergeQuery ((( isset ( $url [ 'query' ])) ? $url [ 'query' ] : '' ), [ 'userId' => $user -> getId (), 'secret' => $tokenSecret , 'expire' => $expire , 'project' => $project -> getId ()]);
2021-08-30 22:44:52 +12:00
$url = Template :: unParseURL ( $url );
2022-12-14 19:35:04 +13:00
$subject = $locale -> getText ( " emails.magicSession.subject " );
2023-04-19 20:29:29 +12:00
$customTemplate = $project -> getAttribute ( 'templates' , [])[ 'email.magicSession-' . $locale -> default ] ? ? [];
2023-08-26 03:13:25 +12:00
2024-01-10 01:23:13 +13:00
$detector = new Detector ( $request -> getUserAgent ( 'UNKNOWN' ));
$agentOs = $detector -> getOS ();
$agentClient = $detector -> getClient ();
$agentDevice = $detector -> getDevice ();
$message = Template :: fromFile ( __DIR__ . '/../../config/locale/templates/email-magic-url.tpl' );
2023-10-05 12:14:27 +13:00
$message
-> setParam ( '{{hello}}' , $locale -> getText ( " emails.magicSession.hello " ))
2024-01-10 01:23:13 +13:00
-> setParam ( '{{optionButton}}' , $locale -> getText ( " emails.magicSession.optionButton " ))
-> setParam ( '{{buttonText}}' , $locale -> getText ( " emails.magicSession.buttonText " ))
-> setParam ( '{{optionUrl}}' , $locale -> getText ( " emails.magicSession.optionUrl " ))
-> setParam ( '{{clientInfo}}' , $locale -> getText ( " emails.magicSession.clientInfo " ))
2023-10-05 12:14:27 +13:00
-> setParam ( '{{thanks}}' , $locale -> getText ( " emails.magicSession.thanks " ))
-> setParam ( '{{signature}}' , $locale -> getText ( " emails.magicSession.signature " ));
2024-01-11 03:52:32 +13:00
2024-02-01 23:41:01 +13:00
if ( ! empty ( $phrase )) {
2024-01-11 03:52:32 +13:00
$message -> setParam ( '{{securityPhrase}}' , $locale -> getText ( " emails.magicSession.securityPhrase " ));
} else {
$message -> setParam ( '{{securityPhrase}}' , '' );
}
2024-01-11 04:10:05 +13:00
2023-08-29 21:40:30 +12:00
$body = $message -> render ();
$smtp = $project -> getAttribute ( 'smtp' , []);
$smtpEnabled = $smtp [ 'enabled' ] ? ? false ;
2023-08-29 00:19:37 +12:00
2023-08-29 21:40:30 +12:00
$senderEmail = App :: getEnv ( '_APP_SYSTEM_EMAIL_ADDRESS' , APP_EMAIL_TEAM );
$senderName = App :: getEnv ( '_APP_SYSTEM_EMAIL_NAME' , APP_NAME . ' Server' );
$replyTo = " " ;
2023-08-29 00:19:37 +12:00
2023-08-29 21:40:30 +12:00
if ( $smtpEnabled ) {
if ( ! empty ( $smtp [ 'senderEmail' ])) {
$senderEmail = $smtp [ 'senderEmail' ];
}
if ( ! empty ( $smtp [ 'senderName' ])) {
$senderName = $smtp [ 'senderName' ];
}
if ( ! empty ( $smtp [ 'replyTo' ])) {
$replyTo = $smtp [ 'replyTo' ];
}
2023-08-29 00:19:37 +12:00
2023-09-28 06:10:21 +13:00
$queueForMails
2023-08-26 03:13:25 +12:00
-> setSmtpHost ( $smtp [ 'host' ] ? ? '' )
-> setSmtpPort ( $smtp [ 'port' ] ? ? '' )
-> setSmtpUsername ( $smtp [ 'username' ] ? ? '' )
-> setSmtpPassword ( $smtp [ 'password' ] ? ? '' )
2023-08-29 21:40:30 +12:00
-> setSmtpSecure ( $smtp [ 'secure' ] ? ? '' );
2023-08-29 00:19:37 +12:00
2023-08-30 16:30:44 +12:00
if ( ! empty ( $customTemplate )) {
if ( ! empty ( $customTemplate [ 'senderEmail' ])) {
$senderEmail = $customTemplate [ 'senderEmail' ];
}
if ( ! empty ( $customTemplate [ 'senderName' ])) {
$senderName = $customTemplate [ 'senderName' ];
}
if ( ! empty ( $customTemplate [ 'replyTo' ])) {
$replyTo = $customTemplate [ 'replyTo' ];
}
$body = $customTemplate [ 'message' ] ? ? '' ;
$subject = $customTemplate [ 'subject' ] ? ? $subject ;
2023-08-29 21:40:30 +12:00
}
2023-09-28 06:10:21 +13:00
$queueForMails
2023-08-30 16:30:44 +12:00
-> setSmtpReplyTo ( $replyTo )
-> setSmtpSenderEmail ( $senderEmail )
-> setSmtpSenderName ( $senderName );
2023-04-19 20:29:29 +12:00
}
2023-08-28 10:45:37 +12:00
$emailVariables = [
'direction' => $locale -> getText ( 'settings.direction' ),
2024-01-12 09:36:05 +13:00
/* {{user}}, {{team}}, {{redirect}} and {{project}} are required in default and custom templates */
2023-08-31 09:52:55 +12:00
'user' => '' ,
'team' => '' ,
'project' => $project -> getAttribute ( 'name' ),
2024-01-10 01:23:13 +13:00
'redirect' => $url ,
2024-01-10 23:33:55 +13:00
'agentDevice' => '<strong>' . ( $agentDevice [ 'deviceBrand' ] ? ? $agentDevice [ 'deviceBrand' ] ? ? 'UNKNOWN' ) . '</strong>' ,
'agentClient' => '<strong>' . ( $agentClient [ 'clientName' ] ? ? 'UNKNOWN' ) . '</strong>' ,
2024-01-20 01:12:07 +13:00
'agentOs' => '<strong>' . ( $agentOs [ 'osName' ] ? ? 'UNKNOWN' ) . '</strong>' ,
2024-02-01 23:41:01 +13:00
'phrase' => '<strong>' . ( ! empty ( $phrase ) ? $phrase : '' ) . '</strong>'
2023-08-28 10:45:37 +12:00
];
2022-12-14 19:35:04 +13:00
2023-06-12 02:08:48 +12:00
$queueForMails
2022-12-14 19:35:04 +13:00
-> setSubject ( $subject )
-> setBody ( $body )
2023-08-28 10:45:37 +12:00
-> setVariables ( $emailVariables )
2023-08-30 16:30:44 +12:00
-> setRecipient ( $email )
-> trigger ();
2021-08-30 22:44:52 +12:00
2022-12-21 05:11:30 +13:00
$queueForEvents -> setPayload (
2022-05-11 01:52:55 +12:00
$response -> output (
2023-10-11 01:30:42 +13:00
$token -> setAttribute ( 'secret' , $tokenSecret ),
2021-08-30 22:44:52 +12:00
Response :: MODEL_TOKEN
2022-05-11 01:52:55 +12:00
)
);
2021-08-30 22:44:52 +12:00
2022-04-19 04:21:45 +12:00
// Hide secret for clients
2023-10-11 02:36:53 +13:00
$token -> setAttribute ( 'secret' , ( $isPrivilegedUser || $isAppUser ) ? $tokenSecret : '' );
2021-08-30 22:44:52 +12:00
2024-02-01 23:41:01 +13:00
if ( ! empty ( $phrase )) {
$token -> setAttribute ( 'phrase' , $phrase );
2024-01-11 03:52:32 +13:00
}
2021-08-30 22:44:52 +12:00
$response
-> setStatusCode ( Response :: STATUS_CODE_CREATED )
-> dynamic ( $token , Response :: MODEL_TOKEN )
;
});
2024-01-20 02:42:26 +13:00
App :: post ( '/v1/account/tokens/email' )
-> desc ( 'Create email token (OTP)' )
-> groups ([ 'api' , 'account' ])
-> label ( 'scope' , 'sessions.write' )
-> label ( 'auth.type' , 'email' )
-> label ( 'audits.event' , 'session.create' )
2022-08-12 01:19:05 +12:00
-> label ( 'audits.resource' , 'user/{response.userId}' )
2022-08-12 23:01:12 +12:00
-> label ( 'audits.userId' , '{response.userId}' )
2021-08-30 22:44:52 +12:00
-> label ( 'sdk.auth' , [])
-> label ( 'sdk.namespace' , 'account' )
2024-01-20 02:42:26 +13:00
-> label ( 'sdk.method' , 'createEmailToken' )
-> label ( 'sdk.description' , '/docs/references/account/create-token-email.md' )
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_CREATED )
2021-08-30 22:44:52 +12:00
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
2024-01-20 02:42:26 +13:00
-> label ( 'sdk.response.model' , Response :: MODEL_TOKEN )
2021-08-30 22:44:52 +12:00
-> label ( 'abuse-limit' , 10 )
2024-01-20 02:42:26 +13:00
-> label ( 'abuse-key' , 'url:{url},email:{param-email}' )
-> param ( 'userId' , '' , new CustomId (), 'User ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can\'t start with a special char. Max length is 36 chars.' )
-> param ( 'email' , '' , new Email (), 'User email.' )
2024-02-02 03:13:30 +13:00
-> param ( 'phrase' , false , new Boolean (), 'Toggle for security phrase. If enabled, email will be send with a randomly generated phrase and the phrase will also be included in the response. Confirming phrases match increases the security of your authentication flow.' , true )
2021-08-30 22:44:52 +12:00
-> inject ( 'request' )
-> inject ( 'response' )
2023-07-07 12:12:39 +12:00
-> inject ( 'user' )
2022-11-01 03:54:15 +13:00
-> inject ( 'project' )
2024-01-20 02:42:26 +13:00
-> inject ( 'dbForProject' )
2021-08-30 22:44:52 +12:00
-> inject ( 'locale' )
2022-12-21 05:11:30 +13:00
-> inject ( 'queueForEvents' )
2024-01-20 02:42:26 +13:00
-> inject ( 'queueForMails' )
2024-02-01 23:41:01 +13:00
-> action ( function ( string $userId , string $email , bool $phrase , Request $request , Response $response , Document $user , Document $project , Database $dbForProject , Locale $locale , Event $queueForEvents , Mail $queueForMails ) {
2024-01-20 02:42:26 +13:00
if ( empty ( App :: getEnv ( '_APP_SMTP_HOST' ))) {
throw new Exception ( Exception :: GENERAL_SMTP_DISABLED , 'SMTP disabled' );
}
2021-08-30 22:44:52 +12:00
2024-02-01 23:41:01 +13:00
if ( $phrase === true ) {
2024-02-02 03:13:30 +13:00
$phrase = Phrase :: generate ();
2024-01-20 02:42:26 +13:00
}
2022-06-08 21:20:23 +12:00
2024-01-20 02:42:26 +13:00
$roles = Authorization :: getRoles ();
$isPrivilegedUser = Auth :: isPrivilegedUser ( $roles );
$isAppUser = Auth :: isAppUser ( $roles );
2021-08-30 22:44:52 +12:00
2024-01-20 02:42:26 +13:00
$result = $dbForProject -> findOne ( 'users' , [ Query :: equal ( 'email' , [ $email ])]);
if ( $result !== false && ! $result -> isEmpty ()) {
$user -> setAttributes ( $result -> getArrayCopy ());
} else {
$limit = $project -> getAttribute ( 'auths' , [])[ 'limit' ] ? ? 0 ;
2021-08-30 22:44:52 +12:00
2024-01-20 02:42:26 +13:00
if ( $limit !== 0 ) {
$total = $dbForProject -> count ( 'users' , max : APP_LIMIT_USERS );
2021-08-30 22:44:52 +12:00
2024-01-20 02:42:26 +13:00
if ( $total >= $limit ) {
throw new Exception ( Exception :: USER_COUNT_EXCEEDED );
}
}
2021-08-30 22:44:52 +12:00
2024-01-20 02:42:26 +13:00
// Makes sure this email is not already used in another identity
$identityWithMatchingEmail = $dbForProject -> findOne ( 'identities' , [
Query :: equal ( 'providerEmail' , [ $email ]),
]);
if ( $identityWithMatchingEmail !== false && ! $identityWithMatchingEmail -> isEmpty ()) {
throw new Exception ( Exception :: USER_EMAIL_ALREADY_EXISTS );
}
2023-07-07 12:12:39 +12:00
2024-01-20 02:42:26 +13:00
$userId = $userId === 'unique()' ? ID :: unique () : $userId ;
2022-07-05 22:59:03 +12:00
2024-01-20 02:42:26 +13:00
$user -> setAttributes ([
'$id' => $userId ,
'$permissions' => [
Permission :: read ( Role :: any ()),
Permission :: update ( Role :: user ( $userId )),
Permission :: delete ( Role :: user ( $userId )),
],
'email' => $email ,
'emailVerification' => false ,
'status' => true ,
'password' => null ,
'hash' => Auth :: DEFAULT_ALGO ,
'hashOptions' => Auth :: DEFAULT_ALGO_OPTIONS ,
'passwordUpdate' => null ,
'registration' => DateTime :: now (),
'reset' => false ,
'prefs' => new \stdClass (),
'sessions' => null ,
'tokens' => null ,
'memberships' => null ,
'search' => implode ( ' ' , [ $userId , $email ]),
'accessedAt' => DateTime :: now (),
]);
$user -> removeAttribute ( '$internalId' );
Authorization :: skip ( fn () => $dbForProject -> createDocument ( 'users' , $user ));
}
$tokenSecret = Auth :: codeGenerator ( 6 );
$expire = DateTime :: formatTz ( DateTime :: addSeconds ( new \DateTime (), Auth :: TOKEN_EXPIRATION_OTP ));
$token = new Document ([
'$id' => ID :: unique (),
'userId' => $user -> getId (),
'userInternalId' => $user -> getInternalId (),
'type' => Auth :: TOKEN_TYPE_EMAIL ,
'secret' => Auth :: hash ( $tokenSecret ), // One way hash encryption to protect DB leak
'expire' => $expire ,
'userAgent' => $request -> getUserAgent ( 'UNKNOWN' ),
'ip' => $request -> getIP (),
]);
2021-08-30 22:44:52 +12:00
2022-08-19 16:04:33 +12:00
Authorization :: setRole ( Role :: user ( $user -> getId ()) -> toString ());
2021-08-30 22:44:52 +12:00
2024-01-20 02:42:26 +13:00
$token = $dbForProject -> createDocument ( 'tokens' , $token
2022-08-02 21:21:53 +12:00
-> setAttribute ( '$permissions' , [
2022-08-15 23:24:31 +12:00
Permission :: read ( Role :: user ( $user -> getId ())),
Permission :: update ( Role :: user ( $user -> getId ())),
Permission :: delete ( Role :: user ( $user -> getId ())),
2022-08-02 21:21:53 +12:00
]));
2021-08-30 22:44:52 +12:00
2024-01-26 05:53:51 +13:00
$dbForProject -> purgeCachedDocument ( 'users' , $user -> getId ());
2022-04-04 21:59:32 +12:00
2024-01-20 02:42:26 +13:00
$subject = $locale -> getText ( " emails.otpSession.subject " );
$customTemplate = $project -> getAttribute ( 'templates' , [])[ 'email.otpSession-' . $locale -> default ] ? ? [];
2021-10-08 08:10:43 +13:00
2024-01-20 02:42:26 +13:00
$detector = new Detector ( $request -> getUserAgent ( 'UNKNOWN' ));
$agentOs = $detector -> getOS ();
$agentClient = $detector -> getClient ();
$agentDevice = $detector -> getDevice ();
2021-08-30 22:44:52 +12:00
2024-01-20 02:42:26 +13:00
$message = Template :: fromFile ( __DIR__ . '/../../config/locale/templates/email-otp.tpl' );
$message
-> setParam ( '{{hello}}' , $locale -> getText ( " emails.otpSession.hello " ))
-> setParam ( '{{description}}' , $locale -> getText ( " emails.otpSession.description " ))
-> setParam ( '{{clientInfo}}' , $locale -> getText ( " emails.otpSession.clientInfo " ))
-> setParam ( '{{thanks}}' , $locale -> getText ( " emails.otpSession.thanks " ))
-> setParam ( '{{signature}}' , $locale -> getText ( " emails.otpSession.signature " ));
2024-02-01 23:41:01 +13:00
if ( ! empty ( $phrase )) {
2024-01-20 02:42:26 +13:00
$message -> setParam ( '{{securityPhrase}}' , $locale -> getText ( " emails.otpSession.securityPhrase " ));
} else {
$message -> setParam ( '{{securityPhrase}}' , '' );
2021-08-30 22:44:52 +12:00
}
2021-09-01 19:29:12 +12:00
2024-01-20 02:42:26 +13:00
$body = $message -> render ();
2021-08-30 22:44:52 +12:00
2024-01-20 02:42:26 +13:00
$smtp = $project -> getAttribute ( 'smtp' , []);
$smtpEnabled = $smtp [ 'enabled' ] ? ? false ;
$senderEmail = App :: getEnv ( '_APP_SYSTEM_EMAIL_ADDRESS' , APP_EMAIL_TEAM );
$senderName = App :: getEnv ( '_APP_SYSTEM_EMAIL_NAME' , APP_NAME . ' Server' );
$replyTo = " " ;
if ( $smtpEnabled ) {
if ( ! empty ( $smtp [ 'senderEmail' ])) {
$senderEmail = $smtp [ 'senderEmail' ];
}
if ( ! empty ( $smtp [ 'senderName' ])) {
$senderName = $smtp [ 'senderName' ];
}
if ( ! empty ( $smtp [ 'replyTo' ])) {
$replyTo = $smtp [ 'replyTo' ];
}
$queueForMails
-> setSmtpHost ( $smtp [ 'host' ] ? ? '' )
-> setSmtpPort ( $smtp [ 'port' ] ? ? '' )
-> setSmtpUsername ( $smtp [ 'username' ] ? ? '' )
-> setSmtpPassword ( $smtp [ 'password' ] ? ? '' )
-> setSmtpSecure ( $smtp [ 'secure' ] ? ? '' );
if ( ! empty ( $customTemplate )) {
if ( ! empty ( $customTemplate [ 'senderEmail' ])) {
$senderEmail = $customTemplate [ 'senderEmail' ];
}
if ( ! empty ( $customTemplate [ 'senderName' ])) {
$senderName = $customTemplate [ 'senderName' ];
}
if ( ! empty ( $customTemplate [ 'replyTo' ])) {
$replyTo = $customTemplate [ 'replyTo' ];
}
$body = $customTemplate [ 'message' ] ? ? '' ;
$subject = $customTemplate [ 'subject' ] ? ? $subject ;
}
$queueForMails
-> setSmtpReplyTo ( $replyTo )
-> setSmtpSenderEmail ( $senderEmail )
-> setSmtpSenderName ( $senderName );
2021-08-30 22:44:52 +12:00
}
2024-01-20 02:42:26 +13:00
$emailVariables = [
'direction' => $locale -> getText ( 'settings.direction' ),
/* {{user}} ,{{team}}, {{project}} and {{otp}} are required in the templates */
'user' => '' ,
'team' => '' ,
'project' => $project -> getAttribute ( 'name' ),
'otp' => $tokenSecret ,
'agentDevice' => '<strong>' . ( $agentDevice [ 'deviceBrand' ] ? ? $agentDevice [ 'deviceBrand' ] ? ? 'UNKNOWN' ) . '</strong>' ,
'agentClient' => '<strong>' . ( $agentClient [ 'clientName' ] ? ? 'UNKNOWN' ) . '</strong>' ,
'agentOs' => '<strong>' . ( $agentOs [ 'osName' ] ? ? 'UNKNOWN' ) . '</strong>' ,
2024-02-01 23:41:01 +13:00
'phrase' => '<strong>' . ( ! empty ( $phrase ) ? $phrase : '' ) . '</strong>'
2023-08-28 10:45:37 +12:00
];
2022-12-14 19:35:04 +13:00
2023-06-12 02:08:48 +12:00
$queueForMails
2022-12-14 19:35:04 +13:00
-> setSubject ( $subject )
-> setBody ( $body )
2023-08-28 10:45:37 +12:00
-> setVariables ( $emailVariables )
2023-08-30 16:30:44 +12:00
-> setRecipient ( $email )
-> trigger ();
2021-08-30 22:44:52 +12:00
2022-12-21 05:11:30 +13:00
$queueForEvents -> setPayload (
2022-05-11 01:52:55 +12:00
$response -> output (
2023-10-11 01:30:42 +13:00
$token -> setAttribute ( 'secret' , $tokenSecret ),
2021-08-30 22:44:52 +12:00
Response :: MODEL_TOKEN
2022-05-11 01:52:55 +12:00
)
);
2021-08-30 22:44:52 +12:00
2022-04-19 04:21:45 +12:00
// Hide secret for clients
2023-10-11 02:36:53 +13:00
$token -> setAttribute ( 'secret' , ( $isPrivilegedUser || $isAppUser ) ? $tokenSecret : '' );
2021-08-30 22:44:52 +12:00
2024-02-01 23:41:01 +13:00
if ( ! empty ( $phrase )) {
$token -> setAttribute ( 'phrase' , $phrase );
2024-01-11 03:52:32 +13:00
}
2021-08-30 22:44:52 +12:00
$response
-> setStatusCode ( Response :: STATUS_CODE_CREATED )
-> dynamic ( $token , Response :: MODEL_TOKEN )
;
});
2024-01-10 04:56:01 +13:00
$createSession = function ( string $userId , string $secret , Request $request , Response $response , Document $user , Database $dbForProject , Document $project , Locale $locale , Reader $geodb , Event $queueForEvents ) {
$roles = Authorization :: getRoles ();
$isPrivilegedUser = Auth :: isPrivilegedUser ( $roles );
$isAppUser = Auth :: isAppUser ( $roles );
2021-08-30 22:44:52 +12:00
2024-01-10 04:56:01 +13:00
/** @var Utopia\Database\Document $user */
$userFromRequest = Authorization :: skip ( fn () => $dbForProject -> getDocument ( 'users' , $userId ));
2022-06-08 21:20:23 +12:00
2024-01-10 04:56:01 +13:00
if ( $userFromRequest -> isEmpty ()) {
throw new Exception ( Exception :: USER_INVALID_TOKEN );
}
2021-08-30 22:44:52 +12:00
2024-01-10 04:56:01 +13:00
$verifiedToken = Auth :: tokenVerify ( $userFromRequest -> getAttribute ( 'tokens' , []), null , $secret );
2021-08-30 22:44:52 +12:00
2024-01-10 04:56:01 +13:00
if ( ! $verifiedToken ) {
throw new Exception ( Exception :: USER_INVALID_TOKEN );
}
2021-08-30 22:44:52 +12:00
2024-01-10 04:56:01 +13:00
$user -> setAttributes ( $userFromRequest -> getArrayCopy ());
2021-08-30 22:44:52 +12:00
2024-01-10 04:56:01 +13:00
$duration = $project -> getAttribute ( 'auths' , [])[ 'duration' ] ? ? Auth :: TOKEN_EXPIRATION_LOGIN_LONG ;
$detector = new Detector ( $request -> getUserAgent ( 'UNKNOWN' ));
$record = $geodb -> get ( $request -> getIP ());
2024-01-18 00:03:04 +13:00
$sessionSecret = Auth :: tokenGenerator ( Auth :: TOKEN_LENGTH_SESSION );
2023-07-07 12:12:39 +12:00
2024-01-10 04:56:01 +13:00
$session = new Document ( array_merge (
[
'$id' => ID :: unique (),
'userId' => $user -> getId (),
'userInternalId' => $user -> getInternalId (),
'provider' => Auth :: getSessionProviderByTokenType ( $verifiedToken -> getAttribute ( 'type' )),
'secret' => Auth :: hash ( $sessionSecret ), // One way hash encryption to protect DB leak
'userAgent' => $request -> getUserAgent ( 'UNKNOWN' ),
'ip' => $request -> getIP (),
'countryCode' => ( $record ) ? \strtolower ( $record [ 'country' ][ 'iso_code' ]) : '--' ,
2024-01-23 00:20:33 +13:00
'expire' => DateTime :: addSeconds ( new \DateTime (), $duration )
2024-01-10 04:56:01 +13:00
],
$detector -> getOS (),
$detector -> getClient (),
$detector -> getDevice ()
));
2021-08-30 22:44:52 +12:00
2024-01-10 04:56:01 +13:00
Authorization :: setRole ( Role :: user ( $user -> getId ()) -> toString ());
2021-08-30 22:44:52 +12:00
2024-01-10 04:56:01 +13:00
$session = $dbForProject -> createDocument ( 'sessions' , $session
-> setAttribute ( '$permissions' , [
Permission :: read ( Role :: user ( $user -> getId ())),
Permission :: update ( Role :: user ( $user -> getId ())),
Permission :: delete ( Role :: user ( $user -> getId ())),
]));
2021-08-30 22:44:52 +12:00
2024-01-26 04:44:05 +13:00
$dbForProject -> purgeCachedDocument ( 'users' , $user -> getId ());
2024-01-10 04:56:01 +13:00
Authorization :: skip ( fn () => $dbForProject -> deleteDocument ( 'tokens' , $verifiedToken -> getId ()));
2024-01-26 04:44:05 +13:00
$dbForProject -> purgeCachedDocument ( 'users' , $user -> getId ());
2022-04-04 21:59:32 +12:00
2024-01-10 04:56:01 +13:00
if ( $verifiedToken -> getAttribute ( 'type' ) === Auth :: TOKEN_TYPE_MAGIC_URL ) {
$user -> setAttribute ( 'emailVerification' , true );
}
2021-10-08 08:10:43 +13:00
2024-01-10 04:56:01 +13:00
if ( $verifiedToken -> getAttribute ( 'type' ) === Auth :: TOKEN_TYPE_PHONE ) {
$user -> setAttribute ( 'phoneVerification' , true );
}
2021-08-30 22:44:52 +12:00
2024-01-10 04:56:01 +13:00
try {
$dbForProject -> updateDocument ( 'users' , $user -> getId (), $user );
} catch ( \Throwable $th ) {
throw new Exception ( Exception :: GENERAL_SERVER_ERROR , 'Failed saving user to DB' );
}
2021-08-30 22:44:52 +12:00
2024-01-10 04:56:01 +13:00
$queueForEvents
-> setParam ( 'userId' , $user -> getId ())
-> setParam ( 'sessionId' , $session -> getId ());
2021-09-01 19:29:12 +12:00
2024-01-10 04:56:01 +13:00
if ( ! Config :: getParam ( 'domainVerification' )) {
$response -> addHeader ( 'X-Fallback-Cookies' , \json_encode ([ Auth :: $cookieName => Auth :: encodeSession ( $user -> getId (), $sessionSecret )]));
}
2021-08-30 22:44:52 +12:00
2024-01-23 00:20:33 +13:00
$expire = DateTime :: formatTz ( DateTime :: addSeconds ( new \DateTime (), $duration ));
2024-01-10 04:56:01 +13:00
$protocol = $request -> getProtocol ();
2021-08-30 22:44:52 +12:00
2024-01-10 04:56:01 +13:00
$response
-> addCookie ( Auth :: $cookieName . '_legacy' , Auth :: encodeSession ( $user -> getId (), $sessionSecret ), ( new \DateTime ( $expire )) -> getTimestamp (), '/' , Config :: getParam ( 'cookieDomain' ), ( 'https' == $protocol ), true , null )
-> addCookie ( Auth :: $cookieName , Auth :: encodeSession ( $user -> getId (), $sessionSecret ), ( new \DateTime ( $expire )) -> getTimestamp (), '/' , Config :: getParam ( 'cookieDomain' ), ( 'https' == $protocol ), true , Config :: getParam ( 'cookieSamesite' ))
-> setStatusCode ( Response :: STATUS_CODE_CREATED );
2021-08-30 22:44:52 +12:00
2024-01-10 04:56:01 +13:00
$countryName = $locale -> getText ( 'countries.' . strtolower ( $session -> getAttribute ( 'countryCode' )), $locale -> getText ( 'locale.country.unknown' ));
2021-08-30 22:44:52 +12:00
2024-01-10 04:56:01 +13:00
$session
-> setAttribute ( 'current' , true )
-> setAttribute ( 'countryName' , $countryName )
-> setAttribute ( 'expire' , $expire )
-> setAttribute ( 'secret' , ( $isPrivilegedUser || $isAppUser ) ? Auth :: encodeSession ( $user -> getId (), $sessionSecret ) : '' )
;
2021-08-30 22:44:52 +12:00
2024-01-10 04:56:01 +13:00
$response -> dynamic ( $session , Response :: MODEL_SESSION );
};
2021-08-30 22:44:52 +12:00
2024-01-10 04:56:01 +13:00
App :: put ( '/v1/account/sessions/magic-url' )
2023-10-13 02:38:32 +13:00
-> alias ( '/v1/account/sessions/phone' )
2024-01-10 04:56:01 +13:00
-> desc ( 'Create session (deprecated)' )
2023-12-01 00:35:52 +13:00
-> label ( 'event' , 'users.[userId].sessions.[sessionId].create' )
2023-10-13 02:38:32 +13:00
-> groups ([ 'api' , 'account' ])
2024-01-18 00:17:03 +13:00
-> label ( 'scope' , 'sessions.write' )
2023-09-29 01:45:52 +13:00
-> label ( 'audits.event' , 'session.create' )
-> label ( 'audits.resource' , 'user/{response.userId}' )
-> label ( 'audits.userId' , '{response.userId}' )
-> label ( 'usage.metric' , 'sessions.{scope}.requests.create' )
-> label ( 'sdk.auth' , [])
-> label ( 'sdk.namespace' , 'account' )
2024-01-10 04:56:01 +13:00
-> label ( 'sdk.method' , [ 'updateMagicURLSession' , 'updatePhoneSession' ])
2023-12-22 22:31:19 +13:00
-> label ( 'sdk.description' , '/docs/references/account/create-session.md' )
2023-09-29 01:45:52 +13:00
-> 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' , 10 )
-> label ( 'abuse-key' , 'ip:{ip},userId:{param-userId}' )
2024-01-13 06:26:01 +13:00
-> param ( 'userId' , '' , new CustomId (), 'User ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can\'t start with a special char. Max length is 36 chars.' )
2023-09-29 01:45:52 +13:00
-> param ( 'secret' , '' , new Text ( 256 ), 'Valid verification token.' )
-> inject ( 'request' )
-> inject ( 'response' )
-> inject ( 'user' )
-> inject ( 'dbForProject' )
-> inject ( 'project' )
-> inject ( 'locale' )
-> inject ( 'geodb' )
2022-12-21 05:11:30 +13:00
-> inject ( 'queueForEvents' )
2024-01-10 04:56:01 +13:00
-> action ( $createSession );
2021-08-30 22:44:52 +12:00
2024-01-10 04:56:01 +13:00
App :: post ( '/v1/account/sessions/token' )
-> desc ( 'Create session' )
-> label ( 'event' , 'users.[userId].sessions.[sessionId].create' )
2022-06-08 21:00:38 +12:00
-> groups ([ 'api' , 'account' ])
2024-01-18 00:17:03 +13:00
-> label ( 'scope' , 'sessions.write' )
2024-01-10 04:56:01 +13:00
-> label ( 'audits.event' , 'session.create' )
-> label ( 'audits.resource' , 'user/{response.userId}' )
-> label ( 'audits.userId' , '{response.userId}' )
-> label ( 'usage.metric' , 'sessions.{scope}.requests.create' )
-> label ( 'sdk.auth' , [])
-> label ( 'sdk.namespace' , 'account' )
-> label ( 'sdk.method' , 'createSession' )
-> label ( 'sdk.description' , '/docs/references/account/create-session.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' , 10 )
-> label ( 'abuse-key' , 'ip:{ip},userId:{param-userId}' )
2024-01-13 06:26:01 +13:00
-> param ( 'userId' , '' , new CustomId (), 'User ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can\'t start with a special char. Max length is 36 chars.' )
2024-01-11 23:54:41 +13:00
-> param ( 'secret' , '' , new Text ( 256 ), 'Secret of a token generated by login methods. For example, the `createMagicURLToken` or `createPhoneToken` methods.' )
2024-01-10 04:56:01 +13:00
-> inject ( 'request' )
-> inject ( 'response' )
-> inject ( 'user' )
-> inject ( 'dbForProject' )
-> inject ( 'project' )
-> inject ( 'locale' )
-> inject ( 'geodb' )
-> inject ( 'queueForEvents' )
-> action ( $createSession );
2021-08-30 22:44:52 +12:00
2023-12-01 00:35:52 +13:00
App :: post ( '/v1/account/tokens/phone' )
-> alias ( '/v1/account/sessions/phone' )
-> desc ( 'Create phone token' )
2022-06-08 21:00:38 +12:00
-> groups ([ 'api' , 'account' ])
2024-01-18 00:17:03 +13:00
-> label ( 'scope' , 'sessions.write' )
2022-06-08 21:00:38 +12:00
-> label ( 'auth.type' , 'phone' )
2022-09-05 20:00:08 +12:00
-> label ( 'audits.event' , 'session.create' )
2022-08-12 01:19:05 +12:00
-> label ( 'audits.resource' , 'user/{response.userId}' )
-> label ( 'audits.userId' , '{response.userId}' )
2022-06-08 21:00:38 +12:00
-> label ( 'sdk.auth' , [])
-> label ( 'sdk.namespace' , 'account' )
2023-12-13 00:24:50 +13:00
-> label ( 'sdk.method' , [ 'createPhoneToken' , 'createPhoneSession' ])
2024-01-16 23:33:54 +13:00
-> label ( 'sdk.description' , '/docs/references/account/create-token-phone.md' )
2022-06-08 21:00:38 +12:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_CREATED )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
-> label ( 'sdk.response.model' , Response :: MODEL_TOKEN )
-> label ( 'abuse-limit' , 10 )
2023-09-04 09:37:02 +12:00
-> label ( 'abuse-key' , 'url:{url},phone:{param-phone}' )
2023-01-21 11:22:16 +13:00
-> param ( 'userId' , '' , new CustomId (), 'Unique Id. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can\'t start with a special char. Max length is 36 chars.' )
2022-08-15 03:10:12 +12:00
-> param ( 'phone' , '' , new Phone (), 'Phone number. Format this number with a leading \'+\' and a country code, e.g., +16175551212.' )
2022-06-08 21:00:38 +12:00
-> inject ( 'request' )
-> inject ( 'response' )
2023-07-07 12:12:39 +12:00
-> inject ( 'user' )
2022-06-08 21:00:38 +12:00
-> inject ( 'project' )
-> inject ( 'dbForProject' )
2022-12-21 05:11:30 +13:00
-> inject ( 'queueForEvents' )
-> inject ( 'queueForMessaging' )
2023-04-19 20:29:29 +12:00
-> inject ( 'locale' )
2023-10-20 22:25:17 +13:00
-> action ( function ( string $userId , string $phone , Request $request , Response $response , Document $user , Document $project , Database $dbForProject , Event $queueForEvents , Messaging $queueForMessaging , Locale $locale ) {
2023-11-16 09:00:47 +13:00
if ( empty ( App :: getEnv ( '_APP_SMS_PROVIDER' ))) {
2022-08-16 18:59:03 +12:00
throw new Exception ( Exception :: GENERAL_PHONE_DISABLED , 'Phone provider not configured' );
2022-06-08 21:00:38 +12:00
}
$roles = Authorization :: getRoles ();
$isPrivilegedUser = Auth :: isPrivilegedUser ( $roles );
$isAppUser = Auth :: isAppUser ( $roles );
2023-07-07 12:12:39 +12:00
$result = $dbForProject -> findOne ( 'users' , [ Query :: equal ( 'phone' , [ $phone ])]);
if ( $result !== false && ! $result -> isEmpty ()) {
$user -> setAttributes ( $result -> getArrayCopy ());
} else {
2022-06-08 21:00:38 +12:00
$limit = $project -> getAttribute ( 'auths' , [])[ 'limit' ] ? ? 0 ;
if ( $limit !== 0 ) {
$total = $dbForProject -> count ( 'users' , max : APP_LIMIT_USERS );
if ( $total >= $limit ) {
2022-08-15 19:13:24 +12:00
throw new Exception ( Exception :: USER_COUNT_EXCEEDED );
2022-06-08 21:00:38 +12:00
}
}
2022-08-15 02:22:38 +12:00
$userId = $userId == 'unique()' ? ID :: unique () : $userId ;
2023-07-07 12:12:39 +12:00
$user -> setAttributes ([
2022-08-15 02:22:38 +12:00
'$id' => $userId ,
2022-08-02 21:21:53 +12:00
'$permissions' => [
2022-08-14 17:21:11 +12:00
Permission :: read ( Role :: any ()),
2022-08-15 23:24:31 +12:00
Permission :: update ( Role :: user ( $userId )),
Permission :: delete ( Role :: user ( $userId )),
2022-08-02 21:21:53 +12:00
],
2022-06-08 21:00:38 +12:00
'email' => null ,
2022-08-15 01:43:41 +12:00
'phone' => $phone ,
2022-06-08 21:00:38 +12:00
'emailVerification' => false ,
'phoneVerification' => false ,
'status' => true ,
'password' => null ,
2022-07-04 21:55:11 +12:00
'passwordUpdate' => null ,
2022-07-14 02:02:49 +12:00
'registration' => DateTime :: now (),
2022-06-08 21:00:38 +12:00
'reset' => false ,
'prefs' => new \stdClass (),
'sessions' => null ,
'tokens' => null ,
'memberships' => null ,
2023-08-23 13:34:23 +12:00
'search' => implode ( ' ' , [ $userId , $phone ]),
'accessedAt' => DateTime :: now (),
2023-07-07 12:12:39 +12:00
]);
2023-09-14 07:18:50 +12:00
$user -> removeAttribute ( '$internalId' );
2023-07-07 12:12:39 +12:00
Authorization :: skip ( fn () => $dbForProject -> createDocument ( 'users' , $user ));
2023-11-29 02:12:34 +13:00
try {
$target = Authorization :: skip ( fn () => $dbForProject -> createDocument ( 'targets' , new Document ([
'userId' => $user -> getId (),
'userInternalId' => $user -> getInternalId (),
2023-11-29 22:52:26 +13:00
'providerType' => MESSAGE_TYPE_SMS ,
2023-11-29 02:12:34 +13:00
'identifier' => $phone ,
])));
$user -> setAttribute ( 'targets' , [ ... $user -> getAttribute ( 'targets' , []), $target ]);
} catch ( Duplicate ) {
$existingTarget = $dbForProject -> findOne ( 'targets' , [
Query :: equal ( 'identifier' , [ $phone ]),
]);
$user -> setAttribute ( 'targets' , [ ... $user -> getAttribute ( 'targets' , []), $existingTarget ]);
}
2023-12-15 02:32:06 +13:00
$dbForProject -> purgeCachedDocument ( 'users' , $user -> getId ());
2022-06-08 21:00:38 +12:00
}
2022-09-19 20:09:48 +12:00
$secret = Auth :: codeGenerator ();
2024-01-20 02:42:26 +13:00
$expire = DateTime :: formatTz ( DateTime :: addSeconds ( new \DateTime (), Auth :: TOKEN_EXPIRATION_OTP ));
2022-06-08 21:00:38 +12:00
$token = new Document ([
2022-08-15 02:22:38 +12:00
'$id' => ID :: unique (),
2022-06-08 21:00:38 +12:00
'userId' => $user -> getId (),
2022-06-21 09:38:45 +12:00
'userInternalId' => $user -> getInternalId (),
2022-06-08 21:00:38 +12:00
'type' => Auth :: TOKEN_TYPE_PHONE ,
2022-09-23 10:25:17 +12:00
'secret' => Auth :: hash ( $secret ),
2022-06-08 21:00:38 +12:00
'expire' => $expire ,
'userAgent' => $request -> getUserAgent ( 'UNKNOWN' ),
'ip' => $request -> getIP (),
]);
2022-08-19 16:04:33 +12:00
Authorization :: setRole ( Role :: user ( $user -> getId ()) -> toString ());
2022-06-08 21:00:38 +12:00
$token = $dbForProject -> createDocument ( 'tokens' , $token
2022-08-02 21:21:53 +12:00
-> setAttribute ( '$permissions' , [
2022-08-15 23:24:31 +12:00
Permission :: read ( Role :: user ( $user -> getId ())),
Permission :: update ( Role :: user ( $user -> getId ())),
Permission :: delete ( Role :: user ( $user -> getId ())),
2022-08-02 21:21:53 +12:00
]));
2022-06-08 21:00:38 +12:00
2023-12-15 02:32:06 +13:00
$dbForProject -> purgeCachedDocument ( 'users' , $user -> getId ());
2022-06-08 21:00:38 +12:00
2023-03-14 22:07:42 +13:00
$message = Template :: fromFile ( __DIR__ . '/../../config/locale/templates/sms-base.tpl' );
2023-04-19 20:44:22 +12:00
2023-04-19 20:29:29 +12:00
$customTemplate = $project -> getAttribute ( 'templates' , [])[ 'sms.login-' . $locale -> default ] ? ? [];
2023-04-19 20:44:22 +12:00
if ( ! empty ( $customTemplate )) {
2023-07-18 19:05:09 +12:00
$message = $customTemplate [ 'message' ] ? ? $message ;
2023-04-19 20:29:29 +12:00
}
2024-01-12 01:50:01 +13:00
$messageContent = Template :: fromString ( $locale -> getText ( " sms.verification.body " ));
$messageContent
-> setParam ( '{{project}}' , $project -> getAttribute ( 'name' ))
-> setParam ( '{{secret}}' , $secret );
2024-01-12 05:28:21 +13:00
$messageContent = \strip_tags ( $messageContent -> render ());
$message = $message -> setParam ( '{{token}}' , $messageContent );
2023-03-14 22:07:42 +13:00
$message = $message -> render ();
2023-09-21 03:21:03 +12:00
2023-11-16 09:00:47 +13:00
$messageDoc = new Document ([
2023-09-22 03:47:15 +12:00
'$id' => $token -> getId (),
2023-09-06 05:10:48 +12:00
'data' => [
'content' => $message ,
],
2023-11-16 09:00:47 +13:00
]);
2022-06-08 21:00:38 +12:00
2022-12-21 05:11:30 +13:00
$queueForMessaging
2023-11-16 09:00:47 +13:00
-> setMessage ( $messageDoc )
-> setRecipients ([ $phone ])
2023-11-29 22:52:26 +13:00
-> setProviderType ( MESSAGE_TYPE_SMS )
2023-10-06 00:27:48 +13:00
-> trigger ();
2023-09-06 05:40:33 +12:00
2022-12-21 05:11:30 +13:00
$queueForEvents -> setPayload (
2022-06-08 21:00:38 +12:00
$response -> output (
$token -> setAttribute ( 'secret' , $secret ),
Response :: MODEL_TOKEN
)
);
// Hide secret for clients
2023-12-20 04:45:44 +13:00
$token -> setAttribute ( 'secret' , ( $isPrivilegedUser || $isAppUser ) ? Auth :: encodeSession ( $user -> getId (), $secret ) : '' );
2022-06-08 21:00:38 +12:00
$response
-> setStatusCode ( Response :: STATUS_CODE_CREATED )
-> dynamic ( $token , Response :: MODEL_TOKEN )
;
});
2021-02-17 02:46:30 +13:00
App :: post ( '/v1/account/sessions/anonymous' )
2023-08-02 03:26:48 +12:00
-> desc ( 'Create anonymous session' )
2022-12-11 21:33:52 +13:00
-> groups ([ 'api' , 'account' , 'auth' , 'session' ])
2022-04-04 18:30:07 +12:00
-> label ( 'event' , 'users.[userId].sessions.[sessionId].create' )
2024-01-18 00:17:03 +13:00
-> label ( 'scope' , 'sessions.write' )
2021-04-03 21:56:32 +13:00
-> label ( 'auth.type' , 'anonymous' )
2022-09-05 20:00:08 +12:00
-> label ( 'audits.event' , 'session.create' )
2022-08-12 01:19:05 +12:00
-> label ( 'audits.resource' , 'user/{response.userId}' )
2022-08-16 21:00:28 +12:00
-> label ( 'audits.userId' , '{response.userId}' )
2021-04-16 19:22:17 +12:00
-> label ( 'sdk.auth' , [])
2021-02-17 02:46:30 +13:00
-> label ( 'sdk.namespace' , 'account' )
2021-02-19 03:52:27 +13:00
-> label ( 'sdk.method' , 'createAnonymousSession' )
-> label ( 'sdk.description' , '/docs/references/account/create-session-anonymous.md' )
2021-02-17 02:46:30 +13:00
-> 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' )
2021-02-24 11:43:05 +13:00
-> inject ( 'project' )
2021-12-28 01:45:23 +13:00
-> inject ( 'dbForProject' )
2021-02-17 02:46:30 +13:00
-> inject ( 'geodb' )
2022-12-21 05:11:30 +13:00
-> inject ( 'queueForEvents' )
-> action ( function ( Request $request , Response $response , Locale $locale , Document $user , Document $project , Database $dbForProject , Reader $geodb , Event $queueForEvents ) {
2021-02-17 02:46:30 +13:00
$protocol = $request -> getProtocol ();
2023-10-14 04:10:55 +13:00
$roles = Authorization :: getRoles ();
$isPrivilegedUser = Auth :: isPrivilegedUser ( $roles );
$isAppUser = Auth :: isAppUser ( $roles );
2021-02-17 02:46:30 +13:00
2021-04-22 02:54:05 +12:00
if ( 'console' === $project -> getId ()) {
2022-08-16 18:59:03 +12:00
throw new Exception ( Exception :: USER_ANONYMOUS_CONSOLE_PROHIBITED , 'Failed to create anonymous user' );
2021-02-17 02:46:30 +13:00
}
2021-06-12 08:39:00 +12:00
if ( ! $user -> isEmpty ()) {
2022-08-16 18:59:03 +12:00
throw new Exception ( Exception :: USER_SESSION_ALREADY_EXISTS , 'Cannot create an anonymous user when logged in' );
2021-04-22 02:54:05 +12:00
}
2021-08-06 20:34:17 +12:00
$limit = $project -> getAttribute ( 'auths' , [])[ 'limit' ] ? ? 0 ;
2021-04-03 21:56:32 +13:00
if ( $limit !== 0 ) {
2022-05-16 21:58:17 +12:00
$total = $dbForProject -> count ( 'users' , max : APP_LIMIT_USERS );
2021-04-03 21:56:32 +13:00
2022-02-27 22:57:09 +13:00
if ( $total >= $limit ) {
2022-08-16 18:59:03 +12:00
throw new Exception ( Exception :: USER_COUNT_EXCEEDED );
2021-04-03 21:56:32 +13:00
}
}
2022-08-15 02:22:38 +12:00
$userId = ID :: unique ();
2023-07-07 12:12:39 +12:00
$user -> setAttributes ([
2022-08-15 02:22:38 +12:00
'$id' => $userId ,
2022-08-02 21:21:53 +12:00
'$permissions' => [
2022-08-14 17:21:11 +12:00
Permission :: read ( Role :: any ()),
2022-08-15 02:22:38 +12:00
Permission :: update ( Role :: user ( $userId )),
Permission :: delete ( Role :: user ( $userId )),
2022-08-02 21:21:53 +12:00
],
2021-05-10 08:34:32 +12:00
'email' => null ,
'emailVerification' => false ,
2021-07-14 23:02:12 +12:00
'status' => true ,
2021-05-10 08:34:32 +12:00
'password' => null ,
2022-05-05 02:37:37 +12:00
'hash' => Auth :: DEFAULT_ALGO ,
'hashOptions' => Auth :: DEFAULT_ALGO_OPTIONS ,
2022-07-04 21:55:11 +12:00
'passwordUpdate' => null ,
2022-07-14 02:02:49 +12:00
'registration' => DateTime :: now (),
2021-05-10 08:34:32 +12:00
'reset' => false ,
'name' => null ,
2021-12-28 23:48:50 +13:00
'prefs' => new \stdClass (),
2022-04-26 22:36:49 +12:00
'sessions' => null ,
2022-04-27 23:06:53 +12:00
'tokens' => null ,
2022-04-28 00:44:47 +12:00
'memberships' => null ,
2023-07-07 12:12:39 +12:00
'search' => $userId ,
2023-08-23 13:34:23 +12:00
'accessedAt' => DateTime :: now (),
2023-07-07 12:12:39 +12:00
]);
2023-09-14 07:18:50 +12:00
$user -> removeAttribute ( '$internalId' );
2023-07-07 12:12:39 +12:00
Authorization :: skip ( fn () => $dbForProject -> createDocument ( 'users' , $user ));
2021-02-17 02:46:30 +13:00
2021-02-17 03:16:09 +13:00
// Create session token
2022-11-14 22:42:18 +13:00
$duration = $project -> getAttribute ( 'auths' , [])[ 'duration' ] ? ? Auth :: TOKEN_EXPIRATION_LOGIN_LONG ;
2021-02-17 02:46:30 +13:00
$detector = new Detector ( $request -> getUserAgent ( 'UNKNOWN' ));
$record = $geodb -> get ( $request -> getIP ());
2024-01-18 00:03:04 +13:00
$secret = Auth :: tokenGenerator ( Auth :: TOKEN_LENGTH_SESSION );
2022-07-05 22:59:03 +12:00
2021-02-17 02:46:30 +13:00
$session = new Document ( array_merge (
[
2022-08-15 02:22:38 +12:00
'$id' => ID :: unique (),
2021-06-13 08:44:25 +12:00
'userId' => $user -> getId (),
2022-06-07 21:37:09 +12:00
'userInternalId' => $user -> getInternalId (),
2021-03-29 22:16:56 +13:00
'provider' => Auth :: SESSION_PROVIDER_ANONYMOUS ,
2021-02-17 02:46:30 +13:00
'secret' => Auth :: hash ( $secret ), // One way hash encryption to protect DB leak
'userAgent' => $request -> getUserAgent ( 'UNKNOWN' ),
'ip' => $request -> getIP (),
'countryCode' => ( $record ) ? \strtolower ( $record [ 'country' ][ 'iso_code' ]) : '--' ,
2024-01-16 02:43:21 +13:00
'expire' => DateTime :: addSeconds ( new \DateTime (), $duration )
2021-02-17 02:46:30 +13:00
],
$detector -> getOS (),
$detector -> getClient (),
$detector -> getDevice ()
));
2022-08-19 16:04:33 +12:00
Authorization :: setRole ( Role :: user ( $user -> getId ()) -> toString ());
2021-02-17 02:46:30 +13:00
2022-08-03 17:43:03 +12:00
$session = $dbForProject -> createDocument ( 'sessions' , $session -> setAttribute ( '$permissions' , [
2022-08-15 23:24:31 +12:00
Permission :: read ( Role :: user ( $user -> getId ())),
Permission :: update ( Role :: user ( $user -> getId ())),
Permission :: delete ( Role :: user ( $user -> getId ())),
2022-08-02 21:21:53 +12:00
]));
2021-07-17 22:04:43 +12:00
2023-12-15 02:32:06 +13:00
$dbForProject -> purgeCachedDocument ( 'users' , $user -> getId ());
2021-02-17 02:46:30 +13:00
2022-12-21 05:11:30 +13:00
$queueForEvents
2022-04-04 18:30:07 +12:00
-> setParam ( 'userId' , $user -> getId ())
-> setParam ( 'sessionId' , $session -> getId ())
;
2021-02-17 02:46:30 +13:00
if ( ! Config :: getParam ( 'domainVerification' )) {
2022-04-19 21:30:42 +12:00
$response -> addHeader ( 'X-Fallback-Cookies' , \json_encode ([ Auth :: $cookieName => Auth :: encodeSession ( $user -> getId (), $secret )]));
2021-02-17 02:46:30 +13:00
}
2024-01-18 02:20:47 +13:00
$expire = DateTime :: formatTz ( DateTime :: addSeconds ( new \DateTime (), $duration ));
2021-02-17 02:46:30 +13:00
$response
2022-07-13 01:32:39 +12:00
-> addCookie ( Auth :: $cookieName . '_legacy' , Auth :: encodeSession ( $user -> getId (), $secret ), ( new \DateTime ( $expire )) -> getTimestamp (), '/' , Config :: getParam ( 'cookieDomain' ), ( 'https' == $protocol ), true , null )
-> addCookie ( Auth :: $cookieName , Auth :: encodeSession ( $user -> getId (), $secret ), ( new \DateTime ( $expire )) -> getTimestamp (), '/' , Config :: getParam ( 'cookieDomain' ), ( 'https' == $protocol ), true , Config :: getParam ( 'cookieSamesite' ))
2021-02-17 02:46:30 +13:00
-> setStatusCode ( Response :: STATUS_CODE_CREATED )
;
2022-05-24 02:54:50 +12:00
$countryName = $locale -> getText ( 'countries.' . strtolower ( $session -> getAttribute ( 'countryCode' )), $locale -> getText ( 'locale.country.unknown' ));
2021-06-17 21:33:57 +12:00
2021-02-17 02:46:30 +13:00
$session
-> setAttribute ( 'current' , true )
2021-06-17 21:33:57 +12:00
-> setAttribute ( 'countryName' , $countryName )
2023-12-20 04:45:44 +13:00
-> setAttribute ( 'secret' , ( $isPrivilegedUser || $isAppUser ) ? Auth :: encodeSession ( $user -> getId (), $secret ) : '' )
2021-02-17 02:46:30 +13:00
;
2021-07-26 02:47:18 +12:00
$response -> dynamic ( $session , Response :: MODEL_SESSION );
2021-02-17 02:46:30 +13:00
});
2020-12-29 09:31:55 +13:00
App :: post ( '/v1/account/jwt' )
2022-11-04 04:24:32 +13:00
-> desc ( 'Create JWT' )
2021-03-01 07:36:13 +13:00
-> groups ([ 'api' , 'account' , 'auth' ])
2024-01-18 00:17:03 +13:00
-> label ( 'scope' , 'accounts.write' )
2021-03-01 07:36:13 +13:00
-> label ( 'auth.type' , 'jwt' )
2023-12-12 05:24:24 +13:00
-> label ( 'sdk.auth' , [])
2020-10-18 06:49:09 +13:00
-> label ( 'sdk.namespace' , 'account' )
-> label ( 'sdk.method' , 'createJWT' )
-> label ( 'sdk.description' , '/docs/references/account/create-jwt.md' )
2021-05-20 20:52:19 +12:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_CREATED )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
-> label ( 'sdk.response.model' , Response :: MODEL_JWT )
2022-06-07 08:57:37 +12:00
-> label ( 'abuse-limit' , 100 )
2021-07-27 23:07:39 +12:00
-> label ( 'abuse-key' , 'url:{url},userId:{userId}' )
2020-12-29 06:03:27 +13:00
-> inject ( 'response' )
-> inject ( 'user' )
2022-04-04 21:59:32 +12:00
-> inject ( 'dbForProject' )
2022-05-19 04:14:21 +12:00
-> action ( function ( Response $response , Document $user , Database $dbForProject ) {
2021-08-05 17:06:38 +12:00
2020-10-18 06:49:09 +13:00
2022-04-26 20:52:59 +12:00
$sessions = $user -> getAttribute ( 'sessions' , []);
$current = new Document ();
foreach ( $sessions as $session ) { /** @var Utopia\Database\Document $session */
if ( $session -> getAttribute ( 'secret' ) == Auth :: hash ( Auth :: $secret )) { // If current session delete the cookies too
$current = $session ;
}
}
if ( $current -> isEmpty ()) {
2022-08-16 18:59:03 +12:00
throw new Exception ( Exception :: USER_SESSION_NOT_FOUND );
2020-12-29 06:03:27 +13:00
}
2021-08-05 17:06:38 +12:00
2020-12-29 10:23:09 +13:00
$jwt = new JWT ( App :: getEnv ( '_APP_OPENSSL_KEY_V1' ), 'HS256' , 900 , 10 ); // Instantiate with key, algo, maxAge and leeway.
2020-12-29 06:03:27 +13:00
2022-09-07 23:02:36 +12:00
$response
-> setStatusCode ( Response :: STATUS_CODE_CREATED )
-> dynamic ( new Document ([ 'jwt' => $jwt -> encode ([
2021-05-07 10:31:05 +12:00
// 'uid' => 1,
// 'aud' => 'http://site.com',
// 'scopes' => ['user'],
// 'iss' => 'http://api.mysite.com',
'userId' => $user -> getId (),
'sessionId' => $current -> getId (),
])]), Response :: MODEL_JWT );
2020-12-29 06:03:27 +13:00
});
2020-01-06 00:29:42 +13:00
2023-11-16 23:56:36 +13:00
App :: post ( '/v1/account/targets/push' )
2023-11-17 00:17:36 +13:00
-> desc ( 'Create Account\'s push target' )
2023-11-16 09:42:06 +13:00
-> groups ([ 'api' , 'account' ])
2024-01-19 02:04:54 +13:00
-> label ( 'scope' , 'account' )
2023-11-16 09:42:06 +13:00
-> label ( 'audits.event' , 'target.create' )
-> label ( 'audits.resource' , 'target/response.$id' )
-> label ( 'event' , 'users.[userId].targets.[targetId].create' )
2023-11-16 23:56:36 +13:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_SESSION ])
-> label ( 'sdk.namespace' , 'account' )
2023-11-17 00:17:36 +13:00
-> label ( 'sdk.method' , 'createPushTarget' )
2023-11-16 23:56:36 +13:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_CREATED )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
-> label ( 'sdk.response.model' , Response :: MODEL_TARGET )
2023-11-16 09:42:06 +13:00
-> param ( 'targetId' , '' , new CustomId (), 'Target ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can\'t start with a special char. Max length is 36 chars.' )
-> param ( 'identifier' , '' , new Text ( Database :: LENGTH_KEY ), 'The target identifier (token, email, phone etc.)' )
2024-01-18 01:50:09 +13:00
-> param ( 'providerId' , '' , new UID (), 'Provider ID. Message will be sent to this target from the specified provider ID. If no provider ID is set the first setup provider will be used.' , true )
2023-11-16 09:42:06 +13:00
-> inject ( 'queueForEvents' )
-> inject ( 'user' )
-> inject ( 'request' )
-> inject ( 'response' )
-> inject ( 'dbForProject' )
2023-11-16 23:56:36 +13:00
-> action ( function ( string $targetId , string $providerId , string $identifier , Event $queueForEvents , Document $user , Request $request , Response $response , Database $dbForProject ) {
2023-11-16 09:42:06 +13:00
$targetId = $targetId == 'unique()' ? ID :: unique () : $targetId ;
2023-11-16 23:56:36 +13:00
$provider = Authorization :: skip ( fn () => $dbForProject -> getDocument ( 'providers' , $providerId ));
2023-11-16 09:42:06 +13:00
if ( $user -> isEmpty ()) {
throw new Exception ( Exception :: USER_NOT_FOUND );
}
$target = Authorization :: skip ( fn () => $dbForProject -> getDocument ( 'targets' , $targetId ));
if ( ! $target -> isEmpty ()) {
throw new Exception ( Exception :: USER_TARGET_ALREADY_EXISTS );
}
$detector = new Detector ( $request -> getUserAgent ());
$detector -> skipBotDetection (); // OPTIONAL: If called, bot detection will completely be skipped (bots will be detected as regular devices then)
$device = $detector -> getDevice ();
try {
$target = $dbForProject -> createDocument ( 'targets' , new Document ([
'$id' => $targetId ,
'$permissions' => [
Permission :: read ( Role :: user ( $user -> getId ())),
Permission :: update ( Role :: user ( $user -> getId ())),
],
2024-01-18 20:55:40 +13:00
'providerId' => ! empty ( $providerId ) ? $providerId : null ,
'providerInternalId' => ! empty ( $providerId ) ? $provider -> getInternalId () : null ,
2023-11-29 17:05:37 +13:00
'providerType' => MESSAGE_TYPE_PUSH ,
2023-11-16 09:42:06 +13:00
'userId' => $user -> getId (),
'userInternalId' => $user -> getInternalId (),
'identifier' => $identifier ,
2023-11-17 00:17:36 +13:00
'name' => " { $device [ 'deviceBrand' ] } { $device [ 'deviceModel' ] } "
2023-11-16 09:42:06 +13:00
]));
} catch ( Duplicate ) {
throw new Exception ( Exception :: USER_TARGET_ALREADY_EXISTS );
}
2023-12-15 02:32:06 +13:00
$dbForProject -> purgeCachedDocument ( 'users' , $user -> getId ());
2023-11-16 09:42:06 +13:00
$queueForEvents
-> setParam ( 'userId' , $user -> getId ())
-> setParam ( 'targetId' , $target -> getId ());
$response
2023-11-16 23:56:36 +13:00
-> setStatusCode ( Response :: STATUS_CODE_CREATED )
2023-11-16 09:42:06 +13:00
-> dynamic ( $target , Response :: MODEL_TARGET );
});
2020-06-29 05:31:21 +12:00
App :: get ( '/v1/account' )
2023-08-02 03:26:48 +12:00
-> desc ( 'Get account' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2024-01-18 00:17:03 +13:00
-> label ( 'scope' , 'accounts.read' )
2023-08-21 00:29:43 +12:00
-> label ( 'usage.metric' , 'users.{scope}.requests.read' )
2021-04-16 19:22:17 +12:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_SESSION , APP_AUTH_TYPE_JWT ])
2020-02-01 11:34:07 +13:00
-> label ( 'sdk.namespace' , 'account' )
-> label ( 'sdk.method' , 'get' )
-> label ( 'sdk.description' , '/docs/references/account/get.md' )
2020-11-12 10:02:24 +13:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_OK )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
2023-02-15 13:10:54 +13:00
-> label ( 'sdk.response.model' , Response :: MODEL_USER )
2023-02-10 14:06:33 +13:00
-> label ( 'sdk.offline.model' , '/account' )
-> label ( 'sdk.offline.key' , 'current' )
2020-12-27 07:11:18 +13:00
-> inject ( 'response' )
-> inject ( 'user' )
2022-08-10 20:45:10 +12:00
-> action ( function ( Response $response , Document $user ) {
2024-02-01 23:41:41 +13:00
if ( $user -> isEmpty ()) {
throw new Exception ( Exception :: USER_NOT_FOUND );
}
2022-04-19 21:30:42 +12:00
2022-05-06 20:58:36 +12:00
$response -> dynamic ( $user , Response :: MODEL_ACCOUNT );
2020-12-27 03:31:53 +13:00
});
2020-02-01 11:34:07 +13:00
2020-06-29 05:31:21 +12:00
App :: get ( '/v1/account/prefs' )
2023-08-02 03:26:48 +12:00
-> desc ( 'Get account preferences' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2024-01-18 00:17:03 +13:00
-> label ( 'scope' , 'accounts.read' )
2023-08-21 00:29:43 +12:00
-> label ( 'usage.metric' , 'users.{scope}.requests.read' )
2021-04-16 19:22:17 +12:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_SESSION , APP_AUTH_TYPE_JWT ])
2020-02-01 11:34:07 +13:00
-> label ( 'sdk.namespace' , 'account' )
-> label ( 'sdk.method' , 'getPrefs' )
-> label ( 'sdk.description' , '/docs/references/account/get-prefs.md' )
2020-11-13 00:54:16 +13:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_OK )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
2021-04-22 01:37:51 +12:00
-> label ( 'sdk.response.model' , Response :: MODEL_PREFERENCES )
2023-02-10 14:06:33 +13:00
-> label ( 'sdk.offline.model' , '/account/prefs' )
-> label ( 'sdk.offline.key' , 'current' )
2020-12-27 03:31:53 +13:00
-> inject ( 'response' )
-> inject ( 'user' )
2022-08-10 20:45:10 +12:00
-> action ( function ( Response $response , Document $user ) {
2020-02-01 11:34:07 +13:00
2023-04-13 04:02:43 +12:00
$prefs = $user -> getAttribute ( 'prefs' , []);
2020-06-30 09:43:34 +12:00
2021-07-26 02:47:18 +12:00
$response -> dynamic ( new Document ( $prefs ), Response :: MODEL_PREFERENCES );
2020-12-27 03:31:53 +13:00
});
2020-02-01 11:34:07 +13:00
2020-06-29 05:31:21 +12:00
App :: get ( '/v1/account/sessions' )
2023-08-02 03:26:48 +12:00
-> desc ( 'List sessions' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2024-01-18 00:17:03 +13:00
-> label ( 'scope' , 'accounts.read' )
2023-08-21 00:29:43 +12:00
-> label ( 'usage.metric' , 'users.{scope}.requests.read' )
2021-04-16 19:22:17 +12:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_SESSION , APP_AUTH_TYPE_JWT ])
2020-02-01 11:34:07 +13:00
-> label ( 'sdk.namespace' , 'account' )
2022-09-14 10:13:04 +12:00
-> label ( 'sdk.method' , 'listSessions' )
-> label ( 'sdk.description' , '/docs/references/account/list-sessions.md' )
2020-11-12 10:02:24 +13:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_OK )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
-> label ( 'sdk.response.model' , Response :: MODEL_SESSION_LIST )
2023-02-10 14:06:33 +13:00
-> label ( 'sdk.offline.model' , '/account/sessions' )
2020-12-27 03:31:53 +13:00
-> inject ( 'response' )
-> inject ( 'user' )
-> inject ( 'locale' )
2022-11-04 22:50:59 +13:00
-> inject ( 'project' )
-> action ( function ( Response $response , Document $user , Locale $locale , Document $project ) {
2020-06-30 09:43:34 +12:00
2021-02-20 01:12:47 +13:00
$sessions = $user -> getAttribute ( 'sessions' , []);
2024-01-16 03:37:47 +13:00
$current = Auth :: sessionVerify ( $sessions , Auth :: $secret );
2020-06-30 09:43:34 +12:00
2021-08-05 17:06:38 +12:00
foreach ( $sessions as $key => $session ) { /** @var Document $session */
2022-05-24 02:54:50 +12:00
$countryName = $locale -> getText ( 'countries.' . strtolower ( $session -> getAttribute ( 'countryCode' )), $locale -> getText ( 'locale.country.unknown' ));
2021-06-17 21:08:01 +12:00
$session -> setAttribute ( 'countryName' , $countryName );
2021-02-20 01:12:47 +13:00
$session -> setAttribute ( 'current' , ( $current == $session -> getId ()) ? true : false );
$sessions [ $key ] = $session ;
2020-02-01 11:34:07 +13:00
}
2020-06-30 09:43:34 +12:00
2021-07-26 02:47:18 +12:00
$response -> dynamic ( new Document ([
2021-05-27 22:09:14 +12:00
'sessions' => $sessions ,
2022-02-27 22:57:09 +13:00
'total' => count ( $sessions ),
2020-10-31 08:53:27 +13:00
]), Response :: MODEL_SESSION_LIST );
2020-12-27 03:31:53 +13:00
});
2020-02-01 11:34:07 +13:00
2020-06-29 05:31:21 +12:00
App :: get ( '/v1/account/logs' )
2023-08-02 03:26:48 +12:00
-> desc ( 'List logs' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2024-01-18 00:17:03 +13:00
-> label ( 'scope' , 'accounts.read' )
2023-08-21 00:29:43 +12:00
-> label ( 'usage.metric' , 'users.{scope}.requests.read' )
2021-04-16 19:22:17 +12:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_SESSION , APP_AUTH_TYPE_JWT ])
2020-02-01 11:34:07 +13:00
-> label ( 'sdk.namespace' , 'account' )
2022-09-14 09:05:03 +12:00
-> label ( 'sdk.method' , 'listLogs' )
-> label ( 'sdk.description' , '/docs/references/account/list-logs.md' )
2020-11-12 10:02:24 +13:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_OK )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
-> label ( 'sdk.response.model' , Response :: MODEL_LOG_LIST )
2023-05-17 00:56:20 +12:00
-> param ( 'queries' , [], new Queries ([ new Limit (), new Offset ()]), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Only supported methods are limit and offset' , true )
2020-12-27 03:31:53 +13:00
-> inject ( 'response' )
-> inject ( 'user' )
-> inject ( 'locale' )
-> inject ( 'geodb' )
2021-12-28 01:45:23 +13:00
-> inject ( 'dbForProject' )
2022-08-25 21:59:28 +12:00
-> action ( function ( array $queries , Response $response , Document $user , Locale $locale , Reader $geodb , Database $dbForProject ) {
2020-06-30 09:43:34 +12:00
2022-08-24 01:06:59 +12:00
$queries = Query :: parseQueries ( $queries );
$grouped = Query :: groupByType ( $queries );
2022-08-30 23:55:23 +12:00
$limit = $grouped [ 'limit' ] ? ? APP_LIMIT_COUNT ;
2022-08-24 01:06:59 +12:00
$offset = $grouped [ 'offset' ] ? ? 0 ;
2022-08-24 01:10:27 +12:00
2022-05-26 01:49:32 +12:00
$audit = new EventAudit ( $dbForProject );
2022-04-04 18:30:07 +12:00
2023-07-13 05:56:24 +12:00
$logs = $audit -> getLogsByUser ( $user -> getInternalId (), $limit , $offset );
2020-06-30 09:43:34 +12:00
$output = [];
foreach ( $logs as $i => & $log ) {
$log [ 'userAgent' ] = ( ! empty ( $log [ 'userAgent' ])) ? $log [ 'userAgent' ] : 'UNKNOWN' ;
2021-02-15 06:28:54 +13:00
$detector = new Detector ( $log [ 'userAgent' ]);
2020-06-30 09:43:34 +12:00
2021-11-18 23:33:42 +13:00
$output [ $i ] = new Document ( array_merge (
$log -> getArrayCopy (),
$log [ 'data' ],
$detector -> getOS (),
$detector -> getClient (),
$detector -> getDevice ()
));
2020-10-31 08:53:27 +13:00
$record = $geodb -> get ( $log [ 'ip' ]);
if ( $record ) {
2022-05-24 02:54:50 +12:00
$output [ $i ][ 'countryCode' ] = $locale -> getText ( 'countries.' . strtolower ( $record [ 'country' ][ 'iso_code' ]), false ) ? \strtolower ( $record [ 'country' ][ 'iso_code' ]) : '--' ;
$output [ $i ][ 'countryName' ] = $locale -> getText ( 'countries.' . strtolower ( $record [ 'country' ][ 'iso_code' ]), $locale -> getText ( 'locale.country.unknown' ));
2020-10-31 08:53:27 +13:00
} else {
$output [ $i ][ 'countryCode' ] = '--' ;
$output [ $i ][ 'countryName' ] = $locale -> getText ( 'locale.country.unknown' );
2020-02-01 11:34:07 +13:00
}
}
2020-06-30 09:43:34 +12:00
2021-11-17 03:54:29 +13:00
$response -> dynamic ( new Document ([
2022-04-04 18:30:07 +12:00
'total' => $audit -> countLogsByUser ( $user -> getId ()),
2021-11-17 03:54:29 +13:00
'logs' => $output ,
]), Response :: MODEL_LOG_LIST );
2020-12-27 03:31:53 +13:00
});
2020-02-01 11:34:07 +13:00
2021-06-16 22:14:08 +12:00
App :: get ( '/v1/account/sessions/:sessionId' )
2023-08-02 03:26:48 +12:00
-> desc ( 'Get session' )
2021-06-16 22:14:08 +12:00
-> groups ([ 'api' , 'account' ])
2024-01-18 00:17:03 +13:00
-> label ( 'scope' , 'accounts.read' )
2023-08-21 00:29:43 +12:00
-> label ( 'usage.metric' , 'users.{scope}.requests.read' )
2021-06-16 22:14:08 +12:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_SESSION , APP_AUTH_TYPE_JWT ])
-> label ( 'sdk.namespace' , 'account' )
2021-06-16 22:48:12 +12:00
-> label ( 'sdk.method' , 'getSession' )
-> label ( 'sdk.description' , '/docs/references/account/get-session.md' )
2021-06-16 22:14:08 +12:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_OK )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
2021-06-16 22:48:12 +12:00
-> label ( 'sdk.response.model' , Response :: MODEL_SESSION )
2023-02-10 14:06:33 +13:00
-> label ( 'sdk.offline.model' , '/account/sessions' )
-> label ( 'sdk.offline.key' , '{sessionId}' )
2022-09-19 22:05:42 +12:00
-> param ( 'sessionId' , '' , new UID (), 'Session ID. Use the string \'current\' to get the current device session.' )
2021-06-16 22:14:08 +12:00
-> inject ( 'response' )
-> inject ( 'user' )
-> inject ( 'locale' )
2021-12-28 01:45:23 +13:00
-> inject ( 'dbForProject' )
2022-11-04 04:03:39 +13:00
-> inject ( 'project' )
-> action ( function ( ? string $sessionId , Response $response , Document $user , Locale $locale , Database $dbForProject , Document $project ) {
2021-06-16 22:14:08 +12:00
2021-08-05 17:06:38 +12:00
$sessions = $user -> getAttribute ( 'sessions' , []);
$sessionId = ( $sessionId === 'current' )
2024-01-16 03:37:47 +13:00
? Auth :: sessionVerify ( $user -> getAttribute ( 'sessions' ), Auth :: $secret )
2022-04-26 00:59:08 +12:00
: $sessionId ;
2021-06-16 22:14:08 +12:00
2021-08-05 17:06:38 +12:00
foreach ( $sessions as $session ) { /** @var Document $session */
2021-07-05 02:14:06 +12:00
if ( $sessionId == $session -> getId ()) {
2022-05-24 02:54:50 +12:00
$countryName = $locale -> getText ( 'countries.' . strtolower ( $session -> getAttribute ( 'countryCode' )), $locale -> getText ( 'locale.country.unknown' ));
2021-06-17 21:33:57 +12:00
2021-07-05 02:14:06 +12:00
$session
-> setAttribute ( 'current' , ( $session -> getAttribute ( 'secret' ) == Auth :: hash ( Auth :: $secret )))
-> setAttribute ( 'countryName' , $countryName )
;
2021-08-05 17:06:38 +12:00
2021-07-26 02:47:18 +12:00
return $response -> dynamic ( $session , Response :: MODEL_SESSION );
2021-07-05 02:14:06 +12:00
}
}
2021-06-16 22:48:12 +12:00
2022-08-16 18:59:03 +12:00
throw new Exception ( Exception :: USER_SESSION_NOT_FOUND );
2021-06-16 22:14:08 +12:00
});
2020-06-29 05:31:21 +12:00
App :: patch ( '/v1/account/name' )
2023-08-02 03:26:48 +12:00
-> desc ( 'Update name' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2022-04-04 18:30:07 +12:00
-> label ( 'event' , 'users.[userId].update.name' )
2024-01-18 00:17:03 +13:00
-> label ( 'scope' , 'accounts.write' )
2022-09-09 01:06:16 +12:00
-> label ( 'audits.event' , 'user.update' )
2022-08-17 19:05:37 +12:00
-> label ( 'audits.resource' , 'user/{response.$id}' )
2021-04-16 19:22:17 +12:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_SESSION , APP_AUTH_TYPE_JWT ])
2019-05-09 18:54:39 +12:00
-> label ( 'sdk.namespace' , 'account' )
2020-01-31 05:18:46 +13:00
-> label ( 'sdk.method' , 'updateName' )
2020-01-06 12:22:02 +13:00
-> label ( 'sdk.description' , '/docs/references/account/update-name.md' )
2020-11-12 10:02:24 +13:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_OK )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
2023-02-15 13:10:54 +13:00
-> label ( 'sdk.response.model' , Response :: MODEL_USER )
2023-02-10 14:06:33 +13:00
-> label ( 'sdk.offline.model' , '/account' )
-> label ( 'sdk.offline.key' , 'current' )
2020-09-11 02:40:14 +12:00
-> param ( 'name' , '' , new Text ( 128 ), 'User name. Max length: 128 chars.' )
2023-01-20 13:36:17 +13:00
-> inject ( 'requestTimestamp' )
2020-12-27 03:31:53 +13:00
-> inject ( 'response' )
-> inject ( 'user' )
2021-12-28 01:45:23 +13:00
-> inject ( 'dbForProject' )
2022-12-21 05:11:30 +13:00
-> inject ( 'queueForEvents' )
2023-10-04 05:50:48 +13:00
-> action ( function ( string $name , ? \DateTime $requestTimestamp , Response $response , Document $user , Database $dbForProject , Event $queueForEvents ) {
2020-06-30 09:43:34 +12:00
2023-05-31 08:55:33 +12:00
$user -> setAttribute ( 'name' , $name );
2023-01-20 13:36:17 +13:00
$user = $dbForProject -> withRequestTimestamp ( $requestTimestamp , fn () => $dbForProject -> updateDocument ( 'users' , $user -> getId (), $user ));
2020-06-30 09:43:34 +12:00
2022-12-21 05:11:30 +13:00
$queueForEvents -> setParam ( 'userId' , $user -> getId ());
2021-08-16 20:53:34 +12:00
2022-05-06 20:58:36 +12:00
$response -> dynamic ( $user , Response :: MODEL_ACCOUNT );
2020-12-27 03:31:53 +13:00
});
2019-05-09 18:54:39 +12:00
2020-06-29 05:31:21 +12:00
App :: patch ( '/v1/account/password' )
2023-08-02 03:26:48 +12:00
-> desc ( 'Update password' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2022-04-04 18:30:07 +12:00
-> label ( 'event' , 'users.[userId].update.password' )
2024-01-18 00:17:03 +13:00
-> label ( 'scope' , 'accounts.write' )
2022-09-09 01:06:16 +12:00
-> label ( 'audits.event' , 'user.update' )
2022-08-09 02:32:54 +12:00
-> label ( 'audits.resource' , 'user/{response.$id}' )
2022-08-17 02:56:05 +12:00
-> label ( 'audits.userId' , '{response.$id}' )
2021-04-16 19:22:17 +12:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_SESSION , APP_AUTH_TYPE_JWT ])
2019-05-09 18:54:39 +12:00
-> label ( 'sdk.namespace' , 'account' )
2020-01-31 05:18:46 +13:00
-> label ( 'sdk.method' , 'updatePassword' )
2020-01-06 12:22:02 +13:00
-> label ( 'sdk.description' , '/docs/references/account/update-password.md' )
2020-11-12 10:02:24 +13:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_OK )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
2023-04-11 20:41:24 +12:00
-> label ( 'sdk.response.model' , Response :: MODEL_USER )
2023-02-10 14:06:33 +13:00
-> label ( 'sdk.offline.model' , '/account' )
-> label ( 'sdk.offline.key' , 'current' )
2023-03-09 14:21:24 +13:00
-> param ( 'password' , '' , fn ( $project , $passwordsDictionary ) => new PasswordDictionary ( $passwordsDictionary , $project -> getAttribute ( 'auths' , [])[ 'passwordDictionary' ] ? ? false ), 'New user password. Must be at least 8 chars.' , false , [ 'project' , 'passwordsDictionary' ])
2021-12-11 01:27:11 +13:00
-> param ( 'oldPassword' , '' , new Password (), 'Current user password. Must be at least 8 chars.' , true )
2023-01-20 13:36:17 +13:00
-> inject ( 'requestTimestamp' )
2020-12-27 03:31:53 +13:00
-> inject ( 'response' )
-> inject ( 'user' )
2022-12-16 23:47:08 +13:00
-> inject ( 'project' )
2021-12-28 01:45:23 +13:00
-> inject ( 'dbForProject' )
2022-12-21 05:11:30 +13:00
-> inject ( 'queueForEvents' )
2024-01-05 04:26:15 +13:00
-> inject ( 'hooks' )
-> action ( function ( string $password , string $oldPassword , ? \DateTime $requestTimestamp , Response $response , Document $user , Document $project , Database $dbForProject , Event $queueForEvents , Hooks $hooks ) {
2020-06-30 09:43:34 +12:00
2021-05-05 06:52:46 +12:00
// Check old password only if its an existing user.
2022-08-27 15:17:48 +12:00
if ( ! empty ( $user -> getAttribute ( 'passwordUpdate' )) && ! Auth :: passwordVerify ( $oldPassword , $user -> getAttribute ( 'password' ), $user -> getAttribute ( 'hash' ), $user -> getAttribute ( 'hashOptions' ))) { // Double check user password
2022-08-16 18:59:03 +12:00
throw new Exception ( Exception :: USER_INVALID_CREDENTIALS );
2020-06-30 09:43:34 +12:00
}
2019-05-09 18:54:39 +12:00
2022-12-26 18:52:49 +13:00
$newPassword = Auth :: passwordHash ( $password , Auth :: DEFAULT_ALGO , Auth :: DEFAULT_ALGO_OPTIONS );
2022-12-18 19:27:41 +13:00
$historyLimit = $project -> getAttribute ( 'auths' , [])[ 'passwordHistory' ] ? ? 0 ;
2023-07-20 09:34:27 +12:00
$history = $user -> getAttribute ( 'passwordHistory' , []);
2022-12-18 19:31:14 +13:00
if ( $historyLimit > 0 ) {
2022-12-18 22:08:51 +13:00
$validator = new PasswordHistory ( $history , $user -> getAttribute ( 'hash' ), $user -> getAttribute ( 'hashOptions' ));
if ( ! $validator -> isValid ( $password )) {
2023-04-14 08:20:03 +12:00
throw new Exception ( Exception :: USER_PASSWORD_RECENTLY_USED );
2022-12-16 23:47:08 +13:00
}
2022-12-18 19:27:41 +13:00
2022-12-16 23:47:08 +13:00
$history [] = $newPassword ;
2023-07-20 09:34:27 +12:00
$history = array_slice ( $history , ( count ( $history ) - $historyLimit ), $historyLimit );
2022-12-16 23:22:39 +13:00
}
2023-07-20 10:24:32 +12:00
if ( $project -> getAttribute ( 'auths' , [])[ 'personalDataCheck' ] ? ? false ) {
2023-04-14 08:20:03 +12:00
$personalDataValidator = new PersonalData ( $user -> getId (), $user -> getAttribute ( 'email' ), $user -> getAttribute ( 'name' ), $user -> getAttribute ( 'phone' ));
if ( ! $personalDataValidator -> isValid ( $password )) {
throw new Exception ( Exception :: USER_PASSWORD_PERSONAL_DATA );
}
2022-12-16 23:22:39 +13:00
}
2024-01-06 00:31:38 +13:00
$hooks -> trigger ( 'passwordValidator' , [ $dbForProject , $project , $password , & $user , true ]);
2024-01-05 04:26:15 +13:00
2023-01-20 13:36:17 +13:00
$user
-> setAttribute ( 'password' , $newPassword )
-> setAttribute ( 'passwordHistory' , $history )
-> setAttribute ( 'passwordUpdate' , DateTime :: now ())
-> setAttribute ( 'hash' , Auth :: DEFAULT_ALGO )
-> setAttribute ( 'hashOptions' , Auth :: DEFAULT_ALGO_OPTIONS );
$user = $dbForProject -> withRequestTimestamp ( $requestTimestamp , fn () => $dbForProject -> updateDocument ( 'users' , $user -> getId (), $user ));
2020-06-30 09:43:34 +12:00
2022-12-21 05:11:30 +13:00
$queueForEvents -> setParam ( 'userId' , $user -> getId ());
2022-04-04 18:30:07 +12:00
2022-05-06 20:58:36 +12:00
$response -> dynamic ( $user , Response :: MODEL_ACCOUNT );
2020-12-27 03:31:53 +13:00
});
2019-05-09 18:54:39 +12:00
2020-06-29 05:31:21 +12:00
App :: patch ( '/v1/account/email' )
2023-08-02 03:26:48 +12:00
-> desc ( 'Update email' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2022-04-04 18:30:07 +12:00
-> label ( 'event' , 'users.[userId].update.email' )
2024-01-18 00:17:03 +13:00
-> label ( 'scope' , 'accounts.write' )
2022-09-09 01:06:16 +12:00
-> label ( 'audits.event' , 'user.update' )
2022-08-09 02:32:54 +12:00
-> label ( 'audits.resource' , 'user/{response.$id}' )
2021-04-16 19:22:17 +12:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_SESSION , APP_AUTH_TYPE_JWT ])
2019-05-09 18:54:39 +12:00
-> label ( 'sdk.namespace' , 'account' )
-> label ( 'sdk.method' , 'updateEmail' )
2019-10-08 20:21:54 +13:00
-> label ( 'sdk.description' , '/docs/references/account/update-email.md' )
2020-11-12 10:02:24 +13:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_OK )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
2023-02-15 13:10:54 +13:00
-> label ( 'sdk.response.model' , Response :: MODEL_USER )
2023-02-10 14:06:33 +13:00
-> label ( 'sdk.offline.model' , '/account' )
-> label ( 'sdk.offline.key' , 'current' )
2020-09-11 02:40:14 +12:00
-> param ( 'email' , '' , new Email (), 'User email.' )
2021-11-26 09:07:54 +13:00
-> param ( 'password' , '' , new Password (), 'User password. Must be at least 8 chars.' )
2023-01-20 13:36:17 +13:00
-> inject ( 'requestTimestamp' )
2020-12-27 03:31:53 +13:00
-> inject ( 'response' )
-> inject ( 'user' )
2021-12-28 01:45:23 +13:00
-> inject ( 'dbForProject' )
2022-12-21 05:11:30 +13:00
-> inject ( 'queueForEvents' )
2024-01-06 00:31:38 +13:00
-> inject ( 'project' )
-> inject ( 'hooks' )
-> action ( function ( string $email , string $password , ? \DateTime $requestTimestamp , Response $response , Document $user , Database $dbForProject , Event $queueForEvents , Document $project , Hooks $hooks ) {
2023-05-26 09:16:19 +12:00
// passwordUpdate will be empty if the user has never set a password
$passwordUpdate = $user -> getAttribute ( 'passwordUpdate' );
2021-02-17 02:46:30 +13:00
if (
2023-05-26 09:16:19 +12:00
! empty ( $passwordUpdate ) &&
2022-05-05 23:21:31 +12:00
! Auth :: passwordVerify ( $password , $user -> getAttribute ( 'password' ), $user -> getAttribute ( 'hash' ), $user -> getAttribute ( 'hashOptions' ))
2021-02-17 02:46:30 +13:00
) { // Double check user password
2022-08-16 18:59:03 +12:00
throw new Exception ( Exception :: USER_INVALID_CREDENTIALS );
2020-06-30 09:43:34 +12:00
}
2019-07-21 23:43:06 +12:00
2024-01-06 00:31:38 +13:00
$hooks -> trigger ( 'passwordValidator' , [ $dbForProject , $project , $password , & $user , false ]);
2023-11-15 06:16:20 +13:00
$oldEmail = $user -> getAttribute ( 'email' );
2024-01-24 23:24:59 +13:00
2021-06-04 01:03:51 +12:00
$email = \strtolower ( $email );
2019-05-09 18:54:39 +12:00
2023-05-18 13:11:45 +12:00
// Makes sure this email is not already used in another identity
$identityWithMatchingEmail = $dbForProject -> findOne ( 'identities' , [
Query :: equal ( 'providerEmail' , [ $email ]),
Query :: notEqual ( 'userId' , $user -> getId ()),
]);
if ( $identityWithMatchingEmail !== false && ! $identityWithMatchingEmail -> isEmpty ()) {
throw new Exception ( Exception :: USER_EMAIL_ALREADY_EXISTS );
}
2022-06-09 00:50:31 +12:00
$user
-> setAttribute ( 'email' , $email )
-> setAttribute ( 'emailVerification' , false ) // After this user needs to confirm mail again
2023-05-31 08:55:33 +12:00
;
2019-05-09 18:54:39 +12:00
2023-05-26 09:16:19 +12:00
if ( empty ( $passwordUpdate )) {
$user
-> setAttribute ( 'password' , Auth :: passwordHash ( $password , Auth :: DEFAULT_ALGO , Auth :: DEFAULT_ALGO_OPTIONS ))
-> setAttribute ( 'hash' , Auth :: DEFAULT_ALGO )
-> setAttribute ( 'hashOptions' , Auth :: DEFAULT_ALGO_OPTIONS )
-> setAttribute ( 'passwordUpdate' , DateTime :: now ());
}
2023-11-29 02:12:34 +13:00
$target = Authorization :: skip ( fn () => $dbForProject -> findOne ( 'targets' , [
2023-11-15 06:16:20 +13:00
Query :: equal ( 'identifier' , [ $email ]),
2023-11-29 02:12:34 +13:00
]));
2023-11-15 06:16:20 +13:00
2023-11-29 02:12:34 +13:00
if ( $target instanceof Document && ! $target -> isEmpty ()) {
2023-11-15 06:16:20 +13:00
throw new Exception ( Exception :: USER_TARGET_ALREADY_EXISTS );
}
2021-08-30 00:00:25 +12:00
try {
2023-01-20 13:36:17 +13:00
$user = $dbForProject -> withRequestTimestamp ( $requestTimestamp , fn () => $dbForProject -> updateDocument ( 'users' , $user -> getId (), $user ));
2023-11-29 02:12:34 +13:00
/**
* @ var Document $oldTarget
*/
$oldTarget = $user -> find ( 'identifier' , $oldEmail , 'targets' );
if ( $oldTarget instanceof Document && ! $oldTarget -> isEmpty ()) {
Authorization :: skip ( fn () => $dbForProject -> updateDocument ( 'targets' , $oldTarget -> getId (), $oldTarget -> setAttribute ( 'identifier' , $email )));
}
2023-12-15 02:32:06 +13:00
$dbForProject -> purgeCachedDocument ( 'users' , $user -> getId ());
2023-06-16 14:16:19 +12:00
} catch ( Duplicate ) {
2022-08-16 18:59:03 +12:00
throw new Exception ( Exception :: USER_EMAIL_ALREADY_EXISTS );
2021-08-30 00:00:25 +12:00
}
2019-05-09 18:54:39 +12:00
2022-12-21 05:11:30 +13:00
$queueForEvents -> setParam ( 'userId' , $user -> getId ());
2022-04-04 18:30:07 +12:00
2022-05-06 20:58:36 +12:00
$response -> dynamic ( $user , Response :: MODEL_ACCOUNT );
2020-12-27 03:31:53 +13:00
});
2019-05-09 18:54:39 +12:00
2022-06-09 00:50:31 +12:00
App :: patch ( '/v1/account/phone' )
2023-08-02 03:26:48 +12:00
-> desc ( 'Update phone' )
2022-06-09 00:50:31 +12:00
-> groups ([ 'api' , 'account' ])
-> label ( 'event' , 'users.[userId].update.phone' )
2024-01-18 00:17:03 +13:00
-> label ( 'scope' , 'accounts.write' )
2022-09-09 01:06:16 +12:00
-> label ( 'audits.event' , 'user.update' )
2022-08-09 02:32:54 +12:00
-> label ( 'audits.resource' , 'user/{response.$id}' )
2022-06-09 00:50:31 +12:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_SESSION , APP_AUTH_TYPE_JWT ])
-> label ( 'sdk.namespace' , 'account' )
-> label ( 'sdk.method' , 'updatePhone' )
-> label ( 'sdk.description' , '/docs/references/account/update-phone.md' )
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_OK )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
2023-02-15 13:10:54 +13:00
-> label ( 'sdk.response.model' , Response :: MODEL_USER )
2023-02-10 14:06:33 +13:00
-> label ( 'sdk.offline.model' , '/account' )
-> label ( 'sdk.offline.key' , 'current' )
2022-08-15 03:10:12 +12:00
-> param ( 'phone' , '' , new Phone (), 'Phone number. Format this number with a leading \'+\' and a country code, e.g., +16175551212.' )
2022-06-09 00:50:31 +12:00
-> param ( 'password' , '' , new Password (), 'User password. Must be at least 8 chars.' )
2023-01-20 13:36:17 +13:00
-> inject ( 'requestTimestamp' )
2022-06-09 00:50:31 +12:00
-> inject ( 'response' )
-> inject ( 'user' )
-> inject ( 'dbForProject' )
2022-12-21 05:11:30 +13:00
-> inject ( 'queueForEvents' )
2024-01-06 00:31:38 +13:00
-> inject ( 'project' )
-> inject ( 'hooks' )
-> action ( function ( string $phone , string $password , ? \DateTime $requestTimestamp , Response $response , Document $user , Database $dbForProject , Event $queueForEvents , Document $project , Hooks $hooks ) {
2023-05-26 09:16:19 +12:00
// passwordUpdate will be empty if the user has never set a password
$passwordUpdate = $user -> getAttribute ( 'passwordUpdate' );
2022-06-09 00:50:31 +12:00
if (
2023-05-26 09:16:19 +12:00
! empty ( $passwordUpdate ) &&
2022-06-22 20:00:12 +12:00
! Auth :: passwordVerify ( $password , $user -> getAttribute ( 'password' ), $user -> getAttribute ( 'hash' ), $user -> getAttribute ( 'hashOptions' ))
2022-06-09 00:50:31 +12:00
) { // Double check user password
2022-08-16 18:59:03 +12:00
throw new Exception ( Exception :: USER_INVALID_CREDENTIALS );
2022-06-09 00:50:31 +12:00
}
2024-01-06 00:31:38 +13:00
$hooks -> trigger ( 'passwordValidator' , [ $dbForProject , $project , $password , & $user , false ]);
2023-11-29 02:12:34 +13:00
$target = Authorization :: skip ( fn () => $dbForProject -> findOne ( 'targets' , [
2023-11-15 06:16:20 +13:00
Query :: equal ( 'identifier' , [ $phone ]),
2023-11-29 02:12:34 +13:00
]));
2023-11-15 06:16:20 +13:00
2023-11-29 02:12:34 +13:00
if ( $target instanceof Document && ! $target -> isEmpty ()) {
2023-11-15 06:16:20 +13:00
throw new Exception ( Exception :: USER_TARGET_ALREADY_EXISTS );
}
2023-11-29 02:12:34 +13:00
$oldPhone = $user -> getAttribute ( 'phone' );
2023-11-15 06:16:20 +13:00
2022-06-09 00:50:31 +12:00
$user
-> setAttribute ( 'phone' , $phone )
-> setAttribute ( 'phoneVerification' , false ) // After this user needs to confirm phone number again
2023-05-31 08:55:33 +12:00
;
2022-06-09 00:50:31 +12:00
2023-06-01 08:52:05 +12:00
if ( empty ( $passwordUpdate )) {
$user
-> setAttribute ( 'password' , Auth :: passwordHash ( $password , Auth :: DEFAULT_ALGO , Auth :: DEFAULT_ALGO_OPTIONS ))
-> setAttribute ( 'hash' , Auth :: DEFAULT_ALGO )
-> setAttribute ( 'hashOptions' , Auth :: DEFAULT_ALGO_OPTIONS )
-> setAttribute ( 'passwordUpdate' , DateTime :: now ());
}
2022-06-09 00:50:31 +12:00
try {
2023-01-20 13:36:17 +13:00
$user = $dbForProject -> withRequestTimestamp ( $requestTimestamp , fn () => $dbForProject -> updateDocument ( 'users' , $user -> getId (), $user ));
2023-11-29 02:12:34 +13:00
/**
* @ var Document $oldTarget
*/
$oldTarget = $user -> find ( 'identifier' , $oldPhone , 'targets' );
if ( $oldTarget instanceof Document && ! $oldTarget -> isEmpty ()) {
Authorization :: skip ( fn () => $dbForProject -> updateDocument ( 'targets' , $oldTarget -> getId (), $oldTarget -> setAttribute ( 'identifier' , $phone )));
}
2023-12-15 02:32:06 +13:00
$dbForProject -> purgeCachedDocument ( 'users' , $user -> getId ());
2022-06-09 00:50:31 +12:00
} catch ( Duplicate $th ) {
2022-08-16 18:59:03 +12:00
throw new Exception ( Exception :: USER_PHONE_ALREADY_EXISTS );
2022-06-09 00:50:31 +12:00
}
2022-12-21 05:11:30 +13:00
$queueForEvents -> setParam ( 'userId' , $user -> getId ());
2022-06-09 00:50:31 +12:00
2022-07-26 00:37:29 +12:00
$response -> dynamic ( $user , Response :: MODEL_ACCOUNT );
2022-06-09 00:50:31 +12:00
});
2020-06-29 05:31:21 +12:00
App :: patch ( '/v1/account/prefs' )
2023-08-02 03:26:48 +12:00
-> desc ( 'Update preferences' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2022-04-04 18:30:07 +12:00
-> label ( 'event' , 'users.[userId].update.prefs' )
2024-01-18 00:17:03 +13:00
-> label ( 'scope' , 'accounts.write' )
2022-09-09 01:06:16 +12:00
-> label ( 'audits.event' , 'user.update' )
2022-08-09 02:32:54 +12:00
-> label ( 'audits.resource' , 'user/{response.$id}' )
2021-04-16 19:22:17 +12:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_SESSION , APP_AUTH_TYPE_JWT ])
2019-05-09 18:54:39 +12:00
-> label ( 'sdk.namespace' , 'account' )
-> label ( 'sdk.method' , 'updatePrefs' )
2019-10-08 20:21:54 +13:00
-> label ( 'sdk.description' , '/docs/references/account/update-prefs.md' )
2020-11-13 00:54:16 +13:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_OK )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
2023-02-15 13:10:54 +13:00
-> label ( 'sdk.response.model' , Response :: MODEL_USER )
2023-02-10 14:06:33 +13:00
-> label ( 'sdk.offline.model' , '/account/prefs' )
-> label ( 'sdk.offline.key' , 'current' )
2020-10-31 08:53:27 +13:00
-> param ( 'prefs' , [], new Assoc (), 'Prefs key-value JSON object.' )
2023-01-20 13:36:17 +13:00
-> inject ( 'requestTimestamp' )
2020-12-27 03:31:53 +13:00
-> inject ( 'response' )
-> inject ( 'user' )
2021-12-28 01:45:23 +13:00
-> inject ( 'dbForProject' )
2022-12-21 05:11:30 +13:00
-> inject ( 'queueForEvents' )
2023-09-28 06:10:21 +13:00
-> action ( function ( array $prefs , ? \DateTime $requestTimestamp , Response $response , Document $user , Database $dbForProject , Event $queueForEvents ) {
2019-05-09 18:54:39 +12:00
2023-01-20 13:36:17 +13:00
$user -> setAttribute ( 'prefs' , $prefs );
2019-05-09 18:54:39 +12:00
2023-01-20 13:36:17 +13:00
$user = $dbForProject -> withRequestTimestamp ( $requestTimestamp , fn () => $dbForProject -> updateDocument ( 'users' , $user -> getId (), $user ));
2019-05-09 18:54:39 +12:00
2022-12-21 05:11:30 +13:00
$queueForEvents -> setParam ( 'userId' , $user -> getId ());
2020-01-12 02:58:02 +13:00
2022-05-06 20:58:36 +12:00
$response -> dynamic ( $user , Response :: MODEL_ACCOUNT );
2020-12-27 03:31:53 +13:00
});
2019-05-09 18:54:39 +12:00
2022-05-16 21:58:17 +12:00
App :: patch ( '/v1/account/status' )
2023-08-02 03:26:48 +12:00
-> desc ( 'Update status' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2022-05-16 21:58:17 +12:00
-> label ( 'event' , 'users.[userId].update.status' )
2024-01-18 00:17:03 +13:00
-> label ( 'scope' , 'accounts.write' )
2022-09-09 01:06:16 +12:00
-> label ( 'audits.event' , 'user.update' )
2022-08-09 02:32:54 +12:00
-> label ( 'audits.resource' , 'user/{response.$id}' )
2021-04-16 19:22:17 +12:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_SESSION , APP_AUTH_TYPE_JWT ])
2019-05-09 18:54:39 +12:00
-> label ( 'sdk.namespace' , 'account' )
2022-05-16 21:58:17 +12:00
-> label ( 'sdk.method' , 'updateStatus' )
-> label ( 'sdk.description' , '/docs/references/account/update-status.md' )
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_OK )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
2023-04-11 20:41:24 +12:00
-> label ( 'sdk.response.model' , Response :: MODEL_USER )
2023-01-20 13:36:17 +13:00
-> inject ( 'requestTimestamp' )
2023-05-20 06:58:17 +12:00
-> inject ( 'request' )
2020-12-27 03:31:53 +13:00
-> inject ( 'response' )
-> inject ( 'user' )
2021-12-28 01:45:23 +13:00
-> inject ( 'dbForProject' )
2022-12-21 05:11:30 +13:00
-> inject ( 'queueForEvents' )
2023-09-28 06:10:21 +13:00
-> action ( function ( ? \DateTime $requestTimestamp , Request $request , Response $response , Document $user , Database $dbForProject , Event $queueForEvents ) {
2020-06-30 09:43:34 +12:00
2023-01-20 13:36:17 +13:00
$user -> setAttribute ( 'status' , false );
2020-06-30 09:43:34 +12:00
2023-01-20 13:36:17 +13:00
$user = $dbForProject -> withRequestTimestamp ( $requestTimestamp , fn () => $dbForProject -> updateDocument ( 'users' , $user -> getId (), $user ));
2021-05-07 10:31:05 +12:00
2022-12-21 05:11:30 +13:00
$queueForEvents
2022-04-04 18:30:07 +12:00
-> setParam ( 'userId' , $user -> getId ())
2022-06-10 20:03:09 +12:00
-> setPayload ( $response -> output ( $user , Response :: MODEL_ACCOUNT ));
2020-06-30 09:43:34 +12:00
if ( ! Config :: getParam ( 'domainVerification' )) {
2022-04-14 00:39:31 +12:00
$response -> addHeader ( 'X-Fallback-Cookies' , \json_encode ([]));
2019-05-09 18:54:39 +12:00
}
2020-06-30 09:43:34 +12:00
2023-05-20 06:58:17 +12:00
$protocol = $request -> getProtocol ();
$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' ))
;
2022-06-10 20:03:09 +12:00
$response -> dynamic ( $user , Response :: MODEL_ACCOUNT );
2020-12-27 03:31:53 +13:00
});
2020-01-06 00:29:42 +13:00
2020-06-29 05:31:21 +12:00
App :: delete ( '/v1/account/sessions/:sessionId' )
2023-08-02 03:26:48 +12:00
-> desc ( 'Delete session' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2024-01-18 00:17:03 +13:00
-> label ( 'scope' , 'accounts.write' )
2022-04-04 18:30:07 +12:00
-> label ( 'event' , 'users.[userId].sessions.[sessionId].delete' )
2022-09-05 20:00:08 +12:00
-> label ( 'audits.event' , 'session.delete' )
2022-08-13 01:21:32 +12:00
-> label ( 'audits.resource' , 'user/{user.$id}' )
2021-04-16 19:22:17 +12:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_SESSION , APP_AUTH_TYPE_JWT ])
2020-01-06 00:29:42 +13:00
-> label ( 'sdk.namespace' , 'account' )
2020-01-31 05:18:46 +13:00
-> label ( 'sdk.method' , 'deleteSession' )
2020-01-06 12:07:41 +13:00
-> label ( 'sdk.description' , '/docs/references/account/delete-session.md' )
2020-11-12 10:02:24 +13:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_NOCONTENT )
-> label ( 'sdk.response.model' , Response :: MODEL_NONE )
2020-01-06 00:29:42 +13:00
-> label ( 'abuse-limit' , 100 )
2022-09-19 22:05:42 +12:00
-> param ( 'sessionId' , '' , new UID (), 'Session ID. Use the string \'current\' to delete the current device session.' )
2023-01-20 13:36:17 +13:00
-> inject ( 'requestTimestamp' )
2020-12-27 03:31:53 +13:00
-> inject ( 'request' )
-> inject ( 'response' )
-> inject ( 'user' )
2021-12-28 01:45:23 +13:00
-> inject ( 'dbForProject' )
2021-06-13 08:44:25 +12:00
-> inject ( 'locale' )
2022-12-21 05:11:30 +13:00
-> inject ( 'queueForEvents' )
2022-11-04 22:50:59 +13:00
-> inject ( 'project' )
2023-10-04 05:50:48 +13:00
-> action ( function ( ? string $sessionId , ? \DateTime $requestTimestamp , Request $request , Response $response , Document $user , Database $dbForProject , Locale $locale , Event $queueForEvents , Document $project ) {
2020-06-30 09:43:34 +12:00
2020-06-30 23:09:28 +12:00
$protocol = $request -> getProtocol ();
2020-06-30 09:43:34 +12:00
$sessionId = ( $sessionId === 'current' )
2024-01-16 03:37:47 +13:00
? Auth :: sessionVerify ( $user -> getAttribute ( 'sessions' ), Auth :: $secret )
2022-02-02 04:54:20 +13:00
: $sessionId ;
2021-08-05 17:06:38 +12:00
2021-02-20 01:12:47 +13:00
$sessions = $user -> getAttribute ( 'sessions' , []);
2020-01-24 11:33:44 +13:00
2021-08-05 17:06:38 +12:00
foreach ( $sessions as $key => $session ) { /** @var Document $session */
2021-05-07 10:31:05 +12:00
if ( $sessionId == $session -> getId ()) {
2023-01-20 13:36:17 +13:00
$dbForProject -> withRequestTimestamp ( $requestTimestamp , function () use ( $dbForProject , $session ) {
return $dbForProject -> deleteDocument ( 'sessions' , $session -> getId ());
});
2020-01-24 11:33:44 +13:00
2023-01-20 13:36:17 +13:00
unset ( $sessions [ $key ]);
2021-07-17 22:04:43 +12:00
2021-02-20 01:12:47 +13:00
$session -> setAttribute ( 'current' , false );
2021-08-05 17:06:38 +12:00
2021-02-20 01:12:47 +13:00
if ( $session -> getAttribute ( 'secret' ) == Auth :: hash ( Auth :: $secret )) { // If current session delete the cookies too
2021-06-13 08:44:25 +12:00
$session
-> setAttribute ( 'current' , true )
2022-05-24 02:54:50 +12:00
-> setAttribute ( 'countryName' , $locale -> getText ( 'countries.' . strtolower ( $session -> getAttribute ( 'countryCode' )), $locale -> getText ( 'locale.country.unknown' )))
2021-06-13 08:44:25 +12:00
;
2021-08-05 17:06:38 +12:00
2021-05-28 18:27:14 +12:00
if ( ! Config :: getParam ( 'domainVerification' )) {
$response
-> addHeader ( 'X-Fallback-Cookies' , \json_encode ([]))
;
}
2020-11-21 10:02:26 +13:00
2020-01-24 11:33:44 +13:00
$response
2021-08-05 17:06:38 +12:00
-> addCookie ( Auth :: $cookieName . '_legacy' , '' , \time () - 3600 , '/' , Config :: getParam ( 'cookieDomain' ), ( 'https' == $protocol ), true , null )
2020-07-01 18:35:57 +12:00
-> addCookie ( Auth :: $cookieName , '' , \time () - 3600 , '/' , Config :: getParam ( 'cookieDomain' ), ( 'https' == $protocol ), true , Config :: getParam ( 'cookieSamesite' ))
2020-01-24 11:33:44 +13:00
;
}
2022-05-24 02:54:50 +12:00
2023-12-15 02:32:06 +13:00
$dbForProject -> purgeCachedDocument ( 'users' , $user -> getId ());
2021-05-07 10:31:05 +12:00
2022-12-21 05:11:30 +13:00
$queueForEvents
2022-04-04 18:30:07 +12:00
-> setParam ( 'userId' , $user -> getId ())
-> setParam ( 'sessionId' , $session -> getId ())
2022-04-14 00:39:31 +12:00
-> setPayload ( $response -> output ( $session , Response :: MODEL_SESSION ))
2020-11-21 10:02:26 +13:00
;
2020-06-30 09:43:34 +12:00
return $response -> noContent ();
}
}
2022-07-27 02:24:32 +12:00
throw new Exception ( Exception :: USER_SESSION_NOT_FOUND );
2020-12-27 03:31:53 +13:00
});
2020-06-30 09:43:34 +12:00
2022-02-03 03:14:17 +13:00
App :: patch ( '/v1/account/sessions/:sessionId' )
2024-01-23 02:20:48 +13:00
-> desc ( 'Update (or renew) a session' )
2022-02-02 04:54:20 +13:00
-> groups ([ 'api' , 'account' ])
2024-01-18 00:17:03 +13:00
-> label ( 'scope' , 'accounts.write' )
2022-04-04 18:30:07 +12:00
-> label ( 'event' , 'users.[userId].sessions.[sessionId].update' )
2022-09-05 20:00:08 +12:00
-> label ( 'audits.event' , 'session.update' )
2022-08-12 01:19:05 +12:00
-> label ( 'audits.resource' , 'user/{response.userId}' )
2022-08-12 23:01:12 +12:00
-> label ( 'audits.userId' , '{response.userId}' )
2022-02-02 04:54:20 +13:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_SESSION , APP_AUTH_TYPE_JWT ])
-> label ( 'sdk.namespace' , 'account' )
2022-02-03 03:14:17 +13:00
-> label ( 'sdk.method' , 'updateSession' )
-> label ( 'sdk.description' , '/docs/references/account/update-session.md' )
2022-02-02 04:54:20 +13:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_OK )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
-> label ( 'sdk.response.model' , Response :: MODEL_SESSION )
-> label ( 'abuse-limit' , 10 )
2022-09-19 22:05:42 +12:00
-> param ( 'sessionId' , '' , new UID (), 'Session ID. Use the string \'current\' to update the current device session.' )
2022-02-02 04:54:20 +13:00
-> inject ( 'response' )
-> inject ( 'user' )
-> inject ( 'dbForProject' )
-> inject ( 'project' )
2022-12-21 05:11:30 +13:00
-> inject ( 'queueForEvents' )
2024-01-22 21:13:46 +13:00
-> action ( function ( ? string $sessionId , Response $response , Document $user , Database $dbForProject , Document $project , Event $queueForEvents ) {
2024-01-16 02:43:21 +13:00
2022-02-02 04:54:20 +13:00
$sessionId = ( $sessionId === 'current' )
2024-01-16 03:37:47 +13:00
? Auth :: sessionVerify ( $user -> getAttribute ( 'sessions' ), Auth :: $secret )
2022-02-02 04:54:20 +13:00
: $sessionId ;
$sessions = $user -> getAttribute ( 'sessions' , []);
2024-01-16 02:43:21 +13:00
$session = null ;
2024-01-23 02:20:48 +13:00
foreach ( $sessions as $key => $value ) {
if ( $sessionId === $value -> getId ()) {
$session = $value ;
2024-01-16 02:43:21 +13:00
break ;
}
}
2022-02-02 04:54:20 +13:00
2024-01-16 02:43:21 +13:00
if ( $session === null ) {
throw new Exception ( Exception :: USER_SESSION_NOT_FOUND );
}
2022-02-02 04:54:20 +13:00
2024-01-16 02:43:21 +13:00
// Extend session
$authDuration = $project -> getAttribute ( 'auths' , [])[ 'duration' ] ? ? Auth :: TOKEN_EXPIRATION_LOGIN_LONG ;
$session -> setAttribute ( 'expire' , DateTime :: addSeconds ( new \DateTime (), $authDuration ));
2022-02-02 04:54:20 +13:00
2024-01-16 02:43:21 +13:00
// Refresh OAuth access token
2024-01-23 00:20:33 +13:00
$provider = $session -> getAttribute ( 'provider' , '' );
$refreshToken = $session -> getAttribute ( 'providerRefreshToken' , '' );
2024-01-22 21:13:46 +13:00
$className = 'Appwrite\\Auth\\OAuth2\\' . \ucfirst ( $provider );
2022-02-02 05:30:49 +13:00
2024-01-23 00:20:33 +13:00
if ( ! empty ( $provider ) && \class_exists ( $className )) {
$appId = $project -> getAttribute ( 'oAuthProviders' , [])[ $provider . 'Appid' ] ? ? '' ;
$appSecret = $project -> getAttribute ( 'oAuthProviders' , [])[ $provider . 'Secret' ] ? ? '{}' ;
2022-02-02 04:54:20 +13:00
2024-01-23 00:20:33 +13:00
$oauth2 = new $className ( $appId , $appSecret , '' , [], []);
$oauth2 -> refreshTokens ( $refreshToken );
2022-11-05 03:48:29 +13:00
2024-01-23 00:20:33 +13:00
$session
-> setAttribute ( 'providerAccessToken' , $oauth2 -> getAccessToken ( '' ))
-> setAttribute ( 'providerRefreshToken' , $oauth2 -> getRefreshToken ( '' ))
-> setAttribute ( 'providerAccessTokenExpiry' , DateTime :: addSeconds ( new \DateTime (), ( int ) $oauth2 -> getAccessTokenExpiry ( '' )));
}
2022-11-04 04:03:39 +13:00
2024-01-22 21:13:46 +13:00
// Save changes
2024-01-16 02:43:21 +13:00
$dbForProject -> updateDocument ( 'sessions' , $sessionId , $session );
2024-01-26 04:44:05 +13:00
$dbForProject -> purgeCachedDocument ( 'users' , $user -> getId ());
2022-02-02 04:54:20 +13:00
2024-01-16 02:43:21 +13:00
$queueForEvents
-> setParam ( 'userId' , $user -> getId ())
-> setParam ( 'sessionId' , $session -> getId ())
-> setPayload ( $response -> output ( $session , Response :: MODEL_SESSION ))
;
2022-02-02 04:54:20 +13:00
2024-01-16 02:43:21 +13:00
return $response -> dynamic ( $session , Response :: MODEL_SESSION );
2022-02-02 04:54:20 +13:00
});
2020-06-30 09:43:34 +12:00
App :: delete ( '/v1/account/sessions' )
2023-08-02 03:26:48 +12:00
-> desc ( 'Delete sessions' )
2020-06-30 09:43:34 +12:00
-> groups ([ 'api' , 'account' ])
2024-01-18 00:17:03 +13:00
-> label ( 'scope' , 'accounts.write' )
2022-04-04 18:30:07 +12:00
-> label ( 'event' , 'users.[userId].sessions.[sessionId].delete' )
2022-09-05 20:00:08 +12:00
-> label ( 'audits.event' , 'session.delete' )
2022-08-13 01:21:32 +12:00
-> label ( 'audits.resource' , 'user/{user.$id}' )
2021-04-16 19:22:17 +12:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_SESSION , APP_AUTH_TYPE_JWT ])
2020-06-30 09:43:34 +12:00
-> label ( 'sdk.namespace' , 'account' )
-> label ( 'sdk.method' , 'deleteSessions' )
-> label ( 'sdk.description' , '/docs/references/account/delete-sessions.md' )
2020-11-12 10:02:24 +13:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_NOCONTENT )
-> label ( 'sdk.response.model' , Response :: MODEL_NONE )
2020-06-30 09:43:34 +12:00
-> label ( 'abuse-limit' , 100 )
2020-12-27 03:31:53 +13:00
-> inject ( 'request' )
-> inject ( 'response' )
-> inject ( 'user' )
2021-12-28 01:45:23 +13:00
-> inject ( 'dbForProject' )
2021-06-13 08:44:25 +12:00
-> inject ( 'locale' )
2022-12-21 05:11:30 +13:00
-> inject ( 'queueForEvents' )
-> action ( function ( Request $request , Response $response , Document $user , Database $dbForProject , Locale $locale , Event $queueForEvents ) {
2020-06-30 09:43:34 +12:00
2020-06-30 23:09:28 +12:00
$protocol = $request -> getProtocol ();
2021-02-20 02:59:36 +13:00
$sessions = $user -> getAttribute ( 'sessions' , []);
2020-06-30 09:43:34 +12:00
2021-08-05 17:06:38 +12:00
foreach ( $sessions as $session ) { /** @var Document $session */
2021-12-28 01:45:23 +13:00
$dbForProject -> deleteDocument ( 'sessions' , $session -> getId ());
2020-06-30 09:43:34 +12:00
if ( ! Config :: getParam ( 'domainVerification' )) {
2022-05-13 07:31:15 +12:00
$response -> addHeader ( 'X-Fallback-Cookies' , \json_encode ([]));
2020-06-30 09:43:34 +12:00
}
2021-06-13 08:44:25 +12:00
$session
-> setAttribute ( 'current' , false )
2022-05-24 02:54:50 +12:00
-> setAttribute ( 'countryName' , $locale -> getText ( 'countries.' . strtolower ( $session -> getAttribute ( 'countryCode' )), $locale -> getText ( 'locale.country.unknown' )))
2021-06-13 08:44:25 +12:00
;
2020-11-21 10:02:26 +13:00
2022-05-13 07:31:15 +12:00
if ( $session -> getAttribute ( 'secret' ) == Auth :: hash ( Auth :: $secret )) {
2021-02-20 02:59:36 +13:00
$session -> setAttribute ( 'current' , true );
2022-05-13 07:31:15 +12:00
// If current session delete the cookies too
2020-06-30 09:43:34 +12:00
$response
2021-08-05 17:06:38 +12:00
-> addCookie ( Auth :: $cookieName . '_legacy' , '' , \time () - 3600 , '/' , Config :: getParam ( 'cookieDomain' ), ( 'https' == $protocol ), true , null )
2022-05-13 07:31:15 +12:00
-> addCookie ( Auth :: $cookieName , '' , \time () - 3600 , '/' , Config :: getParam ( 'cookieDomain' ), ( 'https' == $protocol ), true , Config :: getParam ( 'cookieSamesite' ));
// Use current session for events.
2022-12-21 05:11:30 +13:00
$queueForEvents -> setPayload ( $response -> output ( $session , Response :: MODEL_SESSION ));
2020-06-30 09:43:34 +12:00
}
2020-01-24 11:33:44 +13:00
}
2021-05-07 10:31:05 +12:00
2023-12-15 02:32:06 +13:00
$dbForProject -> purgeCachedDocument ( 'users' , $user -> getId ());
2021-08-05 17:06:38 +12:00
2022-12-21 05:11:30 +13:00
$queueForEvents
2022-04-14 00:39:31 +12:00
-> setParam ( 'userId' , $user -> getId ())
2022-05-13 07:31:15 +12:00
-> setParam ( 'sessionId' , $session -> getId ());
2020-06-30 09:43:34 +12:00
$response -> noContent ();
2020-12-27 03:31:53 +13:00
});
2020-01-24 11:33:44 +13:00
2020-06-29 05:31:21 +12:00
App :: post ( '/v1/account/recovery' )
2023-08-02 03:26:48 +12:00
-> desc ( 'Create password recovery' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2024-01-18 00:17:03 +13:00
-> label ( 'scope' , 'sessions.write' )
2022-04-04 18:30:07 +12:00
-> label ( 'event' , 'users.[userId].recovery.[tokenId].create' )
2022-09-05 20:00:08 +12:00
-> label ( 'audits.event' , 'recovery.create' )
2022-08-12 01:19:05 +12:00
-> label ( 'audits.resource' , 'user/{response.userId}' )
-> label ( 'audits.userId' , '{response.userId}' )
2021-04-16 19:22:17 +12:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_SESSION , APP_AUTH_TYPE_JWT ])
2020-01-06 12:07:41 +13:00
-> label ( 'sdk.namespace' , 'account' )
2020-01-31 05:18:46 +13:00
-> label ( 'sdk.method' , 'createRecovery' )
2020-01-06 12:07:41 +13:00
-> label ( 'sdk.description' , '/docs/references/account/create-recovery.md' )
2020-11-13 11:50:53 +13:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_CREATED )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
-> label ( 'sdk.response.model' , Response :: MODEL_TOKEN )
2020-01-06 12:07:41 +13:00
-> label ( 'abuse-limit' , 10 )
2021-11-09 23:21:24 +13:00
-> label ( 'abuse-key' , [ 'url:{url},email:{param-email}' , 'ip:{ip}' ])
2020-09-11 02:40:14 +12:00
-> param ( 'email' , '' , new Email (), 'User email.' )
2022-05-24 04:34:03 +12:00
-> param ( 'url' , '' , fn ( $clients ) => new Host ( $clients ), 'URL to redirect the user back to your app from the recovery email. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API.' , false , [ 'clients' ])
2020-12-27 03:31:53 +13:00
-> inject ( 'request' )
-> inject ( 'response' )
2023-07-07 12:12:39 +12:00
-> inject ( 'user' )
2021-12-28 01:45:23 +13:00
-> inject ( 'dbForProject' )
2020-12-27 03:31:53 +13:00
-> inject ( 'project' )
-> inject ( 'locale' )
2023-06-12 02:08:48 +12:00
-> inject ( 'queueForMails' )
2022-12-21 05:11:30 +13:00
-> inject ( 'queueForEvents' )
2023-09-28 06:10:21 +13:00
-> action ( function ( string $email , string $url , Request $request , Response $response , Document $user , Database $dbForProject , Document $project , Locale $locale , Mail $queueForMails , Event $queueForEvents ) {
2020-11-21 01:35:16 +13:00
2022-05-24 02:54:50 +12:00
if ( empty ( App :: getEnv ( '_APP_SMTP_HOST' ))) {
2022-08-14 03:15:19 +12:00
throw new Exception ( Exception :: GENERAL_SMTP_DISABLED , 'SMTP Disabled' );
2021-08-31 19:35:04 +12:00
}
2021-12-11 06:52:33 +13:00
$roles = Authorization :: getRoles ();
$isPrivilegedUser = Auth :: isPrivilegedUser ( $roles );
$isAppUser = Auth :: isAppUser ( $roles );
2020-06-30 09:43:34 +12:00
2021-06-04 01:03:51 +12:00
$email = \strtolower ( $email );
2022-05-13 04:25:36 +12:00
$profile = $dbForProject -> findOne ( 'users' , [
2022-08-12 11:53:52 +12:00
Query :: equal ( 'email' , [ $email ]),
2022-05-13 04:25:36 +12:00
]);
2020-06-30 09:43:34 +12:00
2021-05-07 10:31:05 +12:00
if ( ! $profile ) {
2022-07-27 02:24:32 +12:00
throw new Exception ( Exception :: USER_NOT_FOUND );
2020-06-30 09:43:34 +12:00
}
2020-01-12 02:58:02 +13:00
2023-07-07 12:12:39 +12:00
$user -> setAttributes ( $profile -> getArrayCopy ());
2021-07-14 23:02:12 +12:00
if ( false === $profile -> getAttribute ( 'status' )) { // Account is blocked
2022-07-27 02:24:32 +12:00
throw new Exception ( Exception :: USER_BLOCKED );
2020-12-28 00:57:42 +13:00
}
2022-07-14 02:02:49 +12:00
$expire = DateTime :: addSeconds ( new \DateTime (), Auth :: TOKEN_EXPIRATION_RECOVERY );
2021-06-18 00:44:06 +12:00
2024-01-18 00:03:04 +13:00
$secret = Auth :: tokenGenerator ( Auth :: TOKEN_LENGTH_RECOVERY );
2020-06-30 09:43:34 +12:00
$recovery = new Document ([
2022-08-15 02:22:38 +12:00
'$id' => ID :: unique (),
2021-06-13 08:44:25 +12:00
'userId' => $profile -> getId (),
2022-06-07 21:37:09 +12:00
'userInternalId' => $profile -> getInternalId (),
2020-06-30 09:43:34 +12:00
'type' => Auth :: TOKEN_TYPE_RECOVERY ,
2020-11-13 00:54:16 +13:00
'secret' => Auth :: hash ( $secret ), // One way hash encryption to protect DB leak
2021-07-07 00:18:55 +12:00
'expire' => $expire ,
2020-07-04 03:14:51 +12:00
'userAgent' => $request -> getUserAgent ( 'UNKNOWN' ),
2020-06-30 09:43:34 +12:00
'ip' => $request -> getIP (),
]);
2021-08-05 17:06:38 +12:00
2022-08-19 16:04:33 +12:00
Authorization :: setRole ( Role :: user ( $profile -> getId ()) -> toString ());
2020-01-12 02:58:02 +13:00
2022-04-27 23:06:53 +12:00
$recovery = $dbForProject -> createDocument ( 'tokens' , $recovery
2022-08-02 21:21:53 +12:00
-> setAttribute ( '$permissions' , [
2022-08-15 23:24:31 +12:00
Permission :: read ( Role :: user ( $profile -> getId ())),
Permission :: update ( Role :: user ( $profile -> getId ())),
Permission :: delete ( Role :: user ( $profile -> getId ())),
2022-08-02 21:21:53 +12:00
]));
2020-01-06 12:07:41 +13:00
2023-12-15 02:32:06 +13:00
$dbForProject -> purgeCachedDocument ( 'users' , $profile -> getId ());
2020-06-30 09:43:34 +12:00
$url = Template :: parseURL ( $url );
2021-07-07 00:18:55 +12:00
$url [ 'query' ] = Template :: mergeQuery ((( isset ( $url [ 'query' ])) ? $url [ 'query' ] : '' ), [ 'userId' => $profile -> getId (), 'secret' => $secret , 'expire' => $expire ]);
2020-06-30 09:43:34 +12:00
$url = Template :: unParseURL ( $url );
2022-12-15 22:22:05 +13:00
$projectName = $project -> isEmpty () ? 'Console' : $project -> getAttribute ( 'name' , '[APP-NAME]' );
2023-08-28 10:45:37 +12:00
$body = $locale -> getText ( " emails.recovery.body " );
2022-12-15 22:22:05 +13:00
$subject = $locale -> getText ( " emails.recovery.subject " );
2023-04-19 20:29:29 +12:00
$customTemplate = $project -> getAttribute ( 'templates' , [])[ 'email.recovery-' . $locale -> default ] ? ? [];
2023-08-26 03:13:25 +12:00
2023-08-29 21:40:30 +12:00
$message = Template :: fromFile ( __DIR__ . '/../../config/locale/templates/email-inner-base.tpl' );
2023-10-05 12:14:27 +13:00
$message
2024-01-09 06:08:17 +13:00
-> setParam ( '{{body}}' , $body , escapeHtml : false )
2023-10-05 12:14:27 +13:00
-> setParam ( '{{hello}}' , $locale -> getText ( " emails.recovery.hello " ))
-> setParam ( '{{footer}}' , $locale -> getText ( " emails.recovery.footer " ))
-> setParam ( '{{thanks}}' , $locale -> getText ( " emails.recovery.thanks " ))
-> setParam ( '{{signature}}' , $locale -> getText ( " emails.recovery.signature " ));
2023-08-29 21:40:30 +12:00
$body = $message -> render ();
2023-08-29 00:19:37 +12:00
2023-08-29 21:40:30 +12:00
$smtp = $project -> getAttribute ( 'smtp' , []);
$smtpEnabled = $smtp [ 'enabled' ] ? ? false ;
2023-08-29 00:19:37 +12:00
2023-08-29 21:40:30 +12:00
$senderEmail = App :: getEnv ( '_APP_SYSTEM_EMAIL_ADDRESS' , APP_EMAIL_TEAM );
$senderName = App :: getEnv ( '_APP_SYSTEM_EMAIL_NAME' , APP_NAME . ' Server' );
$replyTo = " " ;
if ( $smtpEnabled ) {
if ( ! empty ( $smtp [ 'senderEmail' ])) {
$senderEmail = $smtp [ 'senderEmail' ];
}
if ( ! empty ( $smtp [ 'senderName' ])) {
$senderName = $smtp [ 'senderName' ];
}
if ( ! empty ( $smtp [ 'replyTo' ])) {
$replyTo = $smtp [ 'replyTo' ];
}
2023-08-29 00:19:37 +12:00
2023-09-28 04:51:17 +13:00
$queueForMails
2023-08-26 03:13:25 +12:00
-> setSmtpHost ( $smtp [ 'host' ] ? ? '' )
-> setSmtpPort ( $smtp [ 'port' ] ? ? '' )
-> setSmtpUsername ( $smtp [ 'username' ] ? ? '' )
-> setSmtpPassword ( $smtp [ 'password' ] ? ? '' )
2023-08-29 21:40:30 +12:00
-> setSmtpSecure ( $smtp [ 'secure' ] ? ? '' );
2023-08-29 00:19:37 +12:00
2023-08-30 16:30:44 +12:00
if ( ! empty ( $customTemplate )) {
if ( ! empty ( $customTemplate [ 'senderEmail' ])) {
$senderEmail = $customTemplate [ 'senderEmail' ];
}
if ( ! empty ( $customTemplate [ 'senderName' ])) {
$senderName = $customTemplate [ 'senderName' ];
}
if ( ! empty ( $customTemplate [ 'replyTo' ])) {
$replyTo = $customTemplate [ 'replyTo' ];
}
$body = $customTemplate [ 'message' ] ? ? '' ;
$subject = $customTemplate [ 'subject' ] ? ? $subject ;
2023-08-29 21:40:30 +12:00
}
2023-09-28 04:51:17 +13:00
$queueForMails
2023-08-30 16:30:44 +12:00
-> setSmtpReplyTo ( $replyTo )
-> setSmtpSenderEmail ( $senderEmail )
-> setSmtpSenderName ( $senderName );
2023-04-19 20:29:29 +12:00
}
2023-08-28 10:45:37 +12:00
$emailVariables = [
'direction' => $locale -> getText ( 'settings.direction' ),
2024-01-12 09:36:05 +13:00
/* {{user}}, {{team}}, {{redirect}} and {{project}} are required in default and custom templates */
2023-08-31 09:54:26 +12:00
'user' => $profile -> getAttribute ( 'name' ),
2023-08-31 09:52:55 +12:00
'team' => '' ,
2024-01-12 09:36:05 +13:00
'redirect' => $url ,
2024-01-09 06:08:17 +13:00
'project' => $projectName
2023-08-28 10:45:37 +12:00
];
2022-12-15 22:22:05 +13:00
2023-06-12 02:08:48 +12:00
$queueForMails
2022-04-14 00:39:31 +12:00
-> setRecipient ( $profile -> getAttribute ( 'email' , '' ))
-> setName ( $profile -> getAttribute ( 'name' ))
2022-12-15 22:22:05 +13:00
-> setBody ( $body )
2023-08-28 10:45:37 +12:00
-> setVariables ( $emailVariables )
2022-12-15 22:22:05 +13:00
-> setSubject ( $subject )
2020-06-30 09:43:34 +12:00
-> trigger ();
2022-12-21 05:11:30 +13:00
$queueForEvents
2022-04-14 00:39:31 +12:00
-> setParam ( 'userId' , $profile -> getId ())
-> setParam ( 'tokenId' , $recovery -> getId ())
2022-04-19 04:21:45 +12:00
-> setUser ( $profile )
2022-04-14 00:39:31 +12:00
-> setPayload ( $response -> output (
$recovery -> setAttribute ( 'secret' , $secret ),
Response :: MODEL_TOKEN
))
2020-11-19 08:38:31 +13:00
;
2022-04-19 04:21:45 +12:00
// Hide secret for clients
$recovery -> setAttribute ( 'secret' , ( $isPrivilegedUser || $isAppUser ) ? $secret : '' );
2020-11-19 08:38:31 +13:00
2022-09-07 23:11:10 +12:00
$response
-> setStatusCode ( Response :: STATUS_CODE_CREATED )
-> dynamic ( $recovery , Response :: MODEL_TOKEN );
2020-12-27 03:31:53 +13:00
});
2020-01-06 12:07:41 +13:00
2020-06-29 05:31:21 +12:00
App :: put ( '/v1/account/recovery' )
2023-08-02 03:26:48 +12:00
-> desc ( 'Create password recovery (confirmation)' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2024-01-18 00:17:03 +13:00
-> label ( 'scope' , 'sessions.write' )
2022-04-04 18:30:07 +12:00
-> label ( 'event' , 'users.[userId].recovery.[tokenId].update' )
2022-09-05 20:00:08 +12:00
-> label ( 'audits.event' , 'recovery.update' )
2022-08-12 01:19:05 +12:00
-> label ( 'audits.resource' , 'user/{response.userId}' )
2022-08-12 23:01:12 +12:00
-> label ( 'audits.userId' , '{response.userId}' )
2021-04-16 19:22:17 +12:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_SESSION , APP_AUTH_TYPE_JWT ])
2020-01-06 12:07:41 +13:00
-> label ( 'sdk.namespace' , 'account' )
2020-01-31 05:18:46 +13:00
-> label ( 'sdk.method' , 'updateRecovery' )
2020-01-06 12:07:41 +13:00
-> label ( 'sdk.description' , '/docs/references/account/update-recovery.md' )
2020-11-13 11:50:53 +13:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_OK )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
-> label ( 'sdk.response.model' , Response :: MODEL_TOKEN )
2020-01-06 12:07:41 +13:00
-> label ( 'abuse-limit' , 10 )
-> label ( 'abuse-key' , 'url:{url},userId:{param-userId}' )
2021-12-11 01:27:11 +13:00
-> param ( 'userId' , '' , new UID (), 'User ID.' )
2020-09-11 02:40:14 +12:00
-> param ( 'secret' , '' , new Text ( 256 ), 'Valid reset token.' )
2024-01-02 23:59:35 +13:00
-> param ( 'password' , '' , fn ( $project , $passwordsDictionary ) => new PasswordDictionary ( $passwordsDictionary , $project -> getAttribute ( 'auths' , [])[ 'passwordDictionary' ] ? ? false ), 'New user password. Must be between 8 and 256 chars.' , false , [ 'project' , 'passwordsDictionary' ])
2020-12-27 03:31:53 +13:00
-> inject ( 'response' )
2023-07-07 12:12:39 +12:00
-> inject ( 'user' )
2021-12-28 01:45:23 +13:00
-> inject ( 'dbForProject' )
2023-07-20 09:34:27 +12:00
-> inject ( 'project' )
2022-12-21 05:11:30 +13:00
-> inject ( 'queueForEvents' )
2024-01-06 00:31:38 +13:00
-> inject ( 'hooks' )
2024-01-24 23:24:59 +13:00
-> action ( function ( string $userId , string $secret , string $password , Response $response , Document $user , Database $dbForProject , Document $project , Event $queueForEvents , Hooks $hooks ) {
2021-12-28 01:45:23 +13:00
$profile = $dbForProject -> getDocument ( 'users' , $userId );
2020-01-06 12:07:41 +13:00
2022-05-16 21:58:17 +12:00
if ( $profile -> isEmpty ()) {
2022-07-27 02:24:32 +12:00
throw new Exception ( Exception :: USER_NOT_FOUND );
2020-06-30 09:43:34 +12:00
}
2020-01-06 12:07:41 +13:00
2021-05-07 10:31:05 +12:00
$tokens = $profile -> getAttribute ( 'tokens' , []);
2023-10-05 23:18:19 +13:00
$verifiedToken = Auth :: tokenVerify ( $tokens , Auth :: TOKEN_TYPE_RECOVERY , $secret );
2020-01-06 12:07:41 +13:00
2023-10-05 23:18:19 +13:00
if ( ! $verifiedToken ) {
2022-07-27 02:24:32 +12:00
throw new Exception ( Exception :: USER_INVALID_TOKEN );
2020-06-30 09:43:34 +12:00
}
2020-01-06 12:07:41 +13:00
2022-08-19 16:04:33 +12:00
Authorization :: setRole ( Role :: user ( $profile -> getId ()) -> toString ());
2020-01-06 12:07:41 +13:00
2023-07-20 09:34:27 +12:00
$newPassword = Auth :: passwordHash ( $password , Auth :: DEFAULT_ALGO , Auth :: DEFAULT_ALGO_OPTIONS );
$historyLimit = $project -> getAttribute ( 'auths' , [])[ 'passwordHistory' ] ? ? 0 ;
$history = $profile -> getAttribute ( 'passwordHistory' , []);
if ( $historyLimit > 0 ) {
$validator = new PasswordHistory ( $history , $profile -> getAttribute ( 'hash' ), $profile -> getAttribute ( 'hashOptions' ));
if ( ! $validator -> isValid ( $password )) {
throw new Exception ( Exception :: USER_PASSWORD_RECENTLY_USED );
}
$history [] = $newPassword ;
$history = array_slice ( $history , ( count ( $history ) - $historyLimit ), $historyLimit );
}
2024-01-06 00:31:38 +13:00
$hooks -> trigger ( 'passwordValidator' , [ $dbForProject , $project , $password , & $user , true ]);
2021-12-28 01:45:23 +13:00
$profile = $dbForProject -> updateDocument ( 'users' , $profile -> getId (), $profile
2023-07-20 09:34:27 +12:00
-> setAttribute ( 'password' , $newPassword )
-> setAttribute ( 'passwordHistory' , $history )
2023-02-20 14:51:56 +13:00
-> setAttribute ( 'passwordUpdate' , DateTime :: now ())
2022-06-14 00:53:28 +12:00
-> setAttribute ( 'hash' , Auth :: DEFAULT_ALGO )
-> setAttribute ( 'hashOptions' , Auth :: DEFAULT_ALGO_OPTIONS )
2022-05-24 02:54:50 +12:00
-> setAttribute ( 'emailVerification' , true ));
2020-01-06 12:07:41 +13:00
2023-07-07 12:12:39 +12:00
$user -> setAttributes ( $profile -> getArrayCopy ());
2023-10-05 23:18:19 +13:00
$recoveryDocument = $dbForProject -> getDocument ( 'tokens' , $verifiedToken -> getId ());
2022-04-27 23:06:53 +12:00
2020-06-30 09:43:34 +12:00
/**
2021-08-15 06:56:28 +12:00
* We act like we ' re updating and validating
* the recovery token but actually we don ' t need it anymore .
*/
2023-10-05 23:18:19 +13:00
$dbForProject -> deleteDocument ( 'tokens' , $verifiedToken -> getId ());
2023-12-15 02:32:06 +13:00
$dbForProject -> purgeCachedDocument ( 'users' , $profile -> getId ());
2021-05-07 10:31:05 +12:00
2022-12-21 05:11:30 +13:00
$queueForEvents
2020-06-30 09:43:34 +12:00
-> setParam ( 'userId' , $profile -> getId ())
2022-05-09 03:49:17 +12:00
-> setParam ( 'tokenId' , $recoveryDocument -> getId ())
2020-06-30 09:43:34 +12:00
;
2020-01-06 12:07:41 +13:00
2022-04-27 23:06:53 +12:00
$response -> dynamic ( $recoveryDocument , Response :: MODEL_TOKEN );
2020-12-27 03:31:53 +13:00
});
2020-01-12 13:20:35 +13:00
2020-06-29 05:31:21 +12:00
App :: post ( '/v1/account/verification' )
2023-08-02 03:26:48 +12:00
-> desc ( 'Create email verification' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2024-01-18 00:17:03 +13:00
-> label ( 'scope' , 'accounts.write' )
2022-04-04 18:30:07 +12:00
-> label ( 'event' , 'users.[userId].verification.[tokenId].create' )
2022-09-05 20:00:08 +12:00
-> label ( 'audits.event' , 'verification.create' )
2022-08-12 01:19:05 +12:00
-> label ( 'audits.resource' , 'user/{response.userId}' )
2021-04-16 19:22:17 +12:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_SESSION , APP_AUTH_TYPE_JWT ])
2020-01-12 13:20:35 +13:00
-> label ( 'sdk.namespace' , 'account' )
2020-01-31 05:18:46 +13:00
-> label ( 'sdk.method' , 'createVerification' )
2022-06-21 02:47:49 +12:00
-> label ( 'sdk.description' , '/docs/references/account/create-email-verification.md' )
2020-11-13 11:50:53 +13:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_CREATED )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
-> label ( 'sdk.response.model' , Response :: MODEL_TOKEN )
2020-01-12 13:20:35 +13:00
-> label ( 'abuse-limit' , 10 )
2021-07-27 23:21:26 +12:00
-> label ( 'abuse-key' , 'url:{url},userId:{userId}' )
2022-05-24 04:34:03 +12:00
-> param ( 'url' , '' , fn ( $clients ) => new Host ( $clients ), 'URL to redirect the user back to your app from the verification email. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API.' , false , [ 'clients' ]) // TODO add built-in confirm page
2020-12-27 03:31:53 +13:00
-> inject ( 'request' )
-> inject ( 'response' )
-> inject ( 'project' )
-> inject ( 'user' )
2021-12-28 01:45:23 +13:00
-> inject ( 'dbForProject' )
2020-12-27 03:31:53 +13:00
-> inject ( 'locale' )
2022-12-21 05:11:30 +13:00
-> inject ( 'queueForEvents' )
2023-06-12 02:08:48 +12:00
-> inject ( 'queueForMails' )
-> action ( function ( string $url , Request $request , Response $response , Document $project , Document $user , Database $dbForProject , Locale $locale , Event $queueForEvents , Mail $queueForMails ) {
2020-11-21 01:35:16 +13:00
2022-05-24 02:54:50 +12:00
if ( empty ( App :: getEnv ( '_APP_SMTP_HOST' ))) {
2022-08-14 03:15:19 +12:00
throw new Exception ( Exception :: GENERAL_SMTP_DISABLED , 'SMTP Disabled' );
2021-08-31 19:35:04 +12:00
}
2021-12-11 06:52:33 +13:00
2023-09-23 05:26:07 +12:00
if ( $user -> getAttribute ( 'emailVerification' )) {
2023-09-23 05:23:41 +12:00
throw new Exception ( Exception :: USER_EMAIL_ALREADY_VERIFIED );
}
2021-12-11 06:52:33 +13:00
$roles = Authorization :: getRoles ();
$isPrivilegedUser = Auth :: isPrivilegedUser ( $roles );
$isAppUser = Auth :: isAppUser ( $roles );
2024-01-18 00:03:04 +13:00
$verificationSecret = Auth :: tokenGenerator ( Auth :: TOKEN_LENGTH_VERIFICATION );
2022-07-14 02:02:49 +12:00
$expire = DateTime :: addSeconds ( new \DateTime (), Auth :: TOKEN_EXPIRATION_CONFIRM );
2021-08-05 17:06:38 +12:00
2020-06-30 09:43:34 +12:00
$verification = new Document ([
2022-08-15 02:22:38 +12:00
'$id' => ID :: unique (),
2021-06-13 08:44:25 +12:00
'userId' => $user -> getId (),
2022-06-07 21:37:09 +12:00
'userInternalId' => $user -> getInternalId (),
2020-06-30 09:43:34 +12:00
'type' => Auth :: TOKEN_TYPE_VERIFICATION ,
2020-11-13 00:54:16 +13:00
'secret' => Auth :: hash ( $verificationSecret ), // One way hash encryption to protect DB leak
2021-07-07 00:18:55 +12:00
'expire' => $expire ,
2020-07-04 03:14:51 +12:00
'userAgent' => $request -> getUserAgent ( 'UNKNOWN' ),
2020-06-30 09:43:34 +12:00
'ip' => $request -> getIP (),
]);
2021-08-05 17:06:38 +12:00
2022-08-19 16:04:33 +12:00
Authorization :: setRole ( Role :: user ( $user -> getId ()) -> toString ());
2020-01-12 13:20:35 +13:00
2022-04-27 23:06:53 +12:00
$verification = $dbForProject -> createDocument ( 'tokens' , $verification
2022-08-02 21:21:53 +12:00
-> setAttribute ( '$permissions' , [
2022-08-15 23:24:31 +12:00
Permission :: read ( Role :: user ( $user -> getId ())),
Permission :: update ( Role :: user ( $user -> getId ())),
Permission :: delete ( Role :: user ( $user -> getId ())),
2022-08-02 21:21:53 +12:00
]));
2020-01-12 13:20:35 +13:00
2023-12-15 02:32:06 +13:00
$dbForProject -> purgeCachedDocument ( 'users' , $user -> getId ());
2021-06-18 00:44:06 +12:00
2020-06-30 09:43:34 +12:00
$url = Template :: parseURL ( $url );
2021-07-07 00:18:55 +12:00
$url [ 'query' ] = Template :: mergeQuery ((( isset ( $url [ 'query' ])) ? $url [ 'query' ] : '' ), [ 'userId' => $user -> getId (), 'secret' => $verificationSecret , 'expire' => $expire ]);
2020-06-30 09:43:34 +12:00
$url = Template :: unParseURL ( $url );
2022-12-15 22:22:05 +13:00
$projectName = $project -> isEmpty () ? 'Console' : $project -> getAttribute ( 'name' , '[APP-NAME]' );
2023-08-28 17:09:28 +12:00
$body = $locale -> getText ( " emails.verification.body " );
2022-12-15 22:22:05 +13:00
$subject = $locale -> getText ( " emails.verification.subject " );
2023-04-19 20:29:29 +12:00
$customTemplate = $project -> getAttribute ( 'templates' , [])[ 'email.verification-' . $locale -> default ] ? ? [];
2023-08-26 03:13:25 +12:00
2023-08-29 21:40:30 +12:00
$message = Template :: fromFile ( __DIR__ . '/../../config/locale/templates/email-inner-base.tpl' );
2023-10-05 12:14:27 +13:00
$message
2024-01-09 06:08:17 +13:00
-> setParam ( '{{body}}' , $body , escapeHtml : false )
2023-10-05 12:14:27 +13:00
-> setParam ( '{{hello}}' , $locale -> getText ( " emails.verification.hello " ))
-> setParam ( '{{footer}}' , $locale -> getText ( " emails.verification.footer " ))
-> setParam ( '{{thanks}}' , $locale -> getText ( " emails.verification.thanks " ))
-> setParam ( '{{signature}}' , $locale -> getText ( " emails.verification.signature " ));
2023-08-29 21:40:30 +12:00
$body = $message -> render ();
$smtp = $project -> getAttribute ( 'smtp' , []);
$smtpEnabled = $smtp [ 'enabled' ] ? ? false ;
2023-08-29 00:19:37 +12:00
2023-08-29 21:40:30 +12:00
$senderEmail = App :: getEnv ( '_APP_SYSTEM_EMAIL_ADDRESS' , APP_EMAIL_TEAM );
$senderName = App :: getEnv ( '_APP_SYSTEM_EMAIL_NAME' , APP_NAME . ' Server' );
$replyTo = " " ;
2023-08-29 00:19:37 +12:00
2023-08-29 21:40:30 +12:00
if ( $smtpEnabled ) {
if ( ! empty ( $smtp [ 'senderEmail' ])) {
$senderEmail = $smtp [ 'senderEmail' ];
}
if ( ! empty ( $smtp [ 'senderName' ])) {
$senderName = $smtp [ 'senderName' ];
}
if ( ! empty ( $smtp [ 'replyTo' ])) {
$replyTo = $smtp [ 'replyTo' ];
}
2023-08-29 00:19:37 +12:00
2023-09-28 04:51:17 +13:00
$queueForMails
2023-08-26 03:13:25 +12:00
-> setSmtpHost ( $smtp [ 'host' ] ? ? '' )
-> setSmtpPort ( $smtp [ 'port' ] ? ? '' )
-> setSmtpUsername ( $smtp [ 'username' ] ? ? '' )
-> setSmtpPassword ( $smtp [ 'password' ] ? ? '' )
2023-08-29 21:40:30 +12:00
-> setSmtpSecure ( $smtp [ 'secure' ] ? ? '' );
2023-08-29 00:19:37 +12:00
2023-08-30 16:30:44 +12:00
if ( ! empty ( $customTemplate )) {
if ( ! empty ( $customTemplate [ 'senderEmail' ])) {
$senderEmail = $customTemplate [ 'senderEmail' ];
}
if ( ! empty ( $customTemplate [ 'senderName' ])) {
$senderName = $customTemplate [ 'senderName' ];
}
if ( ! empty ( $customTemplate [ 'replyTo' ])) {
$replyTo = $customTemplate [ 'replyTo' ];
}
$body = $customTemplate [ 'message' ] ? ? '' ;
$subject = $customTemplate [ 'subject' ] ? ? $subject ;
2023-08-29 21:40:30 +12:00
}
2023-09-28 04:51:17 +13:00
$queueForMails
2023-08-30 16:30:44 +12:00
-> setSmtpReplyTo ( $replyTo )
-> setSmtpSenderEmail ( $senderEmail )
-> setSmtpSenderName ( $senderName );
2023-04-19 20:29:29 +12:00
}
2023-08-28 17:09:28 +12:00
$emailVariables = [
'direction' => $locale -> getText ( 'settings.direction' ),
2024-01-12 09:36:05 +13:00
/* {{user}}, {{team}}, {{redirect}} and {{project}} are required in default and custom templates */
2023-08-31 09:52:55 +12:00
'user' => $user -> getAttribute ( 'name' ),
'team' => '' ,
2024-01-12 09:36:05 +13:00
'redirect' => $url ,
2024-01-09 06:08:17 +13:00
'project' => $projectName
2023-08-28 17:09:28 +12:00
];
2020-06-30 09:43:34 +12:00
2023-06-12 02:08:48 +12:00
$queueForMails
2022-12-14 19:35:04 +13:00
-> setSubject ( $subject )
-> setBody ( $body )
2023-08-28 17:09:28 +12:00
-> setVariables ( $emailVariables )
2022-04-14 00:39:31 +12:00
-> setRecipient ( $user -> getAttribute ( 'email' ))
2023-06-24 20:27:02 +12:00
-> setName ( $user -> getAttribute ( 'name' ) ? ? '' )
2023-08-30 16:30:44 +12:00
-> trigger ();
2020-06-30 09:43:34 +12:00
2022-12-21 05:11:30 +13:00
$queueForEvents
2022-04-04 18:30:07 +12:00
-> setParam ( 'userId' , $user -> getId ())
-> setParam ( 'tokenId' , $verification -> getId ())
2022-04-14 00:39:31 +12:00
-> setPayload ( $response -> output (
$verification -> setAttribute ( 'secret' , $verificationSecret ),
Response :: MODEL_TOKEN
2023-08-30 16:30:44 +12:00
));
2020-11-19 08:38:31 +13:00
2022-04-19 04:21:45 +12:00
// Hide secret for clients
$verification -> setAttribute ( 'secret' , ( $isPrivilegedUser || $isAppUser ) ? $verificationSecret : '' );
2020-11-19 08:38:31 +13:00
2022-09-07 23:11:10 +12:00
$response
-> setStatusCode ( Response :: STATUS_CODE_CREATED )
-> dynamic ( $verification , Response :: MODEL_TOKEN );
2020-12-27 03:31:53 +13:00
});
2020-01-12 13:20:35 +13:00
2020-06-29 05:31:21 +12:00
App :: put ( '/v1/account/verification' )
2023-08-02 03:26:48 +12:00
-> desc ( 'Create email verification (confirmation)' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2020-01-12 13:20:35 +13:00
-> label ( 'scope' , 'public' )
2022-04-04 18:30:07 +12:00
-> label ( 'event' , 'users.[userId].verification.[tokenId].update' )
2022-09-05 20:00:08 +12:00
-> label ( 'audits.event' , 'verification.update' )
2022-08-12 01:19:05 +12:00
-> label ( 'audits.resource' , 'user/{response.userId}' )
2021-04-16 19:22:17 +12:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_SESSION , APP_AUTH_TYPE_JWT ])
2020-01-12 13:20:35 +13:00
-> label ( 'sdk.namespace' , 'account' )
2020-01-31 05:18:46 +13:00
-> label ( 'sdk.method' , 'updateVerification' )
2022-06-21 02:47:49 +12:00
-> label ( 'sdk.description' , '/docs/references/account/update-email-verification.md' )
2020-11-13 11:50:53 +13:00
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_OK )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
-> label ( 'sdk.response.model' , Response :: MODEL_TOKEN )
2020-01-12 13:20:35 +13:00
-> label ( 'abuse-limit' , 10 )
-> label ( 'abuse-key' , 'url:{url},userId:{param-userId}' )
2021-12-11 01:27:11 +13:00
-> param ( 'userId' , '' , new UID (), 'User ID.' )
2020-09-11 02:40:14 +12:00
-> param ( 'secret' , '' , new Text ( 256 ), 'Valid verification token.' )
2020-12-27 03:31:53 +13:00
-> inject ( 'response' )
-> inject ( 'user' )
2021-12-28 01:45:23 +13:00
-> inject ( 'dbForProject' )
2022-12-21 05:11:30 +13:00
-> inject ( 'queueForEvents' )
-> action ( function ( string $userId , string $secret , Response $response , Document $user , Database $dbForProject , Event $queueForEvents ) {
2020-06-30 09:43:34 +12:00
2022-04-27 23:06:53 +12:00
$profile = Authorization :: skip ( fn () => $dbForProject -> getDocument ( 'users' , $userId ));
2020-06-30 09:43:34 +12:00
2021-05-07 10:31:05 +12:00
if ( $profile -> isEmpty ()) {
2022-07-27 02:24:32 +12:00
throw new Exception ( Exception :: USER_NOT_FOUND );
2020-06-30 09:43:34 +12:00
}
2020-01-12 13:20:35 +13:00
2021-05-07 10:31:05 +12:00
$tokens = $profile -> getAttribute ( 'tokens' , []);
2023-10-05 23:18:19 +13:00
$verifiedToken = Auth :: tokenVerify ( $tokens , Auth :: TOKEN_TYPE_VERIFICATION , $secret );
2020-01-12 13:20:35 +13:00
2023-10-05 23:18:19 +13:00
if ( ! $verifiedToken ) {
2022-07-27 02:24:32 +12:00
throw new Exception ( Exception :: USER_INVALID_TOKEN );
2020-06-30 09:43:34 +12:00
}
2020-01-12 13:20:35 +13:00
2022-08-19 16:04:33 +12:00
Authorization :: setRole ( Role :: user ( $profile -> getId ()) -> toString ());
2020-01-12 13:20:35 +13:00
2021-12-28 01:45:23 +13:00
$profile = $dbForProject -> updateDocument ( 'users' , $profile -> getId (), $profile -> setAttribute ( 'emailVerification' , true ));
2020-01-12 13:20:35 +13:00
2023-07-07 12:12:39 +12:00
$user -> setAttributes ( $profile -> getArrayCopy ());
2023-10-05 23:18:19 +13:00
$verificationDocument = $dbForProject -> getDocument ( 'tokens' , $verifiedToken -> getId ());
2020-01-12 13:20:35 +13:00
2020-06-30 09:43:34 +12:00
/**
2021-08-15 06:56:28 +12:00
* We act like we ' re updating and validating
* the verification token but actually we don ' t need it anymore .
*/
2023-10-05 23:18:19 +13:00
$dbForProject -> deleteDocument ( 'tokens' , $verifiedToken -> getId ());
2023-12-15 02:32:06 +13:00
$dbForProject -> purgeCachedDocument ( 'users' , $profile -> getId ());
2021-05-07 10:31:05 +12:00
2022-12-21 05:11:30 +13:00
$queueForEvents
2023-03-11 07:53:49 +13:00
-> setParam ( 'userId' , $userId )
2022-05-09 03:25:01 +12:00
-> setParam ( 'tokenId' , $verificationDocument -> getId ())
2021-08-16 20:53:34 +12:00
;
2022-04-04 18:30:07 +12:00
2022-04-27 23:06:53 +12:00
$response -> dynamic ( $verificationDocument , Response :: MODEL_TOKEN );
2021-06-13 02:50:40 +12:00
});
2022-06-09 00:50:31 +12:00
App :: post ( '/v1/account/verification/phone' )
2023-08-02 03:26:48 +12:00
-> desc ( 'Create phone verification' )
2022-06-09 00:50:31 +12:00
-> groups ([ 'api' , 'account' ])
2024-01-18 00:17:03 +13:00
-> label ( 'scope' , 'accounts.write' )
2022-06-09 00:50:31 +12:00
-> label ( 'event' , 'users.[userId].verification.[tokenId].create' )
2022-09-05 20:00:08 +12:00
-> label ( 'audits.event' , 'verification.create' )
2022-08-12 01:19:05 +12:00
-> label ( 'audits.resource' , 'user/{response.userId}' )
2022-06-09 00:50:31 +12:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_SESSION , APP_AUTH_TYPE_JWT ])
-> label ( 'sdk.namespace' , 'account' )
-> label ( 'sdk.method' , 'createPhoneVerification' )
-> label ( 'sdk.description' , '/docs/references/account/create-phone-verification.md' )
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_CREATED )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
-> label ( 'sdk.response.model' , Response :: MODEL_TOKEN )
-> label ( 'abuse-limit' , 10 )
-> label ( 'abuse-key' , 'userId:{userId}' )
-> inject ( 'request' )
-> inject ( 'response' )
-> inject ( 'user' )
-> inject ( 'dbForProject' )
2022-12-21 05:11:30 +13:00
-> inject ( 'queueForEvents' )
-> inject ( 'queueForMessaging' )
2023-04-19 20:29:29 +12:00
-> inject ( 'project' )
-> inject ( 'locale' )
2023-10-20 22:25:17 +13:00
-> action ( function ( Request $request , Response $response , Document $user , Database $dbForProject , Event $queueForEvents , Messaging $queueForMessaging , Document $project , Locale $locale ) {
2023-11-16 09:00:47 +13:00
if ( empty ( App :: getEnv ( '_APP_SMS_PROVIDER' ))) {
2023-09-06 05:10:48 +12:00
throw new Exception ( Exception :: GENERAL_PHONE_DISABLED , 'Phone provider not configured' );
2022-06-09 00:50:31 +12:00
}
if ( empty ( $user -> getAttribute ( 'phone' ))) {
2022-07-27 02:24:32 +12:00
throw new Exception ( Exception :: USER_PHONE_NOT_FOUND );
2022-06-09 00:50:31 +12:00
}
2023-09-23 05:26:07 +12:00
if ( $user -> getAttribute ( 'phoneVerification' )) {
2023-09-23 05:23:41 +12:00
throw new Exception ( Exception :: USER_PHONE_ALREADY_VERIFIED );
}
2022-06-09 00:50:31 +12:00
$roles = Authorization :: getRoles ();
$isPrivilegedUser = Auth :: isPrivilegedUser ( $roles );
$isAppUser = Auth :: isAppUser ( $roles );
2022-09-19 20:09:48 +12:00
$secret = Auth :: codeGenerator ();
2022-07-14 02:02:49 +12:00
$expire = DateTime :: addSeconds ( new \DateTime (), Auth :: TOKEN_EXPIRATION_CONFIRM );
2022-06-09 00:50:31 +12:00
$verification = new Document ([
2022-08-15 02:22:38 +12:00
'$id' => ID :: unique (),
2022-06-09 00:50:31 +12:00
'userId' => $user -> getId (),
2022-06-21 09:38:45 +12:00
'userInternalId' => $user -> getInternalId (),
2022-06-09 00:50:31 +12:00
'type' => Auth :: TOKEN_TYPE_PHONE ,
2022-09-23 10:25:17 +12:00
'secret' => Auth :: hash ( $secret ),
2022-06-09 00:50:31 +12:00
'expire' => $expire ,
'userAgent' => $request -> getUserAgent ( 'UNKNOWN' ),
'ip' => $request -> getIP (),
]);
2022-08-19 16:04:33 +12:00
Authorization :: setRole ( Role :: user ( $user -> getId ()) -> toString ());
2022-06-09 00:50:31 +12:00
$verification = $dbForProject -> createDocument ( 'tokens' , $verification
2022-08-02 21:21:53 +12:00
-> setAttribute ( '$permissions' , [
2022-08-15 23:24:31 +12:00
Permission :: read ( Role :: user ( $user -> getId ())),
Permission :: update ( Role :: user ( $user -> getId ())),
Permission :: delete ( Role :: user ( $user -> getId ())),
2022-08-02 21:21:53 +12:00
]));
2022-06-09 00:50:31 +12:00
2023-12-15 02:32:06 +13:00
$dbForProject -> purgeCachedDocument ( 'users' , $user -> getId ());
2022-06-09 00:50:31 +12:00
2023-03-14 22:07:42 +13:00
$message = Template :: fromFile ( __DIR__ . '/../../config/locale/templates/sms-base.tpl' );
2023-04-19 20:29:29 +12:00
$customTemplate = $project -> getAttribute ( 'templates' , [])[ 'sms.verification-' . $locale -> default ] ? ? [];
2023-04-19 20:44:22 +12:00
if ( ! empty ( $customTemplate )) {
2023-07-18 19:05:09 +12:00
$message = $customTemplate [ 'message' ] ? ? $message ;
2023-04-19 20:29:29 +12:00
}
2024-01-12 01:50:01 +13:00
$messageContent = Template :: fromString ( $locale -> getText ( " sms.verification.body " ));
$messageContent
-> setParam ( '{{project}}' , $project -> getAttribute ( 'name' ))
-> setParam ( '{{secret}}' , $secret );
2024-01-12 02:24:08 +13:00
$messageContent = \strip_tags ( $messageContent -> render ());
$message = $message -> setParam ( '{{token}}' , $messageContent );
2024-01-12 05:28:21 +13:00
2023-03-14 22:07:42 +13:00
$message = $message -> render ();
2022-06-09 00:50:31 +12:00
2023-11-16 09:00:47 +13:00
$messageDoc = new Document ([
2023-09-22 03:47:15 +12:00
'$id' => $verification -> getId (),
2023-09-06 05:10:48 +12:00
'data' => [
'content' => $message ,
],
2023-11-16 09:00:47 +13:00
]);
2023-09-06 05:10:48 +12:00
2022-12-21 05:11:30 +13:00
$queueForMessaging
2023-11-16 09:00:47 +13:00
-> setMessage ( $messageDoc )
-> setRecipients ([ $user -> getAttribute ( 'phone' )])
2023-11-29 22:52:26 +13:00
-> setProviderType ( MESSAGE_TYPE_SMS )
2023-10-06 00:27:48 +13:00
-> trigger ();
2022-06-09 00:50:31 +12:00
2022-12-21 05:11:30 +13:00
$queueForEvents
2022-06-09 00:50:31 +12:00
-> setParam ( 'userId' , $user -> getId ())
-> setParam ( 'tokenId' , $verification -> getId ())
-> setPayload ( $response -> output (
2023-06-23 12:54:09 +12:00
$verification -> setAttribute ( 'secret' , $secret ),
2022-06-09 00:50:31 +12:00
Response :: MODEL_TOKEN
))
;
// Hide secret for clients
2023-06-23 12:54:09 +12:00
$verification -> setAttribute ( 'secret' , ( $isPrivilegedUser || $isAppUser ) ? $secret : '' );
2022-06-09 00:50:31 +12:00
2022-09-07 23:11:10 +12:00
$response
-> setStatusCode ( Response :: STATUS_CODE_CREATED )
-> dynamic ( $verification , Response :: MODEL_TOKEN );
2022-06-09 00:50:31 +12:00
});
App :: put ( '/v1/account/verification/phone' )
2023-08-02 03:26:48 +12:00
-> desc ( 'Create phone verification (confirmation)' )
2022-06-09 00:50:31 +12:00
-> groups ([ 'api' , 'account' ])
-> label ( 'scope' , 'public' )
-> label ( 'event' , 'users.[userId].verification.[tokenId].update' )
2022-09-05 20:00:08 +12:00
-> label ( 'audits.event' , 'verification.update' )
2022-08-12 01:19:05 +12:00
-> label ( 'audits.resource' , 'user/{response.userId}' )
2022-06-09 00:50:31 +12:00
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_SESSION , APP_AUTH_TYPE_JWT ])
-> label ( 'sdk.namespace' , 'account' )
-> label ( 'sdk.method' , 'updatePhoneVerification' )
-> label ( 'sdk.description' , '/docs/references/account/update-phone-verification.md' )
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_OK )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
-> label ( 'sdk.response.model' , Response :: MODEL_TOKEN )
-> label ( 'abuse-limit' , 10 )
-> label ( 'abuse-key' , 'userId:{param-userId}' )
-> param ( 'userId' , '' , new UID (), 'User ID.' )
-> param ( 'secret' , '' , new Text ( 256 ), 'Valid verification token.' )
-> inject ( 'response' )
-> inject ( 'user' )
-> inject ( 'dbForProject' )
2022-12-21 05:11:30 +13:00
-> inject ( 'queueForEvents' )
-> action ( function ( string $userId , string $secret , Response $response , Document $user , Database $dbForProject , Event $queueForEvents ) {
2022-06-09 00:50:31 +12:00
$profile = Authorization :: skip ( fn () => $dbForProject -> getDocument ( 'users' , $userId ));
if ( $profile -> isEmpty ()) {
2022-07-27 02:24:32 +12:00
throw new Exception ( Exception :: USER_NOT_FOUND );
2022-06-09 00:50:31 +12:00
}
2023-10-05 23:18:19 +13:00
$verifiedToken = Auth :: tokenVerify ( $user -> getAttribute ( 'tokens' , []), Auth :: TOKEN_TYPE_PHONE , $secret );
2022-06-09 00:50:31 +12:00
2023-10-05 23:18:19 +13:00
if ( ! $verifiedToken ) {
2022-07-27 02:24:32 +12:00
throw new Exception ( Exception :: USER_INVALID_TOKEN );
2022-06-09 00:50:31 +12:00
}
2022-08-19 16:04:33 +12:00
Authorization :: setRole ( Role :: user ( $profile -> getId ()) -> toString ());
2022-06-09 00:50:31 +12:00
$profile = $dbForProject -> updateDocument ( 'users' , $profile -> getId (), $profile -> setAttribute ( 'phoneVerification' , true ));
2023-07-07 12:12:39 +12:00
$user -> setAttributes ( $profile -> getArrayCopy ());
2023-10-05 23:18:19 +13:00
$verificationDocument = $dbForProject -> getDocument ( 'tokens' , $verifiedToken -> getId ());
2022-06-09 00:50:31 +12:00
/**
* We act like we 're updating and validating the verification token but actually we don' t need it anymore .
*/
2023-10-05 23:18:19 +13:00
$dbForProject -> deleteDocument ( 'tokens' , $verifiedToken -> getId ());
2023-12-15 02:32:06 +13:00
$dbForProject -> purgeCachedDocument ( 'users' , $profile -> getId ());
2022-06-09 00:50:31 +12:00
2022-12-21 05:11:30 +13:00
$queueForEvents
2022-06-09 00:50:31 +12:00
-> setParam ( 'userId' , $user -> getId ())
-> setParam ( 'tokenId' , $verificationDocument -> getId ())
;
$response -> dynamic ( $verificationDocument , Response :: MODEL_TOKEN );
});
2023-11-16 09:42:06 +13:00
2023-11-16 23:56:36 +13:00
App :: put ( '/v1/account/targets/:targetId/push' )
2023-11-17 00:17:36 +13:00
-> desc ( 'Update Account\'s push target' )
2023-11-16 09:42:06 +13:00
-> groups ([ 'api' , 'account' ])
2024-01-19 02:04:54 +13:00
-> label ( 'scope' , 'account' )
2023-11-16 09:42:06 +13:00
-> label ( 'audits.event' , 'target.update' )
-> label ( 'audits.resource' , 'target/response.$id' )
2023-11-17 00:17:36 +13:00
-> label ( 'event' , 'users.[userId].targets.[targetId].update' )
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_SESSION ])
-> label ( 'sdk.namespace' , 'account' )
-> label ( 'sdk.method' , 'updatePushTarget' )
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_OK )
-> label ( 'sdk.response.type' , Response :: CONTENT_TYPE_JSON )
-> label ( 'sdk.response.model' , Response :: MODEL_TARGET )
2023-11-16 09:42:06 +13:00
-> param ( 'targetId' , '' , new UID (), 'Target ID.' )
2023-11-17 00:39:08 +13:00
-> param ( 'identifier' , '' , new Text ( Database :: LENGTH_KEY ), 'The target identifier (token, email, phone etc.)' )
2023-11-16 09:42:06 +13:00
-> inject ( 'queueForEvents' )
-> inject ( 'user' )
-> inject ( 'request' )
-> inject ( 'response' )
-> inject ( 'dbForProject' )
2023-11-17 00:17:36 +13:00
-> action ( function ( string $targetId , string $identifier , Event $queueForEvents , Document $user , Request $request , Response $response , Database $dbForProject ) {
2023-11-16 09:42:06 +13:00
if ( $user -> isEmpty ()) {
throw new Exception ( Exception :: USER_NOT_FOUND );
}
$target = Authorization :: skip ( fn () => $dbForProject -> getDocument ( 'targets' , $targetId ));
if ( $target -> isEmpty ()) {
throw new Exception ( Exception :: USER_TARGET_NOT_FOUND );
}
if ( $user -> getId () !== $target -> getAttribute ( 'userId' )) {
throw new Exception ( Exception :: USER_TARGET_NOT_FOUND );
}
if ( $identifier ) {
$target -> setAttribute ( 'identifier' , $identifier );
}
2023-11-16 23:56:36 +13:00
$detector = new Detector ( $request -> getUserAgent ());
$detector -> skipBotDetection (); // OPTIONAL: If called, bot detection will completely be skipped (bots will be detected as regular devices then)
$device = $detector -> getDevice ();
2023-11-17 00:17:36 +13:00
$target -> setAttribute ( 'name' , " { $device [ 'deviceBrand' ] } { $device [ 'deviceModel' ] } " );
2023-11-16 09:42:06 +13:00
$target = $dbForProject -> updateDocument ( 'targets' , $target -> getId (), $target );
2023-12-15 02:32:06 +13:00
$dbForProject -> purgeCachedDocument ( 'users' , $user -> getId ());
2023-11-16 09:42:06 +13:00
$queueForEvents
-> setParam ( 'userId' , $user -> getId ())
-> setParam ( 'targetId' , $target -> getId ());
$response
-> dynamic ( $target , Response :: MODEL_TARGET );
});
2024-01-23 06:29:10 +13:00
App :: delete ( '/v1/account' )
-> desc ( 'Delete account' )
-> groups ([ 'api' , 'account' ])
-> label ( 'event' , 'users.[userId].delete' )
-> label ( 'scope' , 'accounts.write' )
-> label ( 'audits.event' , 'user.delete' )
-> label ( 'audits.resource' , 'user/{response.$id}' )
-> label ( 'usage.metric' , 'users.{scope}.requests.delete' )
-> label ( 'sdk.auth' , [ APP_AUTH_TYPE_ADMIN ])
-> label ( 'sdk.namespace' , 'account' )
-> label ( 'sdk.method' , 'delete' )
-> label ( 'sdk.description' , '/docs/references/account/delete.md' )
-> label ( 'sdk.response.code' , Response :: STATUS_CODE_NOCONTENT )
-> label ( 'sdk.response.model' , Response :: MODEL_NONE )
-> inject ( 'user' )
-> inject ( 'response' )
-> inject ( 'dbForProject' )
-> inject ( 'queueForEvents' )
-> inject ( 'queueForDeletes' )
-> action ( function ( Document $user , Response $response , Database $dbForProject , Event $queueForEvents , Delete $queueForDeletes ) {
if ( $user -> isEmpty ()) {
throw new Exception ( Exception :: USER_NOT_FOUND );
}
$dbForProject -> deleteDocument ( 'users' , $user -> getId ());
$queueForDeletes
-> setType ( DELETE_TYPE_DOCUMENT )
-> setDocument ( $user );
$queueForEvents
-> setParam ( 'userId' , $user -> getId ())
-> setPayload ( $response -> output ( $user , Response :: MODEL_USER ));
$response -> noContent ();
});