<?php

require_once 'Outspark/3rdparty/Restafarian/OSKRestResource.php';

class OSKSignedRestResource extends OSKRestResource {
	private static $key_master = null;
	private static $signature_check = true;

	function __construct()
	{
		if (!self::$key_master) {
			self::$key_master = OSKKeyMaster::getInstance();
		}

		$conf = parse_ini_file('/var/www/conf/restconf.ini');
		self::$signature_check = $conf['signature_check'];
	}

	final public function GET ($req, $resp)
	{
		if (self::$signature_check) {
			if ($this->_verifyRequest($req, $resp)) {
				$this->signedGET($req, $resp);
			}
		} else {
			$this->signedGET($req, $resp);
		}
	}

	protected function _verifyRequest($req, $resp)
	{
		$uri = clone $req->getUri();
		$params = $uri->getQueryParams();

		$apikey = $params->getFirst('apikey');
		if(empty($apikey)){
			$apikey = $params->getFirst('realm');
		}
		$sig = $params->getFirst('sig');

		if (empty($sig) || empty($apikey)) {
			$resp->setStatusCode(REST_STATUS_UNAUTHORIZED);
			$resp->makeError($this, $resp->getStatusCode(), 'Unauthorized access');
			return false;
		}
		$uri->deleteQueryParam('sig');
		$uri->setAuthority('');
		$uri->setScheme('');
		$signed_uri = $uri->asString();

		$secret = self::$key_master->getKey($apikey . '.sign');

		$our_sig = hash('sha256', $signed_uri . $secret);

		$t = hash('sha256', $secret);

		if ($sig != $our_sig)  {
			$resp->setStatusCode(REST_STATUS_UNAUTHORIZED);
			$resp->makeError($this, $resp->getStatusCode(), 'Unauthorized access');
			return false;
		}

		return true;
	}
}

?>
