Created
April 15, 2016 09:12
-
-
Save nask0/8a6b60094d11cf183f70f35e983b76a2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace CloseContacts\Lib\DataServices; | |
use CloseContacts\Models\ApiAuthTokens; | |
use Lcobucci\JWT\Signer\Hmac\Sha512; | |
use \Lcobucci\JWT\Token as JwtToken; | |
use \CloseContacts\Models\ApiRequests; | |
use \CloseContacts\Lib\Utilities\Str; | |
use \CloseContacts\Lib\Utilities\Date; | |
use \CloseContacts\Lib\Security\Utils as SecUtils; | |
use \CloseContacts\Models\ApiClients as ApiClientModel; | |
use \CloseContacts\Lib\Application\Structs\ApiClient as ApiClientStruct; | |
class ApiClients extends DataServiceAbstract | |
{ | |
/** | |
* @param array $data | |
* @param \CloseContacts\Lib\Application\Structs\ApiClient $requestedWith | |
* @param bool $isActive | |
* @return bool | |
*/ | |
public function register( array $data, ApiClientStruct $requestedWith, $isActive = true ) | |
{ | |
try { | |
$vData = []; | |
$rFields = [ 'user_id', 'username', 'platform' ]; | |
foreach( $rFields as $field ) { | |
if( !array_key_exists( $field, $data ) ) { | |
$this->_setValidationError( $field, Str::ucFirst($field).' is required' ); | |
} else { | |
$vData[$field] = $data[$field]; | |
} | |
} | |
if( true === $this->hasValidationErrors() || count($data) !== count($rFields) ) { | |
return false; | |
} | |
$tx = $this->_getTransaction(); | |
$nameDesc = 'CloseContacts-'.$vData['user_id'].'-'.Str::ucFirst( $vData['platform'] ); | |
$newClient = new ApiClientModel(); | |
$newClient->setTransaction( $tx ); | |
$newClient->setName( $nameDesc ) | |
->setDesc( $nameDesc ) | |
->setType( ApiClientModel::API_CLIENT_TYPE_MOBILE ) // only mobile is supported for now | |
->setUserId( (int) $vData['user_id'] ) | |
->setStatus( (true === $isActive) ? ApiClientModel::API_CLIENT_STATUS_ACTIVE : ApiClientModel::API_CLIENT_STATUS_INACTIVE ) | |
->setApiKey( SecUtils::randApiKey() ) | |
->setPrivateKey( $requestedWith->getPrivKey() ) | |
->setCreated( Date::getUTCTimestamp() ) | |
->setUpdated( Date::getUTCTimestamp() ); | |
if ( false === $newClient->save() ) { | |
$tx->rollback( 'Unable to save API Client' ); | |
} | |
$tx->commit(); | |
return [ | |
'apiKey' => $newClient->getApiKey(), | |
'clientId' => $newClient->getId() | |
]; | |
} catch( \Exception $e ) { | |
$this->_setValidationError( 'unexpected', 'Unable to register user : ' . $e->getMessage() ); | |
return false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment