Created
October 5, 2014 03:31
-
-
Save bobbysciacchitano/7008bbd15fc2aac7e7da to your computer and use it in GitHub Desktop.
Useful Laravel REST API Snippets
This file contains 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
/* | |
|-------------------------------------------------------------------------- | |
| REST API default headers | |
|-------------------------------------------------------------------------- | |
| | |
| Adds extra headers for handling API requests. | |
| | |
*/ | |
App::after(function($request, $response) | |
{ | |
$response->headers->set('Access-Control-Allow-Headers', 'Authorization'); | |
$response->headers->set('Access-Control-Allow-Origin', '*'); | |
$response->headers->set('Access-Control-Max-Age', '432000'); | |
$response->headers->set('Access-Control-Allow-Headers', 'Content-Type', 'Authorization', 'Accept'); | |
$response->headers->set('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE'); | |
}); | |
/* | |
|-------------------------------------------------------------------------- | |
| Token Validation | |
|-------------------------------------------------------------------------- | |
| | |
| The token validation will ensure that the request header includes a | |
| valid token for access to the requested resource. | |
| | |
| Will attempt to login the user to the application. | |
*/ | |
Route::filter('check.token', function() | |
{ | |
$token = UserToken::with(['user' => function($query){ $query->isActive(); }]) | |
->where('hash', Request::header('Authorization')) | |
->first(); | |
if(!$token || !$token->isValid()) | |
{ | |
return Response::make(null, 401); | |
} | |
if(!Auth::onceUsingId($token->user_id)) | |
{ | |
return Response::make(null, 401); | |
} | |
}); | |
/* | |
|-------------------------------------------------------------------------- | |
| Disable Sessions | |
|-------------------------------------------------------------------------- | |
| | |
| Turn of session handling for API calls. They're not needed since | |
| authentication is managed via a token. | |
*/ | |
Route::filter('disable.sessions', function() | |
{ | |
return Config::set('session.driver', 'array'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment