Skip to content

Instantly share code, notes, and snippets.

@Gargron
Created April 23, 2012 16:14
Show Gist options
  • Save Gargron/2471982 to your computer and use it in GitHub Desktop.
Save Gargron/2471982 to your computer and use it in GitHub Desktop.
API call authorization class for The Colorless API
<?php
/**
* Used to authorize API calls based on public API keys
* and private encryption comparison. Only useful for
* server-side API calls since you'd have to open
* up the private key in plaintext if you tried to do
* this from JavaScript.
*
* @author Eugen Rochko
*/
class ApiAuth
{
/**
* Current user of the application API
*
* @var User
*/
public static $user;
/**
* Checksum the incoming API request. Returns true on success or boolean
* false on failure. After success, you can access current user with
* ApiAuth::user()
*
* @param array Incoming request values, all of them
* @param string The hash of the request
* @param string Public key of the request
* @return bool
*/
public static function authorize($request, $their_request_blob_hash, $public_key)
{
$api_user = self::find($public_key);
if(empty($api_user))
return false;
$our_request_blob = http_build_query(array_diff_key($request, array('key', 'hash', 'timestamp')));
$timestamp = $request['timestamp'];
$current_timestamp = time();
$min_timestamp = $current_timestamp - (60*5);
if($timestamp > $current_timestamp || $timestamp < $min_timestamp)
return false;
# How the hash is built (concatenated):
# -------------------------------------
# + The HTTP method
# + The request blob (http_build_query of all variables except the key, the hash and the timestamp)
# + The timestamp
$our_request_blob_hash = hash_hmac('sha1', Request::method() . $our_request_blob . $timestamp, $api_user->private_key);
if($our_request_blob_hash === $their_request_blob_hash)
{
self::$user = User::find($api_user->user_id);
return true;
}
else
{
return false;
}
}
/**
* Get the currently authorized user
*
* @return mixed User or boolean false
*/
public static function user()
{
if(is_null(self::$user))
return false;
else
return self::$user;
}
/**
* Find the public key in the DB
*
* @param string
* @return stdClass
*/
protected static function find($public_key)
{
return DB::first("SELECT * FROM keys WHERE public_key = ?", array($public_key));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment