Last active
August 29, 2015 14:01
-
-
Save arifsetiawan/54b1f59414c3555f6e6f to your computer and use it in GitHub Desktop.
slim-route-middleware
This file contains hidden or 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 | |
error_reporting(E_ALL | E_STRICT); | |
// | |
// Require modules | |
require 'Slim/Slim.php'; | |
\Slim\Slim::registerAutoloader(); | |
require 'Slim/Log.php'; | |
// Get Slim Extras from here https://github.com/codeguy/Slim-Extras | |
require 'Slim/Extras/Log/DateTimeFileWriter.php'; | |
// | |
// Init Slim | |
$app = new \Slim\Slim(array( | |
'debug' => true, | |
'log.writer' => new \Slim\Extras\Log\DateTimeFileWriter(array( | |
'path' => './logs', | |
'name_format' => 'Y-m-d', | |
'message_format' => '%label% - %date% - %message%' | |
)) | |
)); | |
// | |
// Helper | |
function endResponse($code, $status, $message, $data, $app) { | |
$result['status'] = $status; | |
$result['message'] = $message; | |
if (isset($data)) { | |
$result['data'] = $data; | |
} | |
$app->halt($code, json_encode($result)); | |
}; | |
// | |
// Middleware | |
$checkToken = function () use ($app) { | |
return function () use ($app) { | |
$params = $app->request->params(); | |
if (!isset($params['token'])) { | |
endResponse(403, 'Error', 'Invalid credentials. No token are provided.', null, $app); | |
} | |
if ($params['token'] != 'aMxRfN0TjOc9UzUmG3SgtMvv02E7FhoK') { | |
endResponse(403, 'Error', 'Invalid token. Perhaps expired.', null, $app); | |
} | |
}; | |
}; | |
// | |
// Routes | |
// Home | |
$app->get('/',function () use ($app) { | |
$app->log->debug('root'); | |
endResponse(200, 'OK', 'Welcome to API!', null, $app); | |
}); | |
// Auth | |
$app->post('/login', function () use ($app) { | |
$body = $app->request->post(); | |
if (!(isset($body['username']) && isset($body['password']))) { | |
endResponse(403, 'Error', 'Required field is missing.', null, $app); | |
} | |
if ($body['username'] == 'bill' && $body['password'] == 'kill') { | |
$data['token'] = 'aMxRfN0TjOc9UzUmG3SgtMvv02E7FhoK'; | |
endResponse(200, 'OK', 'Login OK', $data, $app); | |
} | |
else { | |
endResponse(403, 'Error', 'Invalid credentials.', null, $app); | |
} | |
}); | |
// Auth-only resources | |
// We add checkToken route middleware here. | |
$app->get('/secret', $checkToken(), function () use ($app) { | |
$data['secret'] = 'This is super secret information available only to you!!'; | |
endResponse(200, 'OK', 'Secret is here!!', $data, $app); | |
}); | |
// | |
// Run | |
$app->run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment