public
Created

API Wrapper for CloudMine that can be used as a Zend_Auth Adapter

  • Download Gist
CloudMine.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
<?php
class CloudMine implements Zend_Auth_Adapter_Interface
{
const API_BASE = 'https://api.cloudmine.me/v1/app/';
const FORMAT_JSON = 'json';
const FORMAT_BINARY = 'binary';
const FORMAT_EMPTY = null;
/**
* HTTP Client
* @var Zend_Http_Client
*/
protected $httpClient;
/**
* CloudMine Application ID
* @var string
*/
protected $appid;
 
/**
* CloudMine Application Key
* @var string
*/
protected $key;
 
/**
* User/App Namespace Flag
* @var bool
*/
protected $user = false;
/**
* Username for Auth
* @var string
*/
protected $username;
/**
* Password for Auth
* @var string
*/
protected $password;
public function __construct($appid, $key)
{
$this->appid = $appid;
$this->key = $key;
}
/**
* Requests will be to user namespace.
* @return CloudMine
*/
public function user()
{
$this->user = true;
return $this;
}
/**
* Requests will be to app namespace.
* @return CloudMine
*/
public function app()
{
$this->user = false;
return $this;
}
/**
* Get Data that matches optional key(s).
*
* @param array|string $keys
*/
public function get($keys = array(), $function = null)
{
if(!empty($keys)){
if(!is_array($keys)){
$keys = array($keys);
}
$this->getHttpClient()->setParameterGet('keys', implode(',', $keys));
}
if($function){
$this->getHttpClient()->setParameterGet('f', $function);
}
$response = $this->getHttpClient()
->setUri($this->getApi('text'))
->request(Zend_Http_Client::GET);
return $this->checkResponse($response);
}
/**
* Get Data that matches cloudmins query.
*
* @param string $query
*/
public function query($query)
{
$response = $this->getHttpClient()
->setParameterGet('q', $query)
->setUri($this->getApi('search'))
->request(Zend_Http_Client::GET);
return $this->checkResponse($response);
}
 
/**
* Set Data for a single key, or multiple keys.
*
* This overwrites any exsisting data.
*
* If only one argument is passed, it's assumed to be an array structure
* of keys => data. If both paramters are passed, the first is considered
* the key, the second the data.
*
* @param array|string $key
* @param array $data
*/
public function set($key, $data = null, $function = null)
{
if($function){
$this->getHttpClient()->setParameterGet('f', $function);
}
$response = $this->getHttpClient()
->setHeaders('Content-Type', 'application/json')
->setRawData($this->formatData($key, $data))
->setUri($this->getApi('text'))
->request(Zend_Http_Client::PUT);
return $this->checkResponse($response);
}
/**
* Update Data for a single key, or multiple keys.
*
* This merges with any exsisting data.
*
* If only one argument is passed, it's assumed to be an array structure
* of keys => data. If both paramters are passed, the first is considered
* the key, the second the data.
*
* @param array|string $key
* @param array $data
*/
public function update($key, $data = null, $function = null)
{
if($function){
$this->getHttpClient()->setParameterGet('f', $function);
}
$response = $this->getHttpClient()
->setHeaders('Content-Type', 'application/json')
->setRawData($this->formatData($key, $data))
->setUri($this->getApi('text'))
->request(Zend_Http_Client::POST);
return $this->checkResponse($response);
}
/**
* Delete Data matching optional key(s).
*
* WARNING: CALLING THIS WITHOUT AN ARGUMENT WILL DELETE ALL THE DATA IN
* THE APPLICATION
*
* @param array|string $keys
*/
public function delete($keys = array())
{
if(!empty($keys)){
if(!is_array($keys)){
$keys = array($keys);
}
$this->getHttpClient()->setParameterGet('keys', implode(',', $keys));
}
 
$response = $this->getHttpClient()
->setUri($this->getApi('data'))
->request(Zend_Http_Client::DELETE);
return $this->checkResponse($response, self::FORMAT_EMPTY);
}
/**
* Get Binary data for a key.
*
* @param string $key
*/
public function getBinary($key)
{
$response = $this->getHttpClient()
->setUri($this->getApi('binary/' . $key))
->request(Zend_Http_Client::GET);
 
return $this->checkResponse($response, self::FORMAT_BINARY);
}
/**
* Set Binary data for a key.
* @param string $key
* @param string $data
* @param unknown_type $type
*/
public function setBinary($key, $data, $type = 'application/octet-stream')
{
$response = $this->getHttpClient()
->setUri($this->getApi('binary/' . $key))
->setRawData($data)
->request(Zend_Http_Client::PUT);
return $this->checkResponse($response, self::FORMAT_EMPTY);
}
 
/**
* Format Data for Set/Update
*
* Takes a key and optional data, returns expected JSON.
*
* @param array|string $key
* @param array $data
* @throws Exception
*/
protected function formatData($key, $data = null)
{
if(isset($data)){
$data = array($key => $data);
} else {
if(!is_array($key)){
throw new Exception('First argument must be array if second argument is missing.');
}
$data = $key;
}
return Zend_Json::encode($data);
}
/**
* Check API Response
* @param Zend_Http_Response $response
* @param string $format the kind of body expected
* @throws Exception
*/
protected function checkResponse(Zend_Http_Response $response, $format = self::FORMAT_JSON)
{
switch($response->getStatus()){
case 201:
case 200:
break;
case 400:
throw new Exception('Invalid Query');
case 401:
throw new Exception('Invalid API Credentials');
case 404:
throw new Exception('Invalid Application ID');
default:
throw new Exception('Unsupported API Response: ' . $response->getStatus());
}
 
switch($format){
case self::FORMAT_JSON:
$data = Zend_Json::decode($response->getBody());
//cloudmine returns and array of successes and failures
$keys = array();
foreach($data['success'] as $key => $value){
$keys[$key] = $value;
}
foreach($data['errors'] as $key => $value){
switch($value['code']){
case 404:
$keys[$key] = null;
break;
case 415:
//TODO: link to binary file
$keys[$key] = null;
break;
default:
$keys[$key] = null;
break;
}
}
if(isset($data['result'])){
$keys['result'] = $data['result'];
}
return $keys;
case self::FORMAT_BINARY:
//TODO: do something intelegent with the content type
return $response->getBody();
default:
return true;
}
}
/**
* Authenticate a User
*
* Cloudmine will try to create users that don't exsist. We don't do that,
* so the auth endpoind may be requested twice (once to see if the user
* exists, once to auth).
*
* @see Zend_Auth_Adapter_Interface::authenticate()
* @return Zend_Auth_Result
*/
public function authenticate($username = false, $pasword = false)
{
//populate username and password if needed
if(!$username){
$username = $this->username;
}
if(!$pasword){
$password = $this->password;
}
//first try without a password, so a new account isn't setup if the
//email address is incorrect
$response = $this->getHttpClient()
->setAuth($username, '', Zend_Http_Client::AUTH_BASIC)
->setUri($this->getApi('user/account'))
->request(Zend_Http_Client::POST);
//a 401 Unauthorized means the username is valid, for anything else
//assume the username does not exsist
if($response->getStatus() !== 401){
return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND, $username);
}
//check again with the password, to validate the credentials
//TODO: hey look, this code is almost the same as a few lines ago
$response = $this->getHttpClient()
->setAuth($username, $password, Zend_Http_Client::AUTH_BASIC)
->setUri($this->getApi('user/account'))
->request(Zend_Http_Client::POST);
//200 means we're all good
if($response->getStatus() !== 200){
return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID, $username);
}
return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $username);
}
/**
* Create a User
*
* @param string $username
* @param string $password
* @throws Exception
* @return CloudMine
*/
public function createUser($username, $password)
{
//make sure the account doesn't already exsist
$result = $this->authenticate($username, $password);
if($result->getCode() != Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND){
throw new Exception('Username already exists: ' . $username);
}
//do an auth request
//TODO: yup, same code again - who wrote this stuff?
$response = $this->getHttpClient()
->setAuth($username, $password, Zend_Http_Client::AUTH_BASIC)
->setUri($this->getApi('user/account'))
->request(Zend_Http_Client::POST);
//expect a 201 Created response
if($response->getStatus() != 201){
throw new Exception('Unexpected status from API: ' . $response->getStatus());
}
return $this;
}
/**
* Set the username when using Zend_Auth or making user namespace requests.
*
* @param string $username
* @return CloudMine
*/
public function setUsername($username) {
$this->username = $username;
return $this;
}
 
