2019-05-09 18:54:39 +12:00
< ? php
2020-01-12 02:58:02 +13:00
global $utopia , $register , $request , $response , $user , $audit ,
2020-06-14 06:30:44 +12:00
$webhook , $mail , $project , $projectDB , $clients ;
2019-05-09 18:54:39 +12:00
use Utopia\Exception ;
2020-01-12 02:58:02 +13:00
use Utopia\Response ;
2020-03-29 01:42:16 +13:00
use Utopia\Config\Config ;
2020-01-19 08:07:02 +13:00
use Utopia\Validator\Assoc ;
2019-05-09 18:54:39 +12:00
use Utopia\Validator\Text ;
use Utopia\Validator\Email ;
2020-01-04 10:00:53 +13:00
use Utopia\Validator\WhiteList ;
use Utopia\Validator\Host ;
use Utopia\Validator\URL ;
2019-12-29 22:47:55 +13:00
use Utopia\Audit\Audit ;
use Utopia\Audit\Adapters\MySQL as AuditAdapter ;
2019-11-09 04:27:16 +13:00
use Utopia\Locale\Locale ;
2020-03-25 06:56:32 +13:00
use Appwrite\Auth\Auth ;
use Appwrite\Auth\Validator\Password ;
use Appwrite\Database\Database ;
use Appwrite\Database\Document ;
use Appwrite\Database\Exception\Duplicate ;
use Appwrite\Database\Validator\UID ;
use Appwrite\Database\Validator\Authorization ;
use Appwrite\Template\Template ;
use Appwrite\OpenSSL\OpenSSL ;
2020-04-11 06:59:14 +12:00
use Appwrite\URL\URL as URLParser ;
2019-05-09 18:54:39 +12:00
use DeviceDetector\DeviceDetector ;
use GeoIp2\Database\Reader ;
2020-06-17 07:37:46 +12:00
use Utopia\Validator\ArrayList ;
2019-05-09 18:54:39 +12:00
2020-06-28 19:59:52 +12:00
$oauthDefaultSuccess = '/auth/oauth2/success' ;
$oauthDefaultFailure = '/auth/oauth2/failure' ;
2020-04-09 01:38:36 +12:00
2020-02-17 00:41:03 +13:00
$oauth2Keys = [];
2020-01-12 02:58:02 +13:00
2020-03-29 01:42:16 +13:00
$utopia -> init ( function () use ( & $oauth2Keys ) {
foreach ( Config :: getParam ( 'providers' ) as $key => $provider ) {
2020-01-12 02:58:02 +13:00
if ( ! $provider [ 'enabled' ]) {
continue ;
}
2020-06-20 23:20:49 +12:00
$oauth2Keys [] = 'oauth2' . \ucfirst ( $key );
$oauth2Keys [] = 'oauth2' . \ucfirst ( $key ) . 'AccessToken' ;
2020-01-12 02:58:02 +13:00
}
2020-06-26 06:32:12 +12:00
}, 'account' );
2020-01-12 02:58:02 +13:00
2020-01-04 10:00:53 +13:00
$utopia -> post ( '/v1/account' )
2020-01-23 12:32:10 +13:00
-> desc ( 'Create Account' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2020-01-04 10:00:53 +13:00
-> label ( 'webhook' , 'account.create' )
2020-01-06 00:29:42 +13:00
-> label ( 'scope' , 'public' )
2020-01-27 19:14:14 +13:00
-> label ( 'sdk.platform' , [ APP_PLATFORM_CLIENT ])
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-01-04 10:00:53 +13:00
-> label ( 'abuse-limit' , 10 )
2020-02-10 18:58:29 +13:00
-> param ( 'email' , '' , function () { return new Email (); }, 'User email.' )
2020-05-31 10:24:05 +12:00
-> param ( 'password' , '' , function () { return new Password (); }, 'User password. Must be between 6 to 32 chars.' )
2020-02-10 10:37:28 +13:00
-> param ( 'name' , '' , function () { return new Text ( 100 ); }, 'User name.' , true )
2020-01-04 10:00:53 +13:00
-> action (
2020-06-14 06:30:44 +12:00
function ( $email , $password , $name ) use ( $request , $response , $audit , $projectDB , $project , $webhook , $oauth2Keys ) {
2020-02-17 20:16:11 +13:00
if ( 'console' === $project -> getId ()) {
2020-01-04 10:00:53 +13:00
$whitlistEmails = $project -> getAttribute ( 'authWhitelistEmails' );
$whitlistIPs = $project -> getAttribute ( 'authWhitelistIPs' );
$whitlistDomains = $project -> getAttribute ( 'authWhitelistDomains' );
2020-06-20 23:20:49 +12:00
if ( ! empty ( $whitlistEmails ) && ! \in_array ( $email , $whitlistEmails )) {
2020-01-04 10:00:53 +13:00
throw new Exception ( 'Console registration is restricted to specific emails. Contact your administrator for more information.' , 401 );
}
2020-06-20 23:20:49 +12:00
if ( ! empty ( $whitlistIPs ) && ! \in_array ( $request -> getIP (), $whitlistIPs )) {
2020-01-04 10:00:53 +13:00
throw new Exception ( 'Console registration is restricted to specific IPs. Contact your administrator for more information.' , 401 );
}
2020-06-20 23:20:49 +12:00
if ( ! empty ( $whitlistDomains ) && ! \in_array ( \substr ( \strrchr ( $email , '@' ), 1 ), $whitlistDomains )) {
2020-01-04 10:00:53 +13:00
throw new Exception ( 'Console registration is restricted to specific domains. Contact your administrator for more information.' , 401 );
}
}
2020-06-27 02:41:13 +12:00
$profile = $projectDB -> getCollectionFirst ([ // Get user by email address
2020-01-04 10:00:53 +13:00
'limit' => 1 ,
'filters' => [
'$collection=' . Database :: SYSTEM_COLLECTION_USERS ,
'email=' . $email ,
],
]);
if ( ! empty ( $profile )) {
throw new Exception ( 'Account already exists' , 409 );
}
Authorization :: disable ();
2020-03-22 10:10:06 +13:00
try {
$user = $projectDB -> createDocument ([
'$collection' => Database :: SYSTEM_COLLECTION_USERS ,
'$permissions' => [
'read' => [ '*' ],
'write' => [ 'user:{self}' ],
],
'email' => $email ,
'emailVerification' => false ,
'status' => Auth :: USER_STATUS_UNACTIVATED ,
'password' => Auth :: passwordHash ( $password ),
2020-06-20 23:20:49 +12:00
'password-update' => \time (),
'registration' => \time (),
2020-03-22 10:10:06 +13:00
'reset' => false ,
'name' => $name ,
], [ 'email' => $email ]);
} catch ( Duplicate $th ) {
throw new Exception ( 'Account already exists' , 409 );
}
2020-01-04 10:00:53 +13:00
Authorization :: enable ();
if ( false === $user ) {
throw new Exception ( 'Failed saving user to DB' , 500 );
}
2020-01-05 04:45:28 +13:00
$webhook
-> setParam ( 'payload' , [
'name' => $name ,
'email' => $email ,
])
;
2020-01-04 10:00:53 +13:00
2020-01-05 04:45:28 +13:00
$audit
2020-02-17 20:16:11 +13:00
-> setParam ( 'userId' , $user -> getId ())
2020-01-05 04:45:28 +13:00
-> setParam ( 'event' , 'account.create' )
2020-02-17 20:16:11 +13:00
-> setParam ( 'resource' , 'users/' . $user -> getId ())
2020-01-04 10:00:53 +13:00
;
2020-01-12 02:58:02 +13:00
$response
-> setStatusCode ( Response :: STATUS_CODE_CREATED )
2020-06-20 23:20:49 +12:00
-> json ( \array_merge ( $user -> getArrayCopy ( \array_merge (
2020-01-12 02:58:02 +13:00
[
2020-02-17 20:16:11 +13:00
'$id' ,
2020-01-12 02:58:02 +13:00
'email' ,
'registration' ,
'name' ,
],
2020-02-17 00:41:03 +13:00
$oauth2Keys
2020-01-12 02:58:02 +13:00
)), [ 'roles' => Authorization :: getRoles ()]));
2020-01-05 04:45:28 +13:00
}
);
$utopia -> post ( '/v1/account/sessions' )
2020-01-06 00:29:42 +13:00
-> desc ( 'Create Account Session' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2020-01-05 04:45:28 +13:00
-> label ( 'webhook' , 'account.sessions.create' )
2020-01-06 00:29:42 +13:00
-> label ( 'scope' , 'public' )
2020-01-27 19:14:14 +13:00
-> label ( 'sdk.platform' , [ APP_PLATFORM_CLIENT ])
2020-01-05 04:45:28 +13:00
-> label ( 'sdk.namespace' , 'account' )
2020-01-31 05:18:46 +13:00
-> label ( 'sdk.method' , 'createSession' )
2020-01-06 00:29:42 +13:00
-> label ( 'sdk.description' , '/docs/references/account/create-session.md' )
2020-01-05 04:45:28 +13:00
-> label ( 'abuse-limit' , 10 )
-> label ( 'abuse-key' , 'url:{url},email:{param-email}' )
2020-02-10 18:58:29 +13:00
-> param ( 'email' , '' , function () { return new Email (); }, 'User email.' )
2020-05-31 10:24:05 +12:00
-> param ( 'password' , '' , function () { return new Password (); }, 'User password. Must be between 6 to 32 chars.' )
2020-01-05 04:45:28 +13:00
-> action (
2020-03-29 01:42:16 +13:00
function ( $email , $password ) use ( $response , $request , $projectDB , $audit , $webhook ) {
$protocol = Config :: getParam ( 'protocol' );
2020-06-27 02:41:13 +12:00
$profile = $projectDB -> getCollectionFirst ([ // Get user by email address
2020-01-05 04:45:28 +13:00
'limit' => 1 ,
'filters' => [
'$collection=' . Database :: SYSTEM_COLLECTION_USERS ,
'email=' . $email ,
],
]);
2020-01-12 02:58:02 +13:00
if ( false == $profile || ! Auth :: passwordVerify ( $password , $profile -> getAttribute ( 'password' ))) {
2020-01-05 04:45:28 +13:00
$audit
2020-02-17 20:16:11 +13:00
//->setParam('userId', $profile->getId())
2020-01-06 00:29:42 +13:00
-> setParam ( 'event' , 'account.sesssions.failed' )
2020-02-17 20:16:11 +13:00
-> setParam ( 'resource' , 'users/' . ( $profile ? $profile -> getId () : '' ))
2020-01-05 04:45:28 +13:00
;
2020-01-04 10:00:53 +13:00
2020-01-05 04:45:28 +13:00
throw new Exception ( 'Invalid credentials' , 401 ); // Wrong password or username
}
2020-01-04 10:00:53 +13:00
2020-06-20 23:20:49 +12:00
$expiry = \time () + Auth :: TOKEN_EXPIRATION_LOGIN_LONG ;
2020-01-05 04:45:28 +13:00
$secret = Auth :: tokenGenerator ();
2020-01-12 02:58:02 +13:00
$session = new Document ([
2020-01-05 04:45:28 +13:00
'$collection' => Database :: SYSTEM_COLLECTION_TOKENS ,
2020-02-17 20:16:11 +13:00
'$permissions' => [ 'read' => [ 'user:' . $profile -> getId ()], 'write' => [ 'user:' . $profile -> getId ()]],
2020-01-05 04:45:28 +13:00
'type' => Auth :: TOKEN_TYPE_LOGIN ,
'secret' => Auth :: hash ( $secret ), // On way hash encryption to protect DB leak
'expire' => $expiry ,
'userAgent' => $request -> getServer ( 'HTTP_USER_AGENT' , 'UNKNOWN' ),
'ip' => $request -> getIP (),
2020-01-12 02:58:02 +13:00
]);
2020-01-05 04:45:28 +13:00
2020-02-17 20:16:11 +13:00
Authorization :: setRole ( 'user:' . $profile -> getId ());
2020-01-04 10:00:53 +13:00
2020-01-12 02:58:02 +13:00
$session = $projectDB -> createDocument ( $session -> getArrayCopy ());
if ( false === $session ) {
throw new Exception ( 'Failed saving session to DB' , 500 );
}
$profile -> setAttribute ( 'tokens' , $session , Document :: SET_TYPE_APPEND );
2020-01-05 04:45:28 +13:00
$profile = $projectDB -> updateDocument ( $profile -> getArrayCopy ());
if ( false === $profile ) {
throw new Exception ( 'Failed saving user to DB' , 500 );
2020-01-04 10:00:53 +13:00
}
$webhook
-> setParam ( 'payload' , [
2020-01-05 04:45:28 +13:00
'name' => $profile -> getAttribute ( 'name' , '' ),
'email' => $profile -> getAttribute ( 'email' , '' ),
2020-01-04 10:00:53 +13:00
])
;
$audit
2020-02-17 20:16:11 +13:00
-> setParam ( 'userId' , $profile -> getId ())
2020-01-12 02:58:02 +13:00
-> setParam ( 'event' , 'account.sessions.create' )
2020-02-17 20:16:11 +13:00
-> setParam ( 'resource' , 'users/' . $profile -> getId ())
2020-01-04 10:00:53 +13:00
;
2020-03-18 00:36:13 +13:00
2020-06-25 08:59:04 +12:00
if ( ! Config :: getParam ( 'domainVerification' )) {
2020-03-18 00:36:13 +13:00
$response
2020-06-20 23:20:49 +12:00
-> addHeader ( 'X-Fallback-Cookies' , \json_encode ([ Auth :: $cookieName => Auth :: encodeSession ( $profile -> getId (), $secret )]))
2020-03-18 00:36:13 +13:00
;
}
2020-01-12 02:58:02 +13:00
2020-01-04 10:00:53 +13:00
$response
2020-02-27 22:17:09 +13:00
-> addCookie ( Auth :: $cookieName . '_legacy' , Auth :: encodeSession ( $profile -> getId (), $secret ), $expiry , '/' , COOKIE_DOMAIN , ( 'https' == $protocol ), true , null )
-> addCookie ( Auth :: $cookieName , Auth :: encodeSession ( $profile -> getId (), $secret ), $expiry , '/' , COOKIE_DOMAIN , ( 'https' == $protocol ), true , COOKIE_SAMESITE )
2020-01-12 02:58:02 +13:00
-> setStatusCode ( Response :: STATUS_CODE_CREATED )
2020-02-17 20:16:11 +13:00
-> json ( $session -> getArrayCopy ([ '$id' , 'type' , 'expire' ]))
2020-01-12 02:58:02 +13:00
;
2020-01-04 10:00:53 +13:00
}
);
2020-02-17 00:41:03 +13:00
$utopia -> get ( '/v1/account/sessions/oauth2/:provider' )
-> desc ( 'Create Account Session with OAuth2' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2020-01-12 10:53:57 +13:00
-> label ( 'error' , __DIR__ . '/../../views/general/error.phtml' )
2020-01-06 00:29:42 +13:00
-> label ( 'scope' , 'public' )
2020-01-27 19:14:14 +13:00
-> label ( 'sdk.platform' , [ APP_PLATFORM_CLIENT ])
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' )
2020-01-15 05:16:24 +13:00
-> label ( 'sdk.response.code' , 301 )
-> label ( 'sdk.response.type' , 'text/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}' )
2020-06-20 23:20:49 +12:00
-> param ( 'provider' , '' , function () { return new WhiteList ( \array_keys ( Config :: getParam ( 'providers' ))); }, 'OAuth2 Provider. Currently, supported providers are: ' . \implode ( ', ' , \array_keys ( \array_filter ( Config :: getParam ( 'providers' ), function ( $node ) { return ( ! $node [ 'mock' ]);}))) . '.' )
2020-05-28 23:34:42 +12:00
-> param ( 'success' , $oauthDefaultSuccess , function () use ( $clients ) { return new Host ( $clients ); }, 'URL to redirect back to your app after a successful login attempt. 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 )
-> param ( 'failure' , $oauthDefaultFailure , function () use ( $clients ) { return new Host ( $clients ); }, 'URL to redirect back to your app after a failed login attempt. 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 )
2020-06-17 07:37:46 +12:00
-> param ( 'scopes' , [], function () { return new ArrayList ( new Text ( 128 )); }, 'A list of custom OAuth2 scopes. Check each provider internal docs for a list of supported scopes.' , true )
2020-01-06 00:29:42 +13:00
-> action (
2020-06-17 07:37:46 +12:00
function ( $provider , $success , $failure , $scopes ) use ( $response , $request , $project ) {
2020-03-29 01:42:16 +13:00
$protocol = Config :: getParam ( 'protocol' );
2020-02-27 22:17:09 +13:00
$callback = $protocol . '://' . $request -> getServer ( 'HTTP_HOST' ) . '/v1/account/sessions/oauth2/callback/' . $provider . '/' . $project -> getId ();
2020-06-20 23:20:49 +12:00
$appId = $project -> getAttribute ( 'usersOauth2' . \ucfirst ( $provider ) . 'Appid' , '' );
$appSecret = $project -> getAttribute ( 'usersOauth2' . \ucfirst ( $provider ) . 'Secret' , '{}' );
2020-01-06 00:29:42 +13:00
2020-06-20 23:20:49 +12:00
$appSecret = \json_decode ( $appSecret , true );
2020-01-06 00:29:42 +13:00
if ( ! empty ( $appSecret ) && isset ( $appSecret [ 'version' ])) {
$key = $request -> getServer ( '_APP_OPENSSL_KEY_V' . $appSecret [ 'version' ]);
2020-06-20 23:20:49 +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
}
if ( empty ( $appId ) || empty ( $appSecret )) {
2020-04-11 06:59:14 +12:00
throw new Exception ( 'This provider is disabled. Please configure the provider app ID and app secret key from your ' . APP_NAME . ' console to continue.' , 412 );
2020-01-06 00:29:42 +13:00
}
2020-06-20 23:20:49 +12:00
$classname = 'Appwrite\\Auth\\OAuth2\\' . \ucfirst ( $provider );
2020-01-06 00:29:42 +13:00
2020-06-20 23:20:49 +12:00
if ( ! \class_exists ( $classname )) {
2020-01-06 00:29:42 +13:00
throw new Exception ( 'Provider is not supported' , 501 );
}
2020-06-17 07:37:46 +12:00
$oauth2 = new $classname ( $appId , $appSecret , $callback , [ 'success' => $success , 'failure' => $failure ], $scopes );
2020-01-06 00:29:42 +13:00
2020-04-08 23:21:41 +12:00
$response
-> addHeader ( 'Cache-Control' , 'no-store, no-cache, must-revalidate, max-age=0' )
-> addHeader ( 'Pragma' , 'no-cache' )
-> redirect ( $oauth2 -> getLoginURL ());
2020-01-06 00:29:42 +13:00
}
);
2020-02-17 00:41:03 +13:00
$utopia -> get ( '/v1/account/sessions/oauth2/callback/:provider/:projectId' )
-> desc ( 'OAuth2 Callback' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2020-01-12 10:53:57 +13:00
-> label ( 'error' , __DIR__ . '/../../views/general/error.phtml' )
2020-01-06 00:29:42 +13:00
-> label ( 'scope' , 'public' )
-> label ( 'docs' , false )
2020-02-10 18:54:26 +13:00
-> param ( 'projectId' , '' , function () { return new Text ( 1024 ); }, 'Project unique ID.' )
2020-06-20 23:20:49 +12:00
-> param ( 'provider' , '' , function () { return new WhiteList ( \array_keys ( Config :: getParam ( 'providers' ))); }, 'OAuth2 provider.' )
2020-02-17 00:41:03 +13:00
-> param ( 'code' , '' , function () { return new Text ( 1024 ); }, 'OAuth2 code.' )
2020-02-10 18:54:26 +13:00
-> param ( 'state' , '' , function () { return new Text ( 2048 ); }, 'Login state params.' , true )
2020-01-06 00:29:42 +13:00
-> action (
2020-03-29 01:42:16 +13:00
function ( $projectId , $provider , $code , $state ) use ( $response ) {
$domain = Config :: getParam ( 'domain' );
$protocol = Config :: getParam ( 'protocol' );
2020-04-08 23:21:41 +12:00
$response
-> addHeader ( 'Cache-Control' , 'no-store, no-cache, must-revalidate, max-age=0' )
-> addHeader ( 'Pragma' , 'no-cache' )
-> redirect ( $protocol . '://' . $domain . '/v1/account/sessions/oauth2/' . $provider . '/redirect?'
2020-06-20 23:20:49 +12:00
. \http_build_query ([ 'project' => $projectId , 'code' => $code , 'state' => $state ]));
2020-01-06 00:29:42 +13:00
}
);
2020-05-30 00:02:53 +12:00
$utopia -> post ( '/v1/account/sessions/oauth2/callback/:provider/:projectId' )
-> desc ( 'OAuth2 Callback' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2020-05-30 00:02:53 +12:00
-> label ( 'error' , __DIR__ . '/../../views/general/error.phtml' )
-> label ( 'scope' , 'public' )
-> label ( 'origin' , '*' )
-> label ( 'docs' , false )
-> param ( 'projectId' , '' , function () { return new Text ( 1024 ); }, 'Project unique ID.' )
2020-06-20 23:20:49 +12:00
-> param ( 'provider' , '' , function () { return new WhiteList ( \array_keys ( Config :: getParam ( 'providers' ))); }, 'OAuth2 provider.' )
2020-05-30 00:02:53 +12:00
-> param ( 'code' , '' , function () { return new Text ( 1024 ); }, 'OAuth2 code.' )
-> param ( 'state' , '' , function () { return new Text ( 2048 ); }, 'Login state params.' , true )
-> action (
function ( $projectId , $provider , $code , $state ) use ( $response ) {
$domain = Config :: getParam ( 'domain' );
$protocol = Config :: getParam ( 'protocol' );
$response
-> addHeader ( 'Cache-Control' , 'no-store, no-cache, must-revalidate, max-age=0' )
-> addHeader ( 'Pragma' , 'no-cache' )
-> redirect ( $protocol . '://' . $domain . '/v1/account/sessions/oauth2/' . $provider . '/redirect?'
2020-06-20 23:20:49 +12:00
. \http_build_query ([ 'project' => $projectId , 'code' => $code , 'state' => $state ]));
2020-05-30 00:02:53 +12:00
}
);
2020-02-17 00:41:03 +13:00
$utopia -> get ( '/v1/account/sessions/oauth2/:provider/redirect' )
-> desc ( 'OAuth2 Redirect' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2020-01-12 10:53:57 +13:00
-> label ( 'error' , __DIR__ . '/../../views/general/error.phtml' )
2020-01-06 00:29:42 +13:00
-> label ( 'webhook' , 'account.sessions.create' )
-> label ( 'scope' , 'public' )
-> label ( 'abuse-limit' , 50 )
-> label ( 'abuse-key' , 'ip:{ip}' )
-> label ( 'docs' , false )
2020-06-20 23:20:49 +12:00
-> param ( 'provider' , '' , function () { return new WhiteList ( \array_keys ( Config :: getParam ( 'providers' ))); }, 'OAuth2 provider.' )
2020-02-17 00:41:03 +13:00
-> param ( 'code' , '' , function () { return new Text ( 1024 ); }, 'OAuth2 code.' )
-> param ( 'state' , '' , function () { return new Text ( 2048 ); }, 'OAuth2 state params.' , true )
2020-01-06 00:29:42 +13:00
-> action (
2020-04-09 01:38:36 +12:00
function ( $provider , $code , $state ) use ( $response , $request , $user , $projectDB , $project , $audit , $oauthDefaultSuccess ) {
2020-03-29 01:42:16 +13:00
$protocol = Config :: getParam ( 'protocol' );
2020-02-27 22:17:09 +13:00
$callback = $protocol . '://' . $request -> getServer ( 'HTTP_HOST' ) . '/v1/account/sessions/oauth2/callback/' . $provider . '/' . $project -> getId ();
2020-01-06 00:29:42 +13:00
$defaultState = [ 'success' => $project -> getAttribute ( 'url' , '' ), 'failure' => '' ];
$validateURL = new URL ();
2020-06-20 23:20:49 +12:00
$appId = $project -> getAttribute ( 'usersOauth2' . \ucfirst ( $provider ) . 'Appid' , '' );
$appSecret = $project -> getAttribute ( 'usersOauth2' . \ucfirst ( $provider ) . 'Secret' , '{}' );
2020-01-06 00:29:42 +13:00
2020-06-20 23:20:49 +12:00
$appSecret = \json_decode ( $appSecret , true );
2020-01-06 00:29:42 +13:00
if ( ! empty ( $appSecret ) && isset ( $appSecret [ 'version' ])) {
$key = $request -> getServer ( '_APP_OPENSSL_KEY_V' . $appSecret [ 'version' ]);
2020-06-20 23:20:49 +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-20 23:20:49 +12:00
$classname = 'Appwrite\\Auth\\OAuth2\\' . \ucfirst ( $provider );
2020-01-06 00:29:42 +13:00
2020-06-20 23:20:49 +12:00
if ( ! \class_exists ( $classname )) {
2020-01-06 00:29:42 +13:00
throw new Exception ( 'Provider is not supported' , 501 );
}
2020-02-17 00:41:03 +13:00
$oauth2 = new $classname ( $appId , $appSecret , $callback );
2020-01-06 00:29:42 +13:00
if ( ! empty ( $state )) {
try {
2020-06-20 23:20:49 +12:00
$state = \array_merge ( $defaultState , $oauth2 -> parseState ( $state ));
2020-01-06 00:29:42 +13:00
} catch ( \Exception $exception ) {
2020-02-17 00:41:03 +13:00
throw new Exception ( 'Failed to parse login state params as passed from OAuth2 provider' );
2020-01-06 00:29:42 +13:00
}
} else {
$state = $defaultState ;
}
if ( ! $validateURL -> isValid ( $state [ 'success' ])) {
throw new Exception ( 'Invalid redirect URL for success login' , 400 );
}
if ( ! empty ( $state [ 'failure' ]) && ! $validateURL -> isValid ( $state [ 'failure' ])) {
throw new Exception ( 'Invalid redirect URL for failure login' , 400 );
}
2020-05-30 00:02:53 +12:00
2020-01-14 04:15:52 +13:00
$state [ 'failure' ] = null ;
2020-02-17 00:41:03 +13:00
$accessToken = $oauth2 -> getAccessToken ( $code );
2020-01-06 00:29:42 +13:00
if ( empty ( $accessToken )) {
if ( ! empty ( $state [ 'failure' ])) {
$response -> redirect ( $state [ 'failure' ], 301 , 0 );
}
throw new Exception ( 'Failed to obtain access token' );
}
2020-02-17 00:41:03 +13:00
$oauth2ID = $oauth2 -> getUserID ( $accessToken );
2020-01-14 04:15:52 +13:00
2020-02-17 00:41:03 +13:00
if ( empty ( $oauth2ID )) {
2020-01-06 00:29:42 +13:00
if ( ! empty ( $state [ 'failure' ])) {
$response -> redirect ( $state [ 'failure' ], 301 , 0 );
}
2020-02-17 00:41:03 +13:00
throw new Exception ( 'Missing ID from OAuth2 provider' , 400 );
2020-01-06 00:29:42 +13:00
}
$current = Auth :: tokenVerify ( $user -> getAttribute ( 'tokens' , []), Auth :: TOKEN_TYPE_LOGIN , Auth :: $secret );
if ( $current ) {
$projectDB -> deleteDocument ( $current ); //throw new Exception('User already logged in', 401);
}
2020-06-27 02:41:13 +12:00
$user = ( empty ( $user -> getId ())) ? $projectDB -> getCollectionFirst ([ // Get user by provider id
2020-01-06 00:29:42 +13:00
'limit' => 1 ,
'filters' => [
'$collection=' . Database :: SYSTEM_COLLECTION_USERS ,
2020-06-20 23:20:49 +12:00
'oauth2' . \ucfirst ( $provider ) . '=' . $oauth2ID ,
2020-01-06 00:29:42 +13:00
],
]) : $user ;
2020-02-17 00:41:03 +13:00
if ( empty ( $user )) { // No user logged in or with OAuth2 provider ID, create new one or connect with account with same email
$name = $oauth2 -> getUserName ( $accessToken );
$email = $oauth2 -> getUserEmail ( $accessToken );
2020-01-06 00:29:42 +13:00
2020-06-27 02:41:13 +12:00
$user = $projectDB -> getCollectionFirst ([ // Get user by provider email address
2020-01-06 00:29:42 +13:00
'limit' => 1 ,
'filters' => [
'$collection=' . Database :: SYSTEM_COLLECTION_USERS ,
'email=' . $email ,
],
]);
2020-02-17 20:16:11 +13:00
if ( ! $user || empty ( $user -> getId ())) { // Last option -> create user alone, generate random password
2020-01-06 00:29:42 +13:00
Authorization :: disable ();
2020-03-22 10:10:06 +13:00
try {
$user = $projectDB -> createDocument ([
'$collection' => Database :: SYSTEM_COLLECTION_USERS ,
'$permissions' => [ 'read' => [ '*' ], 'write' => [ 'user:{self}' ]],
'email' => $email ,
'emailVerification' => true ,
'status' => Auth :: USER_STATUS_ACTIVATED , // Email should already be authenticated by OAuth2 provider
'password' => Auth :: passwordHash ( Auth :: passwordGenerator ()),
2020-06-20 23:20:49 +12:00
'password-update' => \time (),
'registration' => \time (),
2020-03-22 10:10:06 +13:00
'reset' => false ,
'name' => $name ,
], [ 'email' => $email ]);
} catch ( Duplicate $th ) {
throw new Exception ( 'Account already exists' , 409 );
}
2020-01-06 00:29:42 +13:00
Authorization :: enable ();
if ( false === $user ) {
throw new Exception ( 'Failed saving user to DB' , 500 );
}
}
}
2020-02-17 00:41:03 +13:00
// Create session token, verify user account and update OAuth2 ID and Access Token
2020-01-06 00:29:42 +13:00
$secret = Auth :: tokenGenerator ();
2020-06-20 23:20:49 +12:00
$expiry = \time () + Auth :: TOKEN_EXPIRATION_LOGIN_LONG ;
2020-01-12 02:58:02 +13:00
$session = new Document ([
'$collection' => Database :: SYSTEM_COLLECTION_TOKENS ,
2020-02-17 20:16:11 +13:00
'$permissions' => [ 'read' => [ 'user:' . $user [ '$id' ]], 'write' => [ 'user:' . $user [ '$id' ]]],
2020-01-12 02:58:02 +13:00
'type' => Auth :: TOKEN_TYPE_LOGIN ,
'secret' => Auth :: hash ( $secret ), // On way hash encryption to protect DB leak
'expire' => $expiry ,
'userAgent' => $request -> getServer ( 'HTTP_USER_AGENT' , 'UNKNOWN' ),
'ip' => $request -> getIP (),
]);
2020-01-06 00:29:42 +13:00
$user
2020-06-20 23:20:49 +12:00
-> setAttribute ( 'oauth2' . \ucfirst ( $provider ), $oauth2ID )
-> setAttribute ( 'oauth2' . \ucfirst ( $provider ) . 'AccessToken' , $accessToken )
2020-01-06 00:29:42 +13:00
-> setAttribute ( 'status' , Auth :: USER_STATUS_ACTIVATED )
2020-01-12 02:58:02 +13:00
-> setAttribute ( 'tokens' , $session , Document :: SET_TYPE_APPEND )
2020-01-06 00:29:42 +13:00
;
2020-02-17 20:16:11 +13:00
Authorization :: setRole ( 'user:' . $user -> getId ());
2020-01-06 00:29:42 +13:00
$user = $projectDB -> updateDocument ( $user -> getArrayCopy ());
if ( false === $user ) {
throw new Exception ( 'Failed saving user to DB' , 500 );
}
$audit
2020-02-17 20:16:11 +13:00
-> setParam ( 'userId' , $user -> getId ())
2020-01-06 00:29:42 +13:00
-> setParam ( 'event' , 'account.sessions.create' )
2020-02-17 20:16:11 +13:00
-> setParam ( 'resource' , 'users/' . $user -> getId ())
2020-01-06 00:29:42 +13:00
-> setParam ( 'data' , [ 'provider' => $provider ])
;
2020-06-25 08:59:04 +12:00
if ( ! Config :: getParam ( 'domainVerification' )) {
2020-03-18 00:36:13 +13:00
$response
2020-06-20 23:20:49 +12:00
-> addHeader ( 'X-Fallback-Cookies' , \json_encode ([ Auth :: $cookieName => Auth :: encodeSession ( $user -> getId (), $secret )]))
2020-03-18 00:36:13 +13:00
;
}
2020-06-28 19:59:52 +12:00
// Add keys for non-web platforms - TODO - add verification phase to aviod session sniffing
if ( parse_url ( $state [ 'success' ], PHP_URL_PATH ) === $oauthDefaultSuccess ) {
2020-04-11 06:59:14 +12:00
$state [ 'success' ] = URLParser :: parse ( $state [ 'success' ]);
$query = URLParser :: parseQuery ( $state [ 'success' ][ 'query' ]);
2020-05-17 23:11:43 +12:00
$query [ 'project' ] = $project -> getId ();
2020-04-11 06:59:14 +12:00
$query [ 'domain' ] = COOKIE_DOMAIN ;
$query [ 'key' ] = Auth :: $cookieName ;
$query [ 'secret' ] = Auth :: encodeSession ( $user -> getId (), $secret );
$state [ 'success' ][ 'query' ] = URLParser :: unparseQuery ( $query );
$state [ 'success' ] = URLParser :: unparse ( $state [ 'success' ]);
2020-04-09 01:38:36 +12:00
}
2020-01-06 00:29:42 +13:00
$response
2020-04-08 23:21:41 +12:00
-> addHeader ( 'Cache-Control' , 'no-store, no-cache, must-revalidate, max-age=0' )
-> addHeader ( 'Pragma' , 'no-cache' )
2020-02-27 22:17:09 +13:00
-> addCookie ( Auth :: $cookieName . '_legacy' , Auth :: encodeSession ( $user -> getId (), $secret ), $expiry , '/' , COOKIE_DOMAIN , ( 'https' == $protocol ), true , null )
-> addCookie ( Auth :: $cookieName , Auth :: encodeSession ( $user -> getId (), $secret ), $expiry , '/' , COOKIE_DOMAIN , ( 'https' == $protocol ), true , COOKIE_SAMESITE )
2020-01-15 09:50:49 +13:00
-> redirect ( $state [ 'success' ])
2020-01-06 00:29:42 +13:00
;
}
);
2020-02-01 11:34:07 +13:00
$utopia -> get ( '/v1/account' )
-> desc ( 'Get Account' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2020-02-01 11:34:07 +13:00
-> label ( 'scope' , 'account' )
-> label ( 'sdk.platform' , [ APP_PLATFORM_CLIENT ])
-> label ( 'sdk.namespace' , 'account' )
-> label ( 'sdk.method' , 'get' )
-> label ( 'sdk.description' , '/docs/references/account/get.md' )
-> label ( 'sdk.response' , [ '200' => 'user' ])
-> action (
2020-04-11 06:59:14 +12:00
function () use ( $response , & $user , $oauth2Keys ) {
2020-06-20 23:20:49 +12:00
$response -> json ( \array_merge ( $user -> getArrayCopy ( \array_merge (
2020-02-01 11:34:07 +13:00
[
2020-02-17 20:16:11 +13:00
'$id' ,
2020-02-01 11:34:07 +13:00
'email' ,
2020-03-22 01:35:46 +13:00
'emailVerification' ,
2020-02-01 11:34:07 +13:00
'registration' ,
'name' ,
],
2020-02-17 00:41:03 +13:00
$oauth2Keys
2020-02-01 11:34:07 +13:00
)), [ 'roles' => Authorization :: getRoles ()]));
}
);
$utopia -> get ( '/v1/account/prefs' )
-> desc ( 'Get Account Preferences' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2020-02-01 11:34:07 +13:00
-> label ( 'scope' , 'account' )
-> label ( 'sdk.platform' , [ APP_PLATFORM_CLIENT ])
-> label ( 'sdk.namespace' , 'account' )
-> label ( 'sdk.method' , 'getPrefs' )
-> label ( 'sdk.description' , '/docs/references/account/get-prefs.md' )
-> action (
function () use ( $response , $user ) {
$prefs = $user -> getAttribute ( 'prefs' , '{}' );
try {
2020-06-20 23:20:49 +12:00
$prefs = \json_decode ( $prefs , true );
2020-02-01 11:34:07 +13:00
$prefs = ( $prefs ) ? $prefs : [];
} catch ( \Exception $error ) {
throw new Exception ( 'Failed to parse prefs' , 500 );
}
$response -> json ( $prefs );
}
);
$utopia -> get ( '/v1/account/sessions' )
-> desc ( 'Get Account Sessions' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2020-02-01 11:34:07 +13:00
-> label ( 'scope' , 'account' )
-> label ( 'sdk.platform' , [ APP_PLATFORM_CLIENT ])
-> label ( 'sdk.namespace' , 'account' )
-> label ( 'sdk.method' , 'getSessions' )
-> label ( 'sdk.description' , '/docs/references/account/get-sessions.md' )
-> action (
function () use ( $response , $user ) {
$tokens = $user -> getAttribute ( 'tokens' , []);
$reader = new Reader ( __DIR__ . '/../../db/DBIP/dbip-country-lite-2020-01.mmdb' );
$sessions = [];
$current = Auth :: tokenVerify ( $tokens , Auth :: TOKEN_TYPE_LOGIN , Auth :: $secret );
$index = 0 ;
$countries = Locale :: getText ( 'countries' );
foreach ( $tokens as $token ) { /* @var $token Document */
if ( Auth :: TOKEN_TYPE_LOGIN != $token -> getAttribute ( 'type' )) {
continue ;
}
$userAgent = ( ! empty ( $token -> getAttribute ( 'userAgent' ))) ? $token -> getAttribute ( 'userAgent' ) : 'UNKNOWN' ;
$dd = new DeviceDetector ( $userAgent );
// OPTIONAL: If called, bot detection will completely be skipped (bots will be detected as regular devices then)
// $dd->skipBotDetection();
$dd -> parse ();
$sessions [ $index ] = [
2020-02-17 20:16:11 +13:00
'$id' => $token -> getId (),
2020-02-01 11:34:07 +13:00
'OS' => $dd -> getOs (),
'client' => $dd -> getClient (),
'device' => $dd -> getDevice (),
'brand' => $dd -> getBrand (),
'model' => $dd -> getModel (),
'ip' => $token -> getAttribute ( 'ip' , '' ),
'geo' => [],
2020-02-17 20:16:11 +13:00
'current' => ( $current == $token -> getId ()) ? true : false ,
2020-02-01 11:34:07 +13:00
];
try {
$record = $reader -> country ( $token -> getAttribute ( 'ip' , '' ));
2020-06-20 23:20:49 +12:00
$sessions [ $index ][ 'geo' ][ 'isoCode' ] = \strtolower ( $record -> country -> isoCode );
2020-02-01 11:34:07 +13:00
$sessions [ $index ][ 'geo' ][ 'country' ] = ( isset ( $countries [ $record -> country -> isoCode ])) ? $countries [ $record -> country -> isoCode ] : Locale :: getText ( 'locale.country.unknown' );
} catch ( \Exception $e ) {
$sessions [ $index ][ 'geo' ][ 'isoCode' ] = '--' ;
$sessions [ $index ][ 'geo' ][ 'country' ] = Locale :: getText ( 'locale.country.unknown' );
}
++ $index ;
}
$response -> json ( $sessions );
}
);
$utopia -> get ( '/v1/account/logs' )
-> desc ( 'Get Account Logs' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2020-02-01 11:34:07 +13:00
-> label ( 'scope' , 'account' )
-> label ( 'sdk.platform' , [ APP_PLATFORM_CLIENT ])
-> label ( 'sdk.namespace' , 'account' )
-> label ( 'sdk.method' , 'getLogs' )
-> label ( 'sdk.description' , '/docs/references/account/get-logs.md' )
-> action (
function () use ( $response , $register , $project , $user ) {
$adapter = new AuditAdapter ( $register -> get ( 'db' ));
2020-02-17 20:16:11 +13:00
$adapter -> setNamespace ( 'app_' . $project -> getId ());
2020-02-01 11:34:07 +13:00
$audit = new Audit ( $adapter );
$countries = Locale :: getText ( 'countries' );
2020-02-17 20:16:11 +13:00
$logs = $audit -> getLogsByUserAndActions ( $user -> getId (), [
2020-02-01 11:34:07 +13:00
'account.create' ,
'account.delete' ,
'account.update.name' ,
'account.update.email' ,
'account.update.password' ,
'account.update.prefs' ,
'account.sessions.create' ,
'account.sessions.delete' ,
2020-02-12 11:24:30 +13:00
'account.recovery.create' ,
'account.recovery.update' ,
'account.verification.create' ,
'account.verification.update' ,
'teams.membership.create' ,
'teams.membership.update' ,
'teams.membership.delete' ,
2020-02-01 11:34:07 +13:00
]);
$reader = new Reader ( __DIR__ . '/../../db/DBIP/dbip-country-lite-2020-01.mmdb' );
$output = [];
foreach ( $logs as $i => & $log ) {
$log [ 'userAgent' ] = ( ! empty ( $log [ 'userAgent' ])) ? $log [ 'userAgent' ] : 'UNKNOWN' ;
$dd = new DeviceDetector ( $log [ 'userAgent' ]);
$dd -> skipBotDetection (); // OPTIONAL: If called, bot detection will completely be skipped (bots will be detected as regular devices then)
$dd -> parse ();
$output [ $i ] = [
'event' => $log [ 'event' ],
'ip' => $log [ 'ip' ],
2020-06-20 23:20:49 +12:00
'time' => \strtotime ( $log [ 'time' ]),
2020-02-01 11:34:07 +13:00
'OS' => $dd -> getOs (),
'client' => $dd -> getClient (),
'device' => $dd -> getDevice (),
'brand' => $dd -> getBrand (),
'model' => $dd -> getModel (),
'geo' => [],
];
try {
$record = $reader -> country ( $log [ 'ip' ]);
2020-06-20 23:20:49 +12:00
$output [ $i ][ 'geo' ][ 'isoCode' ] = \strtolower ( $record -> country -> isoCode );
2020-02-01 11:34:07 +13:00
$output [ $i ][ 'geo' ][ 'country' ] = $record -> country -> name ;
$output [ $i ][ 'geo' ][ 'country' ] = ( isset ( $countries [ $record -> country -> isoCode ])) ? $countries [ $record -> country -> isoCode ] : Locale :: getText ( 'locale.country.unknown' );
} catch ( \Exception $e ) {
$output [ $i ][ 'geo' ][ 'isoCode' ] = '--' ;
$output [ $i ][ 'geo' ][ 'country' ] = Locale :: getText ( 'locale.country.unknown' );
}
}
$response -> json ( $output );
}
);
2019-05-09 18:54:39 +12:00
$utopia -> patch ( '/v1/account/name' )
-> desc ( 'Update Account Name' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2020-01-05 04:45:28 +13:00
-> label ( 'webhook' , 'account.update.name' )
2019-05-09 18:54:39 +12:00
-> label ( 'scope' , 'account' )
2020-01-27 19:14:14 +13:00
-> label ( 'sdk.platform' , [ APP_PLATFORM_CLIENT ])
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-02-10 18:54:26 +13:00
-> param ( 'name' , '' , function () { return new Text ( 100 ); }, 'User name.' )
2019-05-09 18:54:39 +12:00
-> action (
2020-02-17 00:41:03 +13:00
function ( $name ) use ( $response , $user , $projectDB , $audit , $oauth2Keys ) {
2020-06-20 23:20:49 +12:00
$user = $projectDB -> updateDocument ( \array_merge ( $user -> getArrayCopy (), [
2019-05-09 18:54:39 +12:00
'name' => $name ,
]));
2019-09-07 05:10:41 +12:00
if ( false === $user ) {
2019-05-09 18:54:39 +12:00
throw new Exception ( 'Failed saving user to DB' , 500 );
}
2020-01-06 00:29:42 +13:00
$audit
2020-02-17 20:16:11 +13:00
-> setParam ( 'userId' , $user -> getId ())
2020-01-06 00:29:42 +13:00
-> setParam ( 'event' , 'account.update.name' )
2020-02-17 20:16:11 +13:00
-> setParam ( 'resource' , 'users/' . $user -> getId ())
2020-01-06 00:29:42 +13:00
;
2019-05-09 18:54:39 +12:00
2020-06-20 23:20:49 +12:00
$response -> json ( \array_merge ( $user -> getArrayCopy ( \array_merge (
2020-01-12 02:58:02 +13:00
[
2020-02-17 20:16:11 +13:00
'$id' ,
2020-01-12 02:58:02 +13:00
'email' ,
'registration' ,
'name' ,
],
2020-02-17 00:41:03 +13:00
$oauth2Keys
2020-01-12 02:58:02 +13:00
)), [ 'roles' => Authorization :: getRoles ()]));
2019-05-09 18:54:39 +12:00
}
);
$utopia -> patch ( '/v1/account/password' )
-> desc ( 'Update Account Password' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2020-01-05 04:45:28 +13:00
-> label ( 'webhook' , 'account.update.password' )
2019-05-09 18:54:39 +12:00
-> label ( 'scope' , 'account' )
2020-01-27 19:14:14 +13:00
-> label ( 'sdk.platform' , [ APP_PLATFORM_CLIENT ])
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-05-31 10:24:05 +12:00
-> param ( 'password' , '' , function () { return new Password (); }, 'New user password. Must be between 6 to 32 chars.' )
-> param ( 'oldPassword' , '' , function () { return new Password (); }, 'Old user password. Must be between 6 to 32 chars.' )
2019-05-09 18:54:39 +12:00
-> action (
2020-02-17 00:41:03 +13:00
function ( $password , $oldPassword ) use ( $response , $user , $projectDB , $audit , $oauth2Keys ) {
2019-09-07 05:10:41 +12:00
if ( ! Auth :: passwordVerify ( $oldPassword , $user -> getAttribute ( 'password' ))) { // Double check user password
2019-05-09 18:54:39 +12:00
throw new Exception ( 'Invalid credentials' , 401 );
}
2020-06-20 23:20:49 +12:00
$user = $projectDB -> updateDocument ( \array_merge ( $user -> getArrayCopy (), [
2019-05-09 18:54:39 +12:00
'password' => Auth :: passwordHash ( $password ),
]));
2019-09-07 05:10:41 +12:00
if ( false === $user ) {
2019-05-09 18:54:39 +12:00
throw new Exception ( 'Failed saving user to DB' , 500 );
}
2020-01-06 00:29:42 +13:00
$audit
2020-02-17 20:16:11 +13:00
-> setParam ( 'userId' , $user -> getId ())
2020-01-06 00:29:42 +13:00
-> setParam ( 'event' , 'account.update.password' )
2020-02-17 20:16:11 +13:00
-> setParam ( 'resource' , 'users/' . $user -> getId ())
2020-01-06 00:29:42 +13:00
;
2019-05-09 18:54:39 +12:00
2020-06-20 23:20:49 +12:00
$response -> json ( \array_merge ( $user -> getArrayCopy ( \array_merge (
2020-01-12 02:58:02 +13:00
[
2020-02-17 20:16:11 +13:00
'$id' ,
2020-01-12 02:58:02 +13:00
'email' ,
'registration' ,
'name' ,
],
2020-02-17 00:41:03 +13:00
$oauth2Keys
2020-01-12 02:58:02 +13:00
)), [ 'roles' => Authorization :: getRoles ()]));
2019-05-09 18:54:39 +12:00
}
);
$utopia -> patch ( '/v1/account/email' )
-> desc ( 'Update Account Email' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2020-01-05 04:45:28 +13:00
-> label ( 'webhook' , 'account.update.email' )
2019-05-09 18:54:39 +12:00
-> label ( 'scope' , 'account' )
2020-01-27 19:14:14 +13:00
-> label ( 'sdk.platform' , [ APP_PLATFORM_CLIENT ])
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-02-10 18:58:29 +13:00
-> param ( 'email' , '' , function () { return new Email (); }, 'User email.' )
2020-05-31 10:24:05 +12:00
-> param ( 'password' , '' , function () { return new Password (); }, 'User password. Must be between 6 to 32 chars.' )
2019-05-09 18:54:39 +12:00
-> action (
2020-02-17 00:41:03 +13:00
function ( $email , $password ) use ( $response , $user , $projectDB , $audit , $oauth2Keys ) {
2019-09-07 05:10:41 +12:00
if ( ! Auth :: passwordVerify ( $password , $user -> getAttribute ( 'password' ))) { // Double check user password
2019-05-09 18:54:39 +12:00
throw new Exception ( 'Invalid credentials' , 401 );
}
2020-06-27 02:41:13 +12:00
$profile = $projectDB -> getCollectionFirst ([ // Get user by email address
2019-07-21 23:43:06 +12:00
'limit' => 1 ,
'filters' => [
2019-09-07 05:10:41 +12:00
'$collection=' . Database :: SYSTEM_COLLECTION_USERS ,
'email=' . $email ,
],
2019-07-21 23:43:06 +12:00
]);
2019-09-07 05:10:41 +12:00
if ( ! empty ( $profile )) {
2019-07-21 23:43:06 +12:00
throw new Exception ( 'User already registered' , 400 );
}
2019-05-09 18:54:39 +12:00
// TODO after this user needs to confirm mail again
2020-06-20 23:20:49 +12:00
$user = $projectDB -> updateDocument ( \array_merge ( $user -> getArrayCopy (), [
2019-05-09 18:54:39 +12:00
'email' => $email ,
2020-02-10 10:37:28 +13:00
'emailVerification' => false ,
2019-05-09 18:54:39 +12:00
]));
2019-09-07 05:10:41 +12:00
if ( false === $user ) {
2019-05-09 18:54:39 +12:00
throw new Exception ( 'Failed saving user to DB' , 500 );
}
2020-01-06 00:29:42 +13:00
$audit
2020-02-17 20:16:11 +13:00
-> setParam ( 'userId' , $user -> getId ())
2020-01-06 00:29:42 +13:00
-> setParam ( 'event' , 'account.update.email' )
2020-02-17 20:16:11 +13:00
-> setParam ( 'resource' , 'users/' . $user -> getId ())
2020-01-06 00:29:42 +13:00
;
2019-05-09 18:54:39 +12:00
2020-06-20 23:20:49 +12:00
$response -> json ( \array_merge ( $user -> getArrayCopy ( \array_merge (
2020-01-12 02:58:02 +13:00
[
2020-02-17 20:16:11 +13:00
'$id' ,
2020-01-12 02:58:02 +13:00
'email' ,
'registration' ,
'name' ,
],
2020-02-17 00:41:03 +13:00
$oauth2Keys
2020-01-12 02:58:02 +13:00
)), [ 'roles' => Authorization :: getRoles ()]));
2019-05-09 18:54:39 +12:00
}
);
$utopia -> patch ( '/v1/account/prefs' )
2020-01-06 00:29:42 +13:00
-> desc ( 'Update Account Preferences' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2020-01-05 04:45:28 +13:00
-> label ( 'webhook' , 'account.update.prefs' )
2019-05-09 18:54:39 +12:00
-> label ( 'scope' , 'account' )
2020-01-27 19:14:14 +13:00
-> label ( 'sdk.platform' , [ APP_PLATFORM_CLIENT ])
2019-05-09 18:54:39 +12:00
-> label ( 'sdk.namespace' , 'account' )
-> label ( 'sdk.method' , 'updatePrefs' )
2020-01-19 08:07:02 +13:00
-> param ( 'prefs' , '' , function () { return new Assoc ();}, 'Prefs key-value JSON object.' )
2019-10-08 20:21:54 +13:00
-> label ( 'sdk.description' , '/docs/references/account/update-prefs.md' )
2019-05-09 18:54:39 +12:00
-> action (
2019-09-07 05:10:41 +12:00
function ( $prefs ) use ( $response , $user , $projectDB , $audit ) {
2020-06-20 23:20:49 +12:00
$old = \json_decode ( $user -> getAttribute ( 'prefs' , '{}' ), true );
2020-01-19 08:07:02 +13:00
$old = ( $old ) ? $old : [];
2020-06-20 23:20:49 +12:00
$user = $projectDB -> updateDocument ( \array_merge ( $user -> getArrayCopy (), [
'prefs' => \json_encode ( \array_merge ( $old , $prefs )),
2019-05-09 18:54:39 +12:00
]));
2019-09-07 05:10:41 +12:00
if ( false === $user ) {
2019-05-09 18:54:39 +12:00
throw new Exception ( 'Failed saving user to DB' , 500 );
}
2020-01-06 00:29:42 +13:00
$audit
-> setParam ( 'event' , 'account.update.prefs' )
2020-02-17 20:16:11 +13:00
-> setParam ( 'resource' , 'users/' . $user -> getId ())
2020-01-06 00:29:42 +13:00
;
2019-05-09 18:54:39 +12:00
2020-01-12 02:58:02 +13:00
$prefs = $user -> getAttribute ( 'prefs' , '{}' );
try {
2020-06-20 23:20:49 +12:00
$prefs = \json_decode ( $prefs , true );
2020-01-19 08:07:02 +13:00
$prefs = ( $prefs ) ? $prefs : [];
2020-01-12 02:58:02 +13:00
} catch ( \Exception $error ) {
2020-01-19 08:07:02 +13:00
throw new Exception ( 'Failed to parse prefs' , 500 );
2020-01-12 02:58:02 +13:00
}
$response -> json ( $prefs );
2019-05-09 18:54:39 +12:00
}
);
$utopia -> delete ( '/v1/account' )
-> desc ( 'Delete Account' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2019-05-09 18:54:39 +12:00
-> label ( 'webhook' , 'account.delete' )
-> label ( 'scope' , 'account' )
2020-01-27 19:14:14 +13:00
-> label ( 'sdk.platform' , [ APP_PLATFORM_CLIENT ])
2019-05-09 18:54:39 +12:00
-> label ( 'sdk.namespace' , 'account' )
-> label ( 'sdk.method' , 'delete' )
2019-10-08 20:21:54 +13:00
-> label ( 'sdk.description' , '/docs/references/account/delete.md' )
2019-05-09 18:54:39 +12:00
-> action (
2020-03-29 01:42:16 +13:00
function () use ( $response , $user , $projectDB , $audit , $webhook ) {
$protocol = Config :: getParam ( 'protocol' );
2020-06-20 23:20:49 +12:00
$user = $projectDB -> updateDocument ( \array_merge ( $user -> getArrayCopy (), [
2019-05-09 18:54:39 +12:00
'status' => Auth :: USER_STATUS_BLOCKED ,
]));
2019-09-07 05:10:41 +12:00
if ( false === $user ) {
2019-05-09 18:54:39 +12:00
throw new Exception ( 'Failed saving user to DB' , 500 );
}
//TODO delete all tokens or only current session?
//TODO delete all user data according to GDPR. Make sure everything is backed up and backups are deleted later
2019-09-07 05:10:41 +12:00
/*
2019-05-09 18:54:39 +12:00
* Data to delete
* * Tokens
* * Memberships
*/
$audit
2020-02-17 20:16:11 +13:00
-> setParam ( 'userId' , $user -> getId ())
2019-05-09 18:54:39 +12:00
-> setParam ( 'event' , 'account.delete' )
2020-02-17 20:16:11 +13:00
-> setParam ( 'resource' , 'users/' . $user -> getId ())
2019-05-09 18:54:39 +12:00
-> setParam ( 'data' , $user -> getArrayCopy ())
;
2020-01-06 00:29:42 +13:00
$webhook
-> setParam ( 'payload' , [
'name' => $user -> getAttribute ( 'name' , '' ),
'email' => $user -> getAttribute ( 'email' , '' ),
])
;
2020-06-25 08:59:04 +12:00
if ( ! Config :: getParam ( 'domainVerification' )) {
2020-03-18 00:36:13 +13:00
$response
2020-06-20 23:20:49 +12:00
-> addHeader ( 'X-Fallback-Cookies' , \json_encode ([]))
2020-03-18 00:36:13 +13:00
;
}
2019-05-09 18:54:39 +12:00
$response
2020-06-20 23:20:49 +12:00
-> addCookie ( Auth :: $cookieName . '_legacy' , '' , \time () - 3600 , '/' , COOKIE_DOMAIN , ( 'https' == $protocol ), true , null )
-> addCookie ( Auth :: $cookieName , '' , \time () - 3600 , '/' , COOKIE_DOMAIN , ( 'https' == $protocol ), true , COOKIE_SAMESITE )
2020-01-12 02:58:02 +13:00
-> noContent ()
;
2019-05-09 18:54:39 +12:00
}
2019-09-07 05:10:41 +12:00
);
2020-01-06 00:29:42 +13:00
2020-02-16 07:34:16 +13:00
$utopia -> delete ( '/v1/account/sessions/:sessionId' )
2020-01-06 00:29:42 +13:00
-> desc ( 'Delete Account Session' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2020-01-06 00:29:42 +13:00
-> label ( 'scope' , 'account' )
-> label ( 'webhook' , 'account.sessions.delete' )
2020-01-27 19:14:14 +13:00
-> label ( 'sdk.platform' , [ APP_PLATFORM_CLIENT ])
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-01-06 00:29:42 +13:00
-> label ( 'abuse-limit' , 100 )
2020-02-16 07:34:16 +13:00
-> param ( 'sessionId' , null , function () { return new UID (); }, 'Session unique ID. Use the string \'current\' to delete the current device session.' )
2020-01-06 00:29:42 +13:00
-> action (
2020-03-29 01:42:16 +13:00
function ( $sessionId ) use ( $response , $user , $projectDB , $webhook , $audit ) {
$protocol = Config :: getParam ( 'protocol' );
2020-02-16 07:34:16 +13:00
$sessionId = ( $sessionId === 'current' )
2020-02-12 11:24:30 +13:00
? Auth :: tokenVerify ( $user -> getAttribute ( 'tokens' ), Auth :: TOKEN_TYPE_LOGIN , Auth :: $secret )
2020-02-16 07:34:16 +13:00
: $sessionId ;
2020-02-12 11:24:30 +13:00
2020-01-06 00:29:42 +13:00
$tokens = $user -> getAttribute ( 'tokens' , []);
foreach ( $tokens as $token ) { /* @var $token Document */
2020-02-17 20:16:11 +13:00
if (( $sessionId == $token -> getId ()) && Auth :: TOKEN_TYPE_LOGIN == $token -> getAttribute ( 'type' )) {
if ( ! $projectDB -> deleteDocument ( $token -> getId ())) {
2020-01-06 00:29:42 +13:00
throw new Exception ( 'Failed to remove token from DB' , 500 );
}
$audit
2020-02-17 20:16:11 +13:00
-> setParam ( 'userId' , $user -> getId ())
2020-01-06 00:29:42 +13:00
-> setParam ( 'event' , 'account.sessions.delete' )
2020-02-17 20:16:11 +13:00
-> setParam ( 'resource' , '/user/' . $user -> getId ())
2020-01-06 00:29:42 +13:00
;
$webhook
-> setParam ( 'payload' , [
'name' => $user -> getAttribute ( 'name' , '' ),
'email' => $user -> getAttribute ( 'email' , '' ),
])
;
2020-06-25 08:59:04 +12:00
if ( ! Config :: getParam ( 'domainVerification' )) {
2020-03-18 00:36:13 +13:00
$response
2020-06-20 23:20:49 +12:00
-> addHeader ( 'X-Fallback-Cookies' , \json_encode ([]))
2020-03-18 00:36:13 +13:00
;
}
2020-01-06 00:29:42 +13:00
if ( $token -> getAttribute ( 'secret' ) == Auth :: hash ( Auth :: $secret )) { // If current session delete the cookies too
2020-01-15 09:50:49 +13:00
$response
2020-06-20 23:20:49 +12:00
-> addCookie ( Auth :: $cookieName . '_legacy' , '' , \time () - 3600 , '/' , COOKIE_DOMAIN , ( 'https' == $protocol ), true , null )
-> addCookie ( Auth :: $cookieName , '' , \time () - 3600 , '/' , COOKIE_DOMAIN , ( 'https' == $protocol ), true , COOKIE_SAMESITE )
2020-01-15 09:50:49 +13:00
;
2020-01-06 00:29:42 +13:00
}
2020-02-12 11:24:30 +13:00
return $response -> noContent ();
}
2020-01-12 02:58:02 +13:00
}
2020-01-06 00:29:42 +13:00
2020-02-12 11:24:30 +13:00
throw new Exception ( 'Session not found' , 404 );
2020-01-06 12:07:41 +13:00
}
);
2020-01-27 19:14:14 +13:00
$utopia -> delete ( '/v1/account/sessions' )
2020-01-24 11:33:44 +13:00
-> desc ( 'Delete All Account Sessions' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2020-01-24 11:33:44 +13:00
-> label ( 'scope' , 'account' )
-> label ( 'webhook' , 'account.sessions.delete' )
2020-01-27 19:14:14 +13:00
-> label ( 'sdk.platform' , [ APP_PLATFORM_CLIENT ])
2020-01-24 11:33:44 +13:00
-> label ( 'sdk.namespace' , 'account' )
2020-01-31 05:18:46 +13:00
-> label ( 'sdk.method' , 'deleteSessions' )
2020-01-24 11:33:44 +13:00
-> label ( 'sdk.description' , '/docs/references/account/delete-sessions.md' )
-> label ( 'abuse-limit' , 100 )
-> action (
2020-03-29 01:42:16 +13:00
function () use ( $response , $user , $projectDB , $audit , $webhook ) {
$protocol = Config :: getParam ( 'protocol' );
2020-01-24 11:33:44 +13:00
$tokens = $user -> getAttribute ( 'tokens' , []);
foreach ( $tokens as $token ) { /* @var $token Document */
2020-02-17 20:16:11 +13:00
if ( ! $projectDB -> deleteDocument ( $token -> getId ())) {
2020-01-24 11:33:44 +13:00
throw new Exception ( 'Failed to remove token from DB' , 500 );
}
$audit
2020-02-17 20:16:11 +13:00
-> setParam ( 'userId' , $user -> getId ())
2020-01-24 11:33:44 +13:00
-> setParam ( 'event' , 'account.sessions.delete' )
2020-02-17 20:16:11 +13:00
-> setParam ( 'resource' , '/user/' . $user -> getId ())
2020-01-24 11:33:44 +13:00
;
$webhook
-> setParam ( 'payload' , [
'name' => $user -> getAttribute ( 'name' , '' ),
'email' => $user -> getAttribute ( 'email' , '' ),
])
;
2020-06-25 08:59:04 +12:00
if ( ! Config :: getParam ( 'domainVerification' )) {
2020-03-18 00:36:13 +13:00
$response
2020-06-20 23:20:49 +12:00
-> addHeader ( 'X-Fallback-Cookies' , \json_encode ([]))
2020-03-18 00:36:13 +13:00
;
}
2020-01-24 11:33:44 +13:00
if ( $token -> getAttribute ( 'secret' ) == Auth :: hash ( Auth :: $secret )) { // If current session delete the cookies too
$response
2020-06-20 23:20:49 +12:00
-> addCookie ( Auth :: $cookieName . '_legacy' , '' , \time () - 3600 , '/' , COOKIE_DOMAIN , ( 'https' == $protocol ), true , null )
-> addCookie ( Auth :: $cookieName , '' , \time () - 3600 , '/' , COOKIE_DOMAIN , ( 'https' == $protocol ), true , COOKIE_SAMESITE )
2020-01-24 11:33:44 +13:00
;
}
}
$response -> noContent ();
}
);
2020-01-06 12:07:41 +13:00
$utopia -> post ( '/v1/account/recovery' )
2020-02-09 07:51:49 +13:00
-> desc ( 'Create Password Recovery' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2020-01-06 12:07:41 +13:00
-> label ( 'scope' , 'public' )
2020-01-27 19:14:14 +13:00
-> label ( 'sdk.platform' , [ APP_PLATFORM_CLIENT ])
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' )
-> label ( 'abuse-limit' , 10 )
-> label ( 'abuse-key' , 'url:{url},email:{param-email}' )
2020-02-10 18:58:29 +13:00
-> param ( 'email' , '' , function () { return new Email (); }, 'User email.' )
2020-05-28 23:34:42 +12:00
-> param ( 'url' , '' , function () use ( $clients ) { return 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.' )
2020-01-06 12:07:41 +13:00
-> action (
2020-06-14 06:30:44 +12:00
function ( $email , $url ) use ( $request , $response , $projectDB , $mail , $audit , $project ) {
2020-06-27 02:41:13 +12:00
$profile = $projectDB -> getCollectionFirst ([ // Get user by email address
2020-01-06 12:07:41 +13:00
'limit' => 1 ,
'filters' => [
'$collection=' . Database :: SYSTEM_COLLECTION_USERS ,
'email=' . $email ,
],
]);
if ( empty ( $profile )) {
throw new Exception ( 'User not found' , 404 ); // TODO maybe hide this
}
$secret = Auth :: tokenGenerator ();
2020-01-12 02:58:02 +13:00
$recovery = new Document ([
2020-01-06 12:07:41 +13:00
'$collection' => Database :: SYSTEM_COLLECTION_TOKENS ,
2020-02-17 20:16:11 +13:00
'$permissions' => [ 'read' => [ 'user:' . $profile -> getId ()], 'write' => [ 'user:' . $profile -> getId ()]],
2020-01-06 12:07:41 +13:00
'type' => Auth :: TOKEN_TYPE_RECOVERY ,
'secret' => Auth :: hash ( $secret ), // On way hash encryption to protect DB leak
2020-06-20 23:20:49 +12:00
'expire' => \time () + Auth :: TOKEN_EXPIRATION_RECOVERY ,
2020-01-06 12:07:41 +13:00
'userAgent' => $request -> getServer ( 'HTTP_USER_AGENT' , 'UNKNOWN' ),
'ip' => $request -> getIP (),
2020-01-12 02:58:02 +13:00
]);
2020-02-17 20:16:11 +13:00
Authorization :: setRole ( 'user:' . $profile -> getId ());
2020-01-06 12:07:41 +13:00
2020-01-12 02:58:02 +13:00
$recovery = $projectDB -> createDocument ( $recovery -> getArrayCopy ());
if ( false === $recovery ) {
throw new Exception ( 'Failed saving recovery to DB' , 500 );
}
$profile -> setAttribute ( 'tokens' , $recovery , Document :: SET_TYPE_APPEND );
2020-01-06 12:07:41 +13:00
$profile = $projectDB -> updateDocument ( $profile -> getArrayCopy ());
if ( false === $profile ) {
throw new Exception ( 'Failed to save user to DB' , 500 );
}
2020-01-12 13:20:35 +13:00
$url = Template :: parseURL ( $url );
2020-02-17 20:16:11 +13:00
$url [ 'query' ] = Template :: mergeQuery ((( isset ( $url [ 'query' ])) ? $url [ 'query' ] : '' ), [ 'userId' => $profile -> getId (), 'secret' => $secret ]);
2020-01-12 13:20:35 +13:00
$url = Template :: unParseURL ( $url );
2020-01-06 12:07:41 +13:00
2020-06-12 11:20:32 +12:00
$body = new Template ( __DIR__ . '/../../config/locales/templates/_base.tpl' );
$content = new Template ( __DIR__ . '/../../config/locales/templates/' . Locale :: getText ( 'account.emails.recovery.body' ));
$cta = new Template ( __DIR__ . '/../../config/locales/templates/_cta.tpl' );
2020-01-06 12:07:41 +13:00
$body
2020-06-12 11:20:32 +12:00
-> setParam ( '{{content}}' , $content -> render ())
-> setParam ( '{{cta}}' , $cta -> render ())
-> setParam ( '{{title}}' , Locale :: getText ( 'account.emails.recovery.title' ))
2020-01-06 12:07:41 +13:00
-> setParam ( '{{direction}}' , Locale :: getText ( 'settings.direction' ))
-> setParam ( '{{project}}' , $project -> getAttribute ( 'name' , [ '[APP-NAME]' ]))
-> setParam ( '{{name}}' , $profile -> getAttribute ( 'name' ))
2020-01-12 13:20:35 +13:00
-> setParam ( '{{redirect}}' , $url )
2020-06-13 06:21:58 +12:00
-> setParam ( '{{bg-body}}' , '#f6f6f6' )
-> setParam ( '{{bg-content}}' , '#ffffff' )
-> setParam ( '{{bg-cta}}' , '#3498db' )
-> setParam ( '{{bg-cta-hover}}' , '#34495e' )
-> setParam ( '{{text-content}}' , '#000000' )
-> setParam ( '{{text-cta}}' , '#ffffff' )
2020-01-06 12:07:41 +13:00
;
2020-06-14 06:30:44 +12:00
$mail
2020-06-14 11:06:05 +12:00
-> setParam ( 'event' , 'account.recovery.create' )
2020-06-14 06:30:44 +12:00
-> setParam ( 'recipient' , $profile -> getAttribute ( 'email' , '' ))
-> setParam ( 'name' , $profile -> getAttribute ( 'name' , '' ))
-> setParam ( 'subject' , Locale :: getText ( 'account.emails.recovery.title' ))
-> setParam ( 'body' , $body -> render ())
-> trigger ();
;
2020-01-06 12:07:41 +13:00
$audit
2020-02-17 20:16:11 +13:00
-> setParam ( 'userId' , $profile -> getId ())
2020-01-06 12:07:41 +13:00
-> setParam ( 'event' , 'account.recovery.create' )
2020-02-17 20:16:11 +13:00
-> setParam ( 'resource' , 'users/' . $profile -> getId ())
2020-01-06 12:07:41 +13:00
;
2020-01-12 02:58:02 +13:00
$response
-> setStatusCode ( Response :: STATUS_CODE_CREATED )
2020-02-17 20:16:11 +13:00
-> json ( $recovery -> getArrayCopy ([ '$id' , 'type' , 'expire' ]))
2020-01-12 02:58:02 +13:00
;
2020-01-06 12:07:41 +13:00
}
);
$utopia -> put ( '/v1/account/recovery' )
2020-02-09 07:51:49 +13:00
-> desc ( 'Complete Password Recovery' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2020-01-06 12:07:41 +13:00
-> label ( 'scope' , 'public' )
2020-01-27 19:14:14 +13:00
-> label ( 'sdk.platform' , [ APP_PLATFORM_CLIENT ])
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' )
-> label ( 'abuse-limit' , 10 )
-> label ( 'abuse-key' , 'url:{url},userId:{param-userId}' )
2020-01-12 02:58:02 +13:00
-> param ( 'userId' , '' , function () { return new UID (); }, 'User account UID address.' )
2020-01-20 01:22:45 +13:00
-> param ( 'secret' , '' , function () { return new Text ( 256 ); }, 'Valid reset token.' )
2020-05-31 10:24:05 +12:00
-> param ( 'password' , '' , function () { return new Password (); }, 'New password. Must be between 6 to 32 chars.' )
-> param ( 'passwordAgain' , '' , function () { return new Password (); }, 'New password again. Must be between 6 to 32 chars.' )
2020-01-06 12:07:41 +13:00
-> action (
2020-03-26 09:19:19 +13:00
function ( $userId , $secret , $password , $passwordAgain ) use ( $response , $projectDB , $audit ) {
if ( $password !== $passwordAgain ) {
2020-01-06 12:07:41 +13:00
throw new Exception ( 'Passwords must match' , 400 );
}
2020-06-27 02:41:13 +12:00
$profile = $projectDB -> getCollectionFirst ([ // Get user by email address
2020-01-06 12:07:41 +13:00
'limit' => 1 ,
'filters' => [
'$collection=' . Database :: SYSTEM_COLLECTION_USERS ,
2020-02-17 20:16:11 +13:00
'$id=' . $userId ,
2020-01-06 12:07:41 +13:00
],
]);
if ( empty ( $profile )) {
throw new Exception ( 'User not found' , 404 ); // TODO maybe hide this
}
2020-01-20 01:22:45 +13:00
$recovery = Auth :: tokenVerify ( $profile -> getAttribute ( 'tokens' , []), Auth :: TOKEN_TYPE_RECOVERY , $secret );
2020-01-06 12:07:41 +13:00
2020-01-12 02:58:02 +13:00
if ( ! $recovery ) {
throw new Exception ( 'Invalid recovery token' , 401 );
2020-01-06 12:07:41 +13:00
}
2020-02-17 20:16:11 +13:00
Authorization :: setRole ( 'user:' . $profile -> getId ());
2020-01-06 12:07:41 +13:00
2020-06-20 23:20:49 +12:00
$profile = $projectDB -> updateDocument ( \array_merge ( $profile -> getArrayCopy (), [
2020-03-26 09:19:19 +13:00
'password' => Auth :: passwordHash ( $password ),
2020-06-20 23:20:49 +12:00
'password-update' => \time (),
2020-02-10 10:37:28 +13:00
'emailVerification' => true ,
2020-01-06 12:07:41 +13:00
]));
if ( false === $profile ) {
throw new Exception ( 'Failed saving user to DB' , 500 );
}
2020-01-12 02:58:02 +13:00
/**
* We act like we ' re updating and validating
* the recovery token but actually we don ' t need it anymore .
*/
if ( ! $projectDB -> deleteDocument ( $recovery )) {
throw new Exception ( 'Failed to remove recovery from DB' , 500 );
2020-01-06 12:07:41 +13:00
}
$audit
2020-02-17 20:16:11 +13:00
-> setParam ( 'userId' , $profile -> getId ())
2020-01-06 12:07:41 +13:00
-> setParam ( 'event' , 'account.recovery.update' )
2020-02-17 20:16:11 +13:00
-> setParam ( 'resource' , 'users/' . $profile -> getId ())
2020-01-06 12:07:41 +13:00
;
2020-02-17 20:16:11 +13:00
$recovery = $profile -> search ( '$id' , $recovery , $profile -> getAttribute ( 'tokens' , []));
2020-01-12 02:58:02 +13:00
2020-02-17 20:16:11 +13:00
$response -> json ( $recovery -> getArrayCopy ([ '$id' , 'type' , 'expire' ]));
2020-01-06 00:29:42 +13:00
}
2020-01-12 13:20:35 +13:00
);
2020-02-10 20:34:02 +13:00
$utopia -> post ( '/v1/account/verification' )
2020-02-10 10:37:28 +13:00
-> desc ( 'Create Email Verification' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2020-01-12 13:20:35 +13:00
-> label ( 'scope' , 'account' )
2020-02-08 11:46:12 +13:00
-> label ( 'sdk.platform' , [ APP_PLATFORM_CLIENT ])
2020-01-12 13:20:35 +13:00
-> label ( 'sdk.namespace' , 'account' )
2020-01-31 05:18:46 +13:00
-> label ( 'sdk.method' , 'createVerification' )
2020-01-12 13:20:35 +13:00
-> label ( 'sdk.description' , '/docs/references/account/create-verification.md' )
-> label ( 'abuse-limit' , 10 )
-> label ( 'abuse-key' , 'url:{url},email:{param-email}' )
2020-05-28 23:34:42 +12:00
-> param ( 'url' , '' , function () use ( $clients ) { return 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.' ) // TODO add built-in confirm page
2020-01-12 13:20:35 +13:00
-> action (
2020-06-14 06:30:44 +12:00
function ( $url ) use ( $request , $response , $mail , $user , $project , $projectDB , $audit ) {
2020-01-12 13:20:35 +13:00
$verificationSecret = Auth :: tokenGenerator ();
$verification = new Document ([
'$collection' => Database :: SYSTEM_COLLECTION_TOKENS ,
2020-02-17 20:16:11 +13:00
'$permissions' => [ 'read' => [ 'user:' . $user -> getId ()], 'write' => [ 'user:' . $user -> getId ()]],
2020-01-12 13:20:35 +13:00
'type' => Auth :: TOKEN_TYPE_VERIFICATION ,
'secret' => Auth :: hash ( $verificationSecret ), // On way hash encryption to protect DB leak
2020-06-20 23:20:49 +12:00
'expire' => \time () + Auth :: TOKEN_EXPIRATION_CONFIRM ,
2020-01-12 13:20:35 +13:00
'userAgent' => $request -> getServer ( 'HTTP_USER_AGENT' , 'UNKNOWN' ),
'ip' => $request -> getIP (),
]);
2020-02-17 20:16:11 +13:00
Authorization :: setRole ( 'user:' . $user -> getId ());
2020-01-12 13:20:35 +13:00
$verification = $projectDB -> createDocument ( $verification -> getArrayCopy ());
if ( false === $verification ) {
throw new Exception ( 'Failed saving verification to DB' , 500 );
}
$user -> setAttribute ( 'tokens' , $verification , Document :: SET_TYPE_APPEND );
$user = $projectDB -> updateDocument ( $user -> getArrayCopy ());
if ( false === $user ) {
throw new Exception ( 'Failed to save user to DB' , 500 );
}
$url = Template :: parseURL ( $url );
2020-02-17 20:16:11 +13:00
$url [ 'query' ] = Template :: mergeQuery ((( isset ( $url [ 'query' ])) ? $url [ 'query' ] : '' ), [ 'userId' => $user -> getId (), 'secret' => $verificationSecret ]);
2020-01-12 13:20:35 +13:00
$url = Template :: unParseURL ( $url );
2020-06-12 11:20:32 +12:00
$body = new Template ( __DIR__ . '/../../config/locales/templates/_base.tpl' );
$content = new Template ( __DIR__ . '/../../config/locales/templates/' . Locale :: getText ( 'account.emails.verification.body' ));
$cta = new Template ( __DIR__ . '/../../config/locales/templates/_cta.tpl' );
2020-01-12 13:20:35 +13:00
$body
2020-06-12 11:20:32 +12:00
-> setParam ( '{{content}}' , $content -> render ())
-> setParam ( '{{cta}}' , $cta -> render ())
-> setParam ( '{{title}}' , Locale :: getText ( 'account.emails.verification.title' ))
2020-01-12 13:20:35 +13:00
-> setParam ( '{{direction}}' , Locale :: getText ( 'settings.direction' ))
-> setParam ( '{{project}}' , $project -> getAttribute ( 'name' , [ '[APP-NAME]' ]))
-> setParam ( '{{name}}' , $user -> getAttribute ( 'name' ))
-> setParam ( '{{redirect}}' , $url )
2020-06-13 06:21:58 +12:00
-> setParam ( '{{bg-body}}' , '#f6f6f6' )
-> setParam ( '{{bg-content}}' , '#ffffff' )
-> setParam ( '{{bg-cta}}' , '#3498db' )
-> setParam ( '{{bg-cta-hover}}' , '#34495e' )
-> setParam ( '{{text-content}}' , '#000000' )
-> setParam ( '{{text-cta}}' , '#ffffff' )
2020-01-12 13:20:35 +13:00
;
2020-06-14 06:30:44 +12:00
$mail
2020-06-14 11:06:05 +12:00
-> setParam ( 'event' , 'account.verification.create' )
2020-06-14 06:30:44 +12:00
-> setParam ( 'recipient' , $user -> getAttribute ( 'email' ))
-> setParam ( 'name' , $user -> getAttribute ( 'name' ))
-> setParam ( 'subject' , Locale :: getText ( 'account.emails.verification.title' ))
-> setParam ( 'body' , $body -> render ())
-> trigger ()
;
2020-01-12 13:20:35 +13:00
$audit
2020-02-17 20:16:11 +13:00
-> setParam ( 'userId' , $user -> getId ())
2020-01-12 13:20:35 +13:00
-> setParam ( 'event' , 'account.verification.create' )
2020-02-17 20:16:11 +13:00
-> setParam ( 'resource' , 'users/' . $user -> getId ())
2020-01-12 13:20:35 +13:00
;
$response
-> setStatusCode ( Response :: STATUS_CODE_CREATED )
2020-02-17 20:16:11 +13:00
-> json ( $verification -> getArrayCopy ([ '$id' , 'type' , 'expire' ]))
2020-01-12 13:20:35 +13:00
;
}
);
$utopia -> put ( '/v1/account/verification' )
2020-02-10 10:37:28 +13:00
-> desc ( 'Complete Email Verification' )
2020-06-26 06:32:12 +12:00
-> groups ([ 'api' , 'account' ])
2020-01-12 13:20:35 +13:00
-> label ( 'scope' , 'public' )
2020-01-27 19:14:14 +13:00
-> label ( 'sdk.platform' , [ APP_PLATFORM_CLIENT ])
2020-01-12 13:20:35 +13:00
-> label ( 'sdk.namespace' , 'account' )
2020-01-31 05:18:46 +13:00
-> label ( 'sdk.method' , 'updateVerification' )
2020-01-12 13:20:35 +13:00
-> label ( 'sdk.description' , '/docs/references/account/update-verification.md' )
-> label ( 'abuse-limit' , 10 )
-> label ( 'abuse-key' , 'url:{url},userId:{param-userId}' )
2020-02-10 18:54:26 +13:00
-> param ( 'userId' , '' , function () { return new UID (); }, 'User unique ID.' )
2020-02-10 20:34:02 +13:00
-> param ( 'secret' , '' , function () { return new Text ( 256 ); }, 'Valid verification token.' )
2020-01-12 13:20:35 +13:00
-> action (
2020-01-20 01:22:45 +13:00
function ( $userId , $secret ) use ( $response , $user , $projectDB , $audit ) {
2020-06-27 02:41:13 +12:00
$profile = $projectDB -> getCollectionFirst ([ // Get user by email address
2020-01-12 13:20:35 +13:00
'limit' => 1 ,
'filters' => [
'$collection=' . Database :: SYSTEM_COLLECTION_USERS ,
2020-02-17 20:16:11 +13:00
'$id=' . $userId ,
2020-01-12 13:20:35 +13:00
],
]);
if ( empty ( $profile )) {
throw new Exception ( 'User not found' , 404 ); // TODO maybe hide this
}
2020-01-20 01:22:45 +13:00
$verification = Auth :: tokenVerify ( $profile -> getAttribute ( 'tokens' , []), Auth :: TOKEN_TYPE_VERIFICATION , $secret );
2020-01-12 13:20:35 +13:00
if ( ! $verification ) {
throw new Exception ( 'Invalid verification token' , 401 );
}
2020-02-17 20:16:11 +13:00
Authorization :: setRole ( 'user:' . $profile -> getId ());
2020-01-12 13:20:35 +13:00
2020-06-20 23:20:49 +12:00
$profile = $projectDB -> updateDocument ( \array_merge ( $profile -> getArrayCopy (), [
2020-02-10 10:37:28 +13:00
'emailVerification' => true ,
2020-01-12 13:20:35 +13:00
]));
if ( false === $profile ) {
throw new Exception ( 'Failed saving user to DB' , 500 );
}
/**
* We act like we ' re updating and validating
* the verification token but actually we don ' t need it anymore .
*/
if ( ! $projectDB -> deleteDocument ( $verification )) {
throw new Exception ( 'Failed to remove verification from DB' , 500 );
}
$audit
2020-02-17 20:16:11 +13:00
-> setParam ( 'userId' , $profile -> getId ())
2020-01-12 13:20:35 +13:00
-> setParam ( 'event' , 'account.verification.update' )
2020-02-17 20:16:11 +13:00
-> setParam ( 'resource' , 'users/' . $user -> getId ())
2020-01-12 13:20:35 +13:00
;
2020-02-17 20:16:11 +13:00
$verification = $profile -> search ( '$id' , $verification , $profile -> getAttribute ( 'tokens' , []));
2020-01-12 13:20:35 +13:00
2020-02-17 20:16:11 +13:00
$response -> json ( $verification -> getArrayCopy ([ '$id' , 'type' , 'expire' ]));
2020-01-12 13:20:35 +13:00
}
2020-01-06 00:29:42 +13:00
);