public function getResponse() { $this->buildHeader(); $responseData = []; $responseData['status'] = ['http_code' => $this->statusCode, 'type' => $this->status, 'message' => $this->message]; // only if an api key is given if ($this->apiKey) { $responseData['status']['rate_limit'] = RateLimiter::get($this->apiKey->public_key); } $dataObject = []; if ($this->data) { $this->buildPagination($this->data); $dataObject = ['data' => $this->data]; } // only if pagination is needed // if($this->pagination) // { // $responseData['status']['pagination'] = $this->pagination; // } // auto-check for error status codes and log to the db if ($this->statusCode > 400 && $this->apiKey) { $log = new ApiLog(); $log->api_key_id = $this->apiKey->id; $log->status = $this->status; $log->message = $this->message; $log->ip_address = Request::ip(); $log->save(); } $responseData = array_merge($responseData, $dataObject); return Response::json($responseData, $this->statusCode, $this->headers); }
|-------------------------------------------------------------------------- | | Public API filter provides header based API key authentication and API rate limiting | */ Route::filter('api.auth', function () { // do we have an auth header $authToken = Request::header('X-Remedy-Auth'); if (!$authToken) { $builder = new ResponseBuilder(); $builder->setStatus(401, 'missing_api_key', 'No api key given.'); return $builder->getResponse(); } // does that auth header contain a valid api key $apiKey = ApiKey::where('public_key', $authToken)->first(); if (!$apiKey) { $builder = new ResponseBuilder(); $builder->setStatus(401, 'invalid_api_key', 'Unauthorized request. This event has been logged. Do it 2 more times, I DARE you!'); return $builder->getResponse(); } }); Route::filter('api.rate', function () { $authToken = Request::header('X-Remedy-Auth'); $apiKey = ApiKey::where('public_key', $authToken)->first(); // check if the api key is over their limit and store / update the cache if (!RateLimiter::check($apiKey)) { $builder = new ResponseBuilder(); $builder->setStatus(429, 'rate_limited', 'Too many requests. You have been rate limited, because the internet. ;)'); return $builder->getResponse(); } });