Skip to content

Commit

Permalink
Add rest capabilities #101
Browse files Browse the repository at this point in the history
  • Loading branch information
MathieuNls committed Feb 7, 2016
1 parent f6b546b commit 147d76a
Show file tree
Hide file tree
Showing 5 changed files with 86 additions and 54 deletions.
2 changes: 1 addition & 1 deletion application/config/rest.php
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,7 @@
| ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
*/
$config['rest_enable_keys'] = FALSE;
$config['rest_enable_keys'] = TRUE;

/*
|--------------------------------------------------------------------------
Expand Down
7 changes: 5 additions & 2 deletions application/config/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,5 +72,8 @@
| -------------------------------------------------------------------------
*/

$route['api/example/users/(:num)'] = 'api/user/create/$1'; // Example 4
$route['api/example/users/(:num)(\.)([a-zA-Z0-9_-]+)(.*)'] = 'api/example/users/id/$1/format/$3$4'; // Example 8
$route['api/(:any)'] = 'api/$1_api';

//
// $route['api/example/users/(:num)'] = 'api/user/create/$1'; // Example 4
// $route['api/example/users/(:num)(\.)([a-zA-Z0-9_-]+)(.*)'] = 'api/example/users/id/$1/format/$3$4'; // Example 8
89 changes: 59 additions & 30 deletions application/libraries/REST_Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -624,6 +624,8 @@ public function _remap($object_called, $arguments)
$this->config->item('rest_status_field_name') => FALSE,
$this->config->item('rest_message_field_name') => sprintf($this->lang->line('text_rest_invalid_api_key'), $this->rest->key)
], self::HTTP_FORBIDDEN);

return;
}

// Check to see if this key has access to the requested controller
Expand All @@ -638,6 +640,8 @@ public function _remap($object_called, $arguments)
$this->config->item('rest_status_field_name') => FALSE,
$this->config->item('rest_message_field_name') => $this->lang->line('text_rest_api_key_unauthorized')
], self::HTTP_UNAUTHORIZED);

return;
}

// Sure it exists, but can they do anything with it?
Expand All @@ -657,6 +661,7 @@ public function _remap($object_called, $arguments)
{
$response = [$this->config->item('rest_status_field_name') => FALSE, $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_api_key_time_limit')];
$this->response($response, self::HTTP_UNAUTHORIZED);
return;
}

// If no level is set use 0, they probably aren't using permissions
Expand All @@ -672,8 +677,11 @@ public function _remap($object_called, $arguments)
}

// They don't have good enough perms
$response = [$this->config->item('rest_status_field_name') => FALSE, $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_api_key_permissions')];
$authorized || $this->response($response, self::HTTP_UNAUTHORIZED);
if($authorized == false){
$response = [$this->config->item('rest_status_field_name') => FALSE, $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_api_key_permissions')];
$this->response($response, self::HTTP_UNAUTHORIZED);
return;
}
}

// No key stuff, but record that stuff is happening
Expand Down Expand Up @@ -709,7 +717,7 @@ public function _remap($object_called, $arguments)
* @param bool $continue TRUE to flush the response to the client and continue
* running the script; otherwise, exit
*/
public function response($data = NULL, $http_code = NULL, $continue = FALSE)
public function response($data = NULL, $http_code = NULL)
{
// If the HTTP status is not NULL, then cast as an integer
if ($http_code !== NULL)
Expand Down Expand Up @@ -770,17 +778,7 @@ public function response($data = NULL, $http_code = NULL, $continue = FALSE)
$this->_log_response_code($http_code);
}

// Output the data
$this->output->set_output($output);

if ($continue === FALSE)
{
// Display the data and exit execution
$this->output->_display();
exit;
}

// Otherwise dump the output automatically
$this->output->_display($output);
}

/**
Expand Down Expand Up @@ -963,6 +961,14 @@ protected function _detect_api_key()
// Work out the name of the SERVER entry based on config
$key_name = 'HTTP_' . strtoupper(str_replace('-', '_', $api_key_variable));

// echo PHP_EOL.PHP_EOL.'=========API KEY========='.PHP_EOL;
// echo "here".PHP_EOL.$key_name.PHP_EOL;
// echo "args".PHP_EOL;
// var_dump($this->_args);
// echo '$this->input->server('.$key_name.')'.PHP_EOL;
// var_dump($this->input->server($key_name));
// echo PHP_EOL.'========================'.PHP_EOL.PHP_EOL;

$this->rest->key = NULL;
$this->rest->level = NULL;
$this->rest->user_id = NULL;
Expand All @@ -980,6 +986,7 @@ protected function _detect_api_key()

isset($row->user_id) && $this->rest->user_id = $row->user_id;
isset($row->level) && $this->rest->level = $row->level;
isset($row->id) && $this->rest->key_id = $row->id;
isset($row->ignore_limits) && $this->rest->ignore_limits = $row->ignore_limits;

$this->_apiuser = $row;
Expand Down Expand Up @@ -1067,22 +1074,33 @@ protected function _detect_lang()
protected function _log_request($authorized = FALSE)
{
// Insert the request into the log table
$is_inserted = $this->rest->db
->insert(
$this->config->item('rest_logs_table'), [
'uri' => $this->uri->uri_string(),
'method' => $this->request->method,
'params' => $this->_args ? ($this->config->item('rest_logs_json_params') === TRUE ? json_encode($this->_args) : serialize($this->_args)) : NULL,
'api_key' => isset($this->rest->key) ? $this->rest->key : '',
'ip_address' => $this->input->ip_address(),
'time' => time(),
'authorized' => $authorized
]);

// Get the last insert id to update at a later stage of the request
$this->_insert_id = $this->rest->db->insert_id();

return $is_inserted;
// $is_inserted = $this->rest->db
// ->insert(
// $this->config->item('rest_logs_table'), [
// 'uri' => $this->uri->uri_string(),
// 'method' => $this->request->method,
// 'params' => $this->_args ? ($this->config->item('rest_logs_json_params') === TRUE ? json_encode($this->_args) : serialize($this->_args)) : NULL,
// 'api_key' => isset($this->rest->key) ? $this->rest->key : '',
// 'ip_address' => $this->input->ip_address(),
// 'time' => time(),
// 'authorized' => $authorized
// ]);
//
// // Get the last insert id to update at a later stage of the request
// $this->_insert_id = $this->rest->db->insert_id();

log_message('INFO', print_r([
'uri' => $this->uri->uri_string(),
'method' => $this->request->method,
'params' => $this->_args ? ($this->config->item('rest_logs_json_params') === TRUE ? json_encode($this->_args) : serialize($this->_args)) : NULL,
'api_key' => isset($this->rest->key) ? $this->rest->key : '',
'ip_address' => $this->input->ip_address(),
'time' => time(),
'authorized' => $authorized
], true));

//return $is_inserted;
return 1;
}

/**
Expand Down Expand Up @@ -1424,6 +1442,12 @@ protected function _parse_put()
// If no filetype is provided, then there are probably just arguments
$this->_put_args = $this->input->input_stream();
}


if(sizeof($this->_put_args) === 0){
$this->_parse_post();
$this->_put_args = $this->_post_args;
}
}

/**
Expand Down Expand Up @@ -1489,6 +1513,11 @@ protected function _parse_delete()
{
$this->_delete_args = $this->input->input_stream();
}

if(sizeof($this->_delete_args) === 0){
$this->_parse_post();
$this->_delete_args = $this->_post_args;
}
}

/**
Expand Down
38 changes: 18 additions & 20 deletions application/models/Key.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
<?php if (!defined('BASEPATH')) {exit('No direct script access allowed');
}

class Key extends ObservableModel {
/**
* Manages API keys
*/
class Key extends MY_MODEL {

/**
* Default constructeur
Expand All @@ -12,45 +15,40 @@ function __construct() {
$this->load->config("rest");
}

public function has_valide_key($userId, $key){
return $this->select("count(*)")
->where("user_id", $userId)
->find_by("key", $key) > 0;
}

/**
* Generate a key for a given user
* @param User $user
* @return String generated key
*/
public function generate_key($user)
{
do
{
// Generate a random salt
$salt = base_convert(bin2hex($this->security->get_random_bytes(64)), 16, 36);

// If an error occurred, then fall back to the previous method
if ($salt === FALSE)
{
$salt = hash('sha256', time() . mt_rand());
}

$new_key = substr($salt, 0, config_item('rest_key_length'));
}
while ($this->key_exists($key));
while ($this->key_exists($new_key));

$data[config_item('rest_key_column')] = $key;
$data[config_item('rest_key_column')] = $new_key;
$data['date_created'] = function_exists('now') ? now() : time();
$data['user_id'] = $user->userId;

if(($this->update_where("user_id", $user->userId, $data) === true
&& $this->affected_rows() === 1)
||
&& $this->affected_rows() === 1) ||
($this->insert($data) !== false
&& $this->affected_rows() === 1)){

return $key;
return $new_key;
}

return false;
}

/**
* Checks if a key already exists
* @param String $key
* @return boolean
*/
private function key_exists($key)
{
return $this->count_by(config_item('rest_key_column'), $key) > 0;
Expand Down
4 changes: 3 additions & 1 deletion application/tests/phpunit.xml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@
<exclude>
<file>../libraries/__.php</file>
<file>../libraries/Mcapi.php</file>
<file>../libraries/Mandrill.php</file>
<file>../libraries/Mandrill.php</file>
<file>../libraries/REST_Controller.php</file>
<file>../libraries/Format.php</file>
<directory suffix=".php">../libraries/Mandrill</directory>
<directory suffix=".php">../libraries/Google</directory>
</exclude>
Expand Down

0 comments on commit 147d76a

Please sign in to comment.