/**
* Set the password when using Zend_Auth or making user namespace requests.
*
* @param string $password
* @return CloudMine
*/
public function setPassword($password) {
$this->password = $password;
return $this;
}
 
/**
* Get a URI based on the given path and the API URI format.
*
* @param string $path
* @return string
*/
public function getApi($path)
{
$parts = array(self::API_BASE, $this->appid);
if($this->user){
$parts[] = 'user';
}
$parts[] = $path;
return implode('/', $parts);
}
/**
* Get the HTTP Client
*
* @return Zend_Http_Client $httpClient
*/
public function getHttpClient() {
if(empty($this->httpClient)){
$this->httpClient = new Zend_Http_Client();
}
 
//set user/pass if user namespace request
if($this->user){
$this->httpClient->setAuth($this->username, $this->password, Zend_Http_Client::AUTH_BASIC);
} else {
$this->httpClient->setAuth(false);
}
//set auth header
return $this->httpClient->setHeaders('X-CloudMine-ApiKey', $this->key);
}
 
/**
* Set the HTTP Client
*
* @param field_type $httpClient
*/
public function setHttpClient($httpClient) {
$this->httpClient = $httpClient;
}
}
auth.php
PHP
1 2 3 4 5 6
<?php
//example using as an auth adapter
$cloudmine->setUsername('username@example.com');
$cloudmine->setPassword('password');
$result = Zend_Auth::getInstance()->authenticate($cloudmine);
echo $result->getIdentity(); //username@example.com

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.