Skip to content

Instantly share code, notes, and snippets.

@waqqas
Last active November 20, 2015 07:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save waqqas/1d9c88b7c7e6568696ff to your computer and use it in GitHub Desktop.
Save waqqas/1d9c88b7c7e6568696ff to your computer and use it in GitHub Desktop.
ApiHelper Class
<?php
class ApiHelper
{
public static function GetAllowedOrigins()
{
if ($key = Yii::app()->getRequest()->getParam('apikey')) {
$origins = Origin::model()->findAll(array(
'select' => 'url',
'with' => array('key_search' =>
array(
'select' => false,
'together' => true,
)
),
'condition' => 'key_search.key = :apiKey',
'params' => array(
':apiKey' => $key,
)
));
return array_map(function ($origin) {
return $origin->url;
}, $origins);
}
return array();
}
}
<?php
class m150430_064427_create_api_key_tables extends CDbMigration
{
public function safeUp()
{
$this->createTable('{{apikey}}', array(
'id' => 'pk',
'key' => 'varchar(64) not null',
'KEY `key_index` (`key`)'
), 'ENGINE=InnoDB'
);
$this->createTable('{{origin}}', array(
'id' => 'pk',
'url' => 'varchar(256) not null',
'key_id' => 'int(10) NOT NULL',
'foreign key (`key_id`) references `{{apikey}}` (`id`) on delete cascade on update cascade',
), 'ENGINE=InnoDB'
);
}
public function safeDown()
{
$this->dropTable('{{origin}}');
$this->dropTable('{{apikey}}');
}
}
public function restEvents()
{
$this->onRest('req.cors.access.control.allow.origin', function() {
return ApiHelper::GetAllowedOrigins();
});
$this->onRest('req.cors.access.control.allow.methods', function() {
return array('GET', 'POST', 'PUT', 'DELETE','OPTIONS');
});
$this->onRest('req.cors.access.control.allow.headers', function($application_id) {
return array();
});
$this->onRest('req.auth.type', function($application_id) {
// set value of origin header, if not present
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : Yii::app()->getBaseUrl(true);
$_SERVER['HTTP_ORIGIN'] = $origin;
// treat all request as CORS
return ERestEventListenerRegistry::REQ_TYPE_CORS;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment