Created
March 20, 2015 00:10
-
-
Save kressaty/e5e2a4df80d818ee16d9 to your computer and use it in GitHub Desktop.
Simple basic auth example for Laravel
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
<?php | |
// this is a route filter that goes in your filters.php file | |
// you'll call this on a route by doing something like Route::get('/api/whatever', ['before' => 'auth.api'], function() {whatever}); | |
Route::filter('auth.api', function() | |
{ | |
// get the basic auth username | |
$key = Request::getUser(); | |
// get the basic auth password | |
$secret = Request::getPassword(); | |
// on your model the credentials are stored on, lookup that user using the key and secret | |
$consumer = Consumer::where('id', '=', $key)->where('api_secret', '=', $secret); | |
// if there isn't exactly one consumer with those credentials | |
if($consumer->count() != 1) | |
{ | |
// return an http header and proper code | |
$headers = array('WWW-Authenticate' => 'Basic'); | |
return Response::make('Invalid credentials.', 401, $headers); | |
} | |
// otherwise, share the model result with all of your views | |
View::share('consumer', $consumer->first()); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment