Skip to content

Instantly share code, notes, and snippets.

@cincodenada
Created November 9, 2012 23:29
Show Gist options
  • Save cincodenada/4049010 to your computer and use it in GitHub Desktop.
Save cincodenada/4049010 to your computer and use it in GitHub Desktop.
Emergent API Authentication Client
<?php
ini_set('display_errors','on');
error_reporting(E_ALL);
//This is less than desirable, but we'll figure out restructuring later
$backend_path = '../../../backend/';
require_once($backend_path . 'lib/logger.php');
require_once($backend_path . 'config.php');
$logger = new Logger();
//Default to unauthorized
header('HTTP/1.1 401 Unauthorized');
$logger->log(print_r(apache_request_headers(), true));
$logger->log(file_get_contents('php://input'));
$conn = Config::$db;
$db = new PDO(
sprintf(
"mysql:host=%s;dbname=%s",
$conn['host'],
$conn['schema']
),
$conn['user'],
$conn['password'],
array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_PERSISTENT => true,
)
);
//if($_SERVER['AUTH_TYPE'] != 'Basic') { challenge(); }
$email = $_SERVER['PHP_AUTH_USER'];
$rawpw = $_SERVER['PHP_AUTH_PW'];
if(empty($email) || empty($rawpw)) { challenge(); }
$hashpw = sha1(Config::$security['salt'] . $rawpw);
$logger->log("Auth: $email/$rawpw ($hashpw)");
$is_hashy = (strlen($rawpw) == 40 && preg_match('/^[0-9a-f]+$/i',$rawpw) == 1);
$user_query = $db->prepare("SELECT * FROM `users` WHERE `email`=:email AND `password`=:password LIMIT 1");
$user_query->execute(array(
'email' => $email,
'password' => $is_hashy ? $rawpw : $hashpw
));
$userdata = $user_query->fetch(PDO::FETCH_ASSOC);
if(empty($userdata) && $is_hashy) {
//Try it with the hashy password as a normal password
$user_query->execute(array(
'email' => $email,
'password' => $hashpw
));
$userdata = $user_query->fetch(PDO::FETCH_ASSOC);
}
if(!empty($userdata)) {
//Return user/org data
$passkeys = array('id','email','role','org_id');
$passdata = array_intersect_key($userdata, array_flip($passkeys));
success(array('user' => $passdata));
} else {
echo "Your username and password were not found in our system.";
exit;
}
function challenge() {
header('WWW-Authenticate: Basic realm="SERPs.com API"');
echo "Sorry, you have to log in to access the SERPs.com API";
exit;
}
function success($data) {
header('HTTP/1.1 200 OK', true);
header('Content-Type: application/json');
echo json_encode($data);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment