Last active
January 3, 2016 20:19
-
-
Save infacq/8514213 to your computer and use it in GitHub Desktop.
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
/** | |
* Quick and dirty login function with hard coded credentials (admin/admin) | |
* This is just an example. Do not use this in a production environment | |
*/ | |
function login() { | |
if(!empty($_POST['email']) && !empty($_POST['password'])) { | |
// normally you would load credentials from a database. | |
// This is just an example and is certainly not secure | |
if($_POST['email'] == 'admin' && $_POST['password'] == 'admin') { | |
$user = array("email"=>"admin", "firstName"=>"Web", "lastName"=>"Scents", "token"=>base64_encode(openssl_random_pseudo_bytes(16))); | |
$_SESSION['user'] = $user; | |
echo json_encode($user); | |
} | |
else { | |
$error = array("error"=> array("text"=>"You shall not pass...")); | |
echo json_encode($error); | |
} | |
} | |
else { | |
$error = array("error"=> array("text"=>"Username and Password are required.")); | |
echo json_encode($error); | |
} | |
} | |
/** | |
* Authorise function, used as Slim Route Middlewear (http://www.slimframework.com/documentation/stable#routing-middleware) | |
*/ | |
function authorize() { | |
return function () use ( $role ) { | |
// Get the Slim framework object | |
$app = Slim::getInstance(); | |
// First, check to see if the user is logged in at all | |
if(!empty($_SESSION['user'])) { | |
if($_SESSION['user']['token'] == $_SERVER['HTTP_X_CSRF_TOKEN']) { | |
//User is logged in and has the correct permissions... Nice! | |
return true; | |
} else { | |
// If a user is logged in, but doesn't have permissions, return 403 | |
$app->halt(403, 'ACCESS DENIED'); | |
} | |
} else { | |
// If a user is not logged in at all, return a 401 | |
$app->halt(401, 'PLEASE LOGIN FIRST'); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment