/** * Checks whether the policy and sig * @param ApiUser $user * @return bool * @throws EApiError */ public function isSignatureMatched($user) { $requestArray = Yii::app()->getController()->getJsonInputAsArray(); if (empty($requestArray)) { throw new EApiError(HHttp::ERROR_BADREQUEST, HHttp::getErrorMessage(HHttp::ERROR_BADREQUEST)); } $signature = ArrayX::pop($requestArray, 'signature'); $expires = ArrayX::pop($requestArray, 'expiration'); if (!$signature || !$expires) { throw new EApiError(HHttp::ERROR_BADREQUEST, HHttp::getErrorMessage(HHttp::ERROR_BADREQUEST)); } // check time if (strtotime($expires) < time()) { throw new EApiError(HHttp::ERROR_INTERNAL_504, HHttp::getErrorMessage(HHttp::ERROR_INTERNAL_504)); } // set back the expiration time to recreate the policy and make a handshake $requestArray['ttd'] = $expires; $requestData = new RequestData($requestArray); $requestData->prepareData($user->api_secret); // use secret to create signature return strcmp($requestData->getSignature(), $signature) === 0; }
/** * Returns the * @return mixed * @throws EApiError */ protected function getUser() { if (null === $this->_user) { $apiKeyName = 'HTTP_' . Yii::app()->params['api.key.name']; if (!isset($_SERVER[$apiKeyName]) || !($apiKey = trim($_SERVER[$apiKeyName])) || !($this->_user = ApiUser::model()->findByAttributes(array('api_key' => $apiKey)))) { throw new EApiError(HHttp::ERROR_UNAUTHORIZED, HHttp::getErrorMessage(HHttp::ERROR_UNAUTHORIZED)); } } Yii::app()->user->setId($this->_user->id); Yii::app()->user->setName($this->_user->{$this->attributeName}); return $this->_user; }
/** * Error handler, when there is an error this will fire * @param CEvent $event */ public function apiErrorHandler(CEvent $event) { $event->handled = true; $debug = Yii::app()->params['yii.debug']; $response = array(); if ($event instanceof CExceptionEvent) { if ($event->exception instanceof EApiError) { $response['code'] = $event->exception->statusCode; $response['message'] = $event->exception->getMessage(); } else { $response['code'] = isset($event->exception->statusCode) ? $event->exception->statusCode : $event->exception->getCode(); $response['message'] = $event->exception->getMessage(); if ($debug) { $response['traceback'] = $event->exception->getTrace(); } } } else { if ($event instanceof CErrorEvent) { $response['code'] = 500; $response['message'] = $event->message; if ($debug) { $response['traceback'] = debug_backtrace(); } } } if (!$response['code']) { $response['code'] = 500; } try { HHttp::sendHttpResponseCode($response['code']); } catch (exception $e) { $response['code'] = 500; HHttp::sendHttpResponseCode($response['code']); } $this->renderJson($response); Yii::app()->end(); }