This commit is contained in:
Paminger
2016-03-11 10:08:34 +01:00
parent 24756d9cf3
commit 19129266b2
19 changed files with 1153 additions and 12 deletions
+272
View File
@@ -0,0 +1,272 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
// This can be removed if you use __autoload() in config.php OR use Modular Extensions
require APPPATH . '/libraries/REST_Controller.php';
/**
* Keys Controller
* This is a basic Key Management REST controller to make and delete keys
*
* @package CodeIgniter
* @subpackage Rest Server
* @category Controller
* @author Phil Sturgeon, Chris Kacerguis
* @license MIT
* @link https://github.com/chriskacerguis/codeigniter-restserver
*/
class Key extends REST_Controller {
protected $methods = [
'index_put' => ['level' => 10, 'limit' => 10],
'index_delete' => ['level' => 10],
'level_post' => ['level' => 10],
'regenerate_post' => ['level' => 10],
];
/**
* Insert a key into the database
*
* @access public
* @return void
*/
public function index_put()
{
// Build a new key
$key = $this->_generate_key();
// If no key level provided, provide a generic key
$level = $this->put('level') ? $this->put('level') : 1;
$ignore_limits = ctype_digit($this->put('ignore_limits')) ? (int) $this->put('ignore_limits') : 1;
// Insert the new key
if ($this->_insert_key($key, ['level' => $level, 'ignore_limits' => $ignore_limits]))
{
$this->response([
'status' => TRUE,
'key' => $key
], REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code
}
else
{
$this->response([
'status' => FALSE,
'message' => 'Could not save the key'
], REST_Controller::HTTP_INTERNAL_SERVER_ERROR); // INTERNAL_SERVER_ERROR (500) being the HTTP response code
}
}
/**
* Remove a key from the database to stop it working
*
* @access public
* @return void
*/
public function index_delete()
{
$key = $this->delete('key');
// Does this key exist?
if (!$this->_key_exists($key))
{
// It doesn't appear the key exists
$this->response([
'status' => FALSE,
'message' => 'Invalid API key'
], REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
}
// Destroy it
$this->_delete_key($key);
// Respond that the key was destroyed
$this->response([
'status' => TRUE,
'message' => 'API key was deleted'
], REST_Controller::HTTP_NO_CONTENT); // NO_CONTENT (204) being the HTTP response code
}
/**
* Change the level
*
* @access public
* @return void
*/
public function level_post()
{
$key = $this->post('key');
$new_level = $this->post('level');
// Does this key exist?
if (!$this->_key_exists($key))
{
// It doesn't appear the key exists
$this->response([
'status' => FALSE,
'message' => 'Invalid API key'
], REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
}
// Update the key level
if ($this->_update_key($key, ['level' => $new_level]))
{
$this->response([
'status' => TRUE,
'message' => 'API key was updated'
], REST_Controller::HTTP_OK); // OK (200) being the HTTP response code
}
else
{
$this->response([
'status' => FALSE,
'message' => 'Could not update the key level'
], REST_Controller::HTTP_INTERNAL_SERVER_ERROR); // INTERNAL_SERVER_ERROR (500) being the HTTP response code
}
}
/**
* Suspend a key
*
* @access public
* @return void
*/
public function suspend_post()
{
$key = $this->post('key');
// Does this key exist?
if (!$this->_key_exists($key))
{
// It doesn't appear the key exists
$this->response([
'status' => FALSE,
'message' => 'Invalid API key'
], REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
}
// Update the key level
if ($this->_update_key($key, ['level' => 0]))
{
$this->response([
'status' => TRUE,
'message' => 'Key was suspended'
], REST_Controller::HTTP_OK); // OK (200) being the HTTP response code
}
else
{
$this->response([
'status' => FALSE,
'message' => 'Could not suspend the user'
], REST_Controller::HTTP_INTERNAL_SERVER_ERROR); // INTERNAL_SERVER_ERROR (500) being the HTTP response code
}
}
/**
* Regenerate a key
*
* @access public
* @return void
*/
public function regenerate_post()
{
$old_key = $this->post('key');
$key_details = $this->_get_key($old_key);
// Does this key exist?
if (!$key_details)
{
// It doesn't appear the key exists
$this->response([
'status' => FALSE,
'message' => 'Invalid API key'
], REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
}
// Build a new key
$new_key = $this->_generate_key();
// Insert the new key
if ($this->_insert_key($new_key, ['level' => $key_details->level, 'ignore_limits' => $key_details->ignore_limits]))
{
// Suspend old key
$this->_update_key($old_key, ['level' => 0]);
$this->response([
'status' => TRUE,
'key' => $new_key
], REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code
}
else
{
$this->response([
'status' => FALSE,
'message' => 'Could not save the key'
], REST_Controller::HTTP_INTERNAL_SERVER_ERROR); // INTERNAL_SERVER_ERROR (500) being the HTTP response code
}
}
/* Helper Methods */
private function _generate_key()
{
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($new_key));
return $new_key;
}
/* Private Data Methods */
private function _get_key($key)
{
return $this->db
->where(config_item('rest_key_column'), $key)
->get(config_item('rest_keys_table'))
->row();
}
private function _key_exists($key)
{
return $this->db
->where(config_item('rest_key_column'), $key)
->count_all_results(config_item('rest_keys_table')) > 0;
}
private function _insert_key($key, $data)
{
$data[config_item('rest_key_column')] = $key;
$data['date_created'] = function_exists('now') ? now() : time();
return $this->db
->set($data)
->insert(config_item('rest_keys_table'));
}
private function _update_key($key, $data)
{
return $this->db
->where(config_item('rest_key_column'), $key)
->update(config_item('rest_keys_table'), $data);
}
private function _delete_key($key)
{
return $this->db
->where(config_item('rest_key_column'), $key)
->delete(config_item('rest_keys_table'));
}
}
+11
View File
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html>
+130
View File
@@ -0,0 +1,130 @@
<?php
/**
* Whisperocity
*
* @package Whisperocity
* @author WSP-Team
* @copyright Copyright (c) 2015, Whisperocity
* @license proprietary
* @link http://whisperocity.com/
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
defined('BASEPATH') OR exit('No direct script access allowed');
// This can be removed if you use __autoload() in config.php OR use Modular Extensions
require APPPATH . '/libraries/REST_Controller.php';
/**
* Handles user authentication and registration process
*/
class AuthAPI extends REST_Controller {
/**
* Userauth-Controller constructor.
* A more elaborate description of the constructor.
* {@inheritdoc}
*/
function __construct()
{
// Construct the parent class
parent::__construct();
// Configure limits on our controller methods
// Ensure you have created the 'limits' table and enabled 'limits' within application/config/rest.php
$this->methods['login_get']['limit'] = 500; // 500 requests per hour per user/key
// Load helper
$this->load->helper('fhcauth');
$this->load->library('session');
}
/**
* Checks user credentials and creates a new session
* @return string JSON that indicates success/failure of login
* @example normal account: http://wsp.fortyseeds.at/backend/api/userauth/login/username/foo%40bar.at/password/secret/device_id/abcdef123
* @example OAuth Google: http://wsp.fortyseeds.at/backend/api/userauth/login/username/foo%40bar.at/device_id/abcdef123/google_token/qwert321
* @example OAuth Facebook: http://wsp.fortyseeds.at/backend/api/userauth/login/username/foo%40bar.at/device_id/abcdef123/fb_token/qwert321
*/
public function login_get()
{
$payload = array();
$errormsg = "";
$httpstatus = null;
$username = urldecode($this->get('username'));
$password = urldecode($this->get('password'));
$account = auth($username,$password);
// perform login checks
if (!$account)
$errormsg = "Auth not accepted!";
if (empty($errormsg))
{
// generate new session
$this->session->sess_regenerate();
$token = session_id();
$payload = [
'success' => true,
'message' => 'User successfully logged in',
'session_id' => $token
];
$httpstatus = REST_Controller::HTTP_OK;
}
else
{
$payload = [
'success' => false,
'message' => $errormsg
];
$httpstatus = REST_Controller::HTTP_UNAUTHORIZED;
}
// Set the response and exit
$this->response($payload, $httpstatus);
}
/**
* Logs out user by destroying session
* @return string JSON that indicates success/failure of logout
* @example http://wsp.fortyseeds.at/backend/api/userauth/logout/username/foo%40bar.at/session_id/55afab8ba6f1b/device_id/abcdef123
*/
public function logout_get()
{
$payload = array();
$httpstatus = null;
$token = $this->get('session_id');
$username = urldecode($this->get('username'));
$deviceid = $this->get('device_id');
$account = $this->user_model->load($username);
// destroy session
if ($this->session_model->destroy($account, $token, $deviceid))
{
$payload = [
'success' => true,
'message' => 'user successfully logged out'
];
$httpstatus = REST_Controller::HTTP_OK;
}
else
{
$payload = [
'success' => false,
'message' => 'user could not be logged out'
];
$httpstatus = REST_Controller::HTTP_BAD_REQUEST;
}
// Set the response and exit
$this->response($payload, $httpstatus);
}
}
+140
View File
@@ -0,0 +1,140 @@
<?php
/**
* @file
* This is an example of a few basic user interaction methods you could use
* all done with a hardcoded array
*
* @package CodeIgniter
* @subpackage Rest Server
* @category Controller
* @author Phil Sturgeon, Chris Kacerguis
* @license MIT
* @link https://github.com/chriskacerguis/codeigniter-restserver
*/
defined('BASEPATH') OR exit('No direct script access allowed');
// This can be removed if you use __autoload() in config.php OR use Modular Extensions
require APPPATH . '/libraries/REST_Controller.php';
class Example extends REST_Controller {
/**
* @copydoc REST_Controller::__construct()
*/
function __construct()
{
// Construct the parent class
parent::__construct();
// Configure limits on our controller methods
// Ensure you have created the 'limits' table and enabled 'limits' within application/config/rest.php
$this->methods['user_get']['limit'] = 500; // 500 requests per hour per user/key
$this->methods['user_post']['limit'] = 100; // 100 requests per hour per user/key
$this->methods['user_delete']['limit'] = 50; // 50 requests per hour per user/key
}
public function users_get()
{
// Users from a data store e.g. database
$users = [
['id' => 1, 'name' => 'John', 'email' => 'john@example.com', 'fact' => 'Loves coding'],
['id' => 2, 'name' => 'Jim', 'email' => 'jim@example.com', 'fact' => 'Developed on CodeIgniter'],
['id' => 3, 'name' => 'Jane', 'email' => 'jane@example.com', 'fact' => 'Lives in the USA', ['hobbies' => ['guitar', 'cycling']]],
];
$id = $this->get('id');
// If the id parameter doesn't exist return all the users
if ($id === NULL)
{
// Check if the users data store contains users (in case the database result returns NULL)
if ($users)
{
// Set the response and exit
$this->response($users, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code
}
else
{
// Set the response and exit
$this->response([
'status' => FALSE,
'message' => 'No users were found'
], REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code
}
}
// Find and return a single record for a particular user.
$id = (int) $id;
// Validate the id.
if ($id <= 0)
{
// Invalid id, set the response and exit.
$this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
}
// Get the user from the array, using the id as key for retreival.
// Usually a model is to be used for this.
$user = NULL;
if (!empty($users))
{
foreach ($users as $key => $value)
{
if (isset($value['id']) && $value['id'] === $id)
{
$user = $value;
}
}
}
if (!empty($user))
{
$this->set_response($user, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code
}
else
{
$this->set_response([
'status' => FALSE,
'message' => 'User could not be found'
], REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code
}
}
public function users_post()
{
// $this->some_model->update_user( ... );
$message = [
'id' => 100, // Automatically generated by the model
'name' => $this->post('name'),
'email' => $this->post('email'),
'message' => 'Added a resource'
];
$this->set_response($message, REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code
}
public function users_delete()
{
$id = (int) $this->get('id');
// Validate the id.
if ($id <= 0)
{
// Set the response and exit
$this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
}
// $this->some_model->delete_something($id);
$message = [
'id' => $id,
'message' => 'Deleted the resource'
];
$this->set_response($message, REST_Controller::HTTP_NO_CONTENT); // NO_CONTENT (204) being the HTTP response code
}
}
+367
View File
@@ -0,0 +1,367 @@
<?php
/**
* FH-Complete
*
* @package FHC-API
* @author FHC-Team
* @copyright Copyright (c) 2016, fhcomplete.org
* @license GPLv3
* @link http://fhcomplete.org
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
defined('BASEPATH') OR exit('No direct script access allowed');
class Person extends API_Controller
{
//public $session;
/**
* Person API constructor.
*/
function __construct()
{
parent::__construct();
$this->load->model('person/person_model');
}
public function person_get()
{
//if (!$this->session_model->validate($this->get('session_id'), $this->get('device_id')))
// $this->response(array(['success' => false, 'message' => 'access denied']), REST_Controller::HTTP_UNAUTHORIZED);
$code = $this->get('code');
if (!is_null($code))
$result = $this->person_model->getPersonByCode($code);
// var_dump($result[0]);
if (empty($result))
{
$payload = [
'success' => false,
'message' => 'Person not found'
];
$httpstatus = REST_Controller::HTTP_OK;
}
else
{
// return all available locations
$payload = [
'success' => true,
'message' => 'Person with code found',
'person_id' => $result[0]->person_id
];
$httpstatus = REST_Controller::HTTP_OK;
}
// Set the response and exit
$this->response($payload, $httpstatus);
}
/**
* Creates a new location for whisper or returns all available locations
* within a certain radius
* @return string JSON that indicates success/failure of creating location
* @example http://wsp.fortyseeds.at/backend/api/whisper/location/name/Foo/latitude/37.37888785004527/longitude/-120.333251953125/session_id/55afab8ba6f1b/device_id/abcdef123
*/
public function location_get()
{
if (!$this->session_model->validate($this->get('session_id'), $this->get('device_id')))
$this->response(array(['success' => false, 'message' => 'access denied']), REST_Controller::HTTP_UNAUTHORIZED);
$name = urldecode($this->get('name'));
$latitude = $this->get('latitude');
$longitude = $this->get('longitude');
if (!empty($name) && !empty($latitude) && !empty($longitude))
{
// check available locations
$locsWithinRadius = $this->location_model->getLocationsWithinRadius($latitude, $longitude);
if (empty($locsWithinRadius))
{
// create new location
$locId = $this->location_model->create($name, $latitude, $longitude);
if ($locId !== false)
{
$payload = [
'success' => true,
'message' => 'location created successfully',
'location_id' => $locId
];
$httpstatus = REST_Controller::HTTP_CREATED;
}
else
{
$payload = [
'success' => false,
'message' => 'location could not be created'
];
$httpstatus = REST_Controller::HTTP_INTERNAL_SERVER_ERROR;
}
}
else
{
// return all available locations
$payload = [
'success' => true,
'message' => '1 or more locations available',
'location_id' => $locsWithinRadius
];
$httpstatus = REST_Controller::HTTP_OK;
}
}
else
{
$payload = [
'success' => false,
'message' => "name, latitude or longitude missing"
];
$httpstatus = REST_Controller::HTTP_BAD_REQUEST;
}
// Set the response and exit
$this->response($payload, $httpstatus);
}
/**
* Creates a new whisper
* @return string JSON that indicates success/failure of creating location
* @example http://wsp.fortyseeds.at/backend/api/whisper/create/session_id/55afab8ba6f1b/device_id/abcdef123
*/
public function create_post()
{
if (!$this->session_model->validate($this->get('session_id'), $this->get('device_id')))
$this->response(array(['success' => false, 'message' => 'access denied']), REST_Controller::HTTP_UNAUTHORIZED);
$data = $this->post('whisper');
// perform checks if whisper can be created
$errormsg = "";
$notNull = array('location_id', 'name', 'type', 'description', 'scenery', 'price', 'sportiness', 'address', 'category');
foreach ($notNull as $key)
{
if (empty($data[$key]))
{
$errormsg = "missing data";
break;
}
}
if (empty($errormsg))
{
if (!empty($data['picture']))
{
// save file name in the profile
$data['picture'] = $this->_savePicture($data['picture']);
}
// add user ID to data
$session = $this->session_model->load($this->get('session_id'));
$data['user_id'] = $session->user_id;
// create new whisper
$whisperId = $this->whisper_model->create($data);
if ($whisperId !== false)
{
// check if user status change is necessary
if ($this->status_model->current($session->user_id) != 'full' &&
$this->whisper_model->count($session->user_id) >= $this->config->item('userstatus_full_whisperer'))
{
$this->status_model->set($session->user_id, 'full');
}
$payload = [
'success' => true,
'message' => 'whisper created successfully',
'whisper_id' => $whisperId
];
$httpstatus = REST_Controller::HTTP_CREATED;
}
else
{
$payload = [
'success' => false,
'message' => 'whisper could not be created'
];
$httpstatus = REST_Controller::HTTP_INTERNAL_SERVER_ERROR;
}
}
else
{
$payload = [
'success' => false,
'message' => $errormsg
];
$httpstatus = REST_Controller::HTTP_BAD_REQUEST;
}
// Set the response and exit
$this->response($payload, $httpstatus);
}
/**
* Edits a whisper
* @return string JSON that indicates success/failure of editing whisper
* @example http://wsp.fortyseeds.at/backend/api/whisper/edit/whisper_id/1/session_id/55afab8ba6f1b/device_id/abcdef123
*/
public function edit_post()
{
if (!$this->session_model->validate($this->get('session_id'), $this->get('device_id')))
$this->response(array(['success' => false, 'message' => 'access denied']), REST_Controller::HTTP_UNAUTHORIZED);
$data = $this->post('whisper');
$whisperId = $this->get('whisper_id');
// perform checks if whisper can be edited
$errormsg = "";
$notNull = array('location_id', 'name', 'type', 'description', 'scenery', 'price', 'sportiness', 'address', 'category');
foreach ($notNull as $key)
{
if (isset($data[$key]) && empty($data[$key]))
{
$errormsg = "missing data";
break;
}
}
if (empty($errormsg))
{
if (!empty($data['picture']))
{
$data['picture'] = $this->_savePicture($data['picture']);
}
// load user session
$session = $this->session_model->load($this->get('session_id'));
// save changes
$result = $this->whisper_model->edit($whisperId, $data, $session->user_id);
if ($result === 1)
{
$payload = [
'success' => true,
'message' => 'whisper edited successfully'
];
$httpstatus = REST_Controller::HTTP_OK;
}
else
{
$payload = [
'success' => false,
'message' => 'whisper does not exist or does not belong to user'
];
$httpstatus = REST_Controller::HTTP_BAD_REQUEST;
}
}
else
{
$payload = [
'success' => false,
'message' => $errormsg
];
$httpstatus = REST_Controller::HTTP_BAD_REQUEST;
}
// Set the response and exit
$this->response($payload, $httpstatus);
}
/**
* Returns all whispers of a user
* @return string JSON with whisper data
* @example http://wsp.fortyseeds.at/backend/api/whisper/personal/session_id/55afab8ba6f1b/device_id/abcdef123
*/
public function personal_get()
{
if (!$this->session_model->validate($this->get('session_id'), $this->get('device_id')))
$this->response(array(['success' => false, 'message' => 'access denied']), REST_Controller::HTTP_UNAUTHORIZED);
$profile = $this->profile_model->loadBySession($this->get('session_id'));
$whispers = $this->whisper_model->getByUser($profile->user_id);
$payload = [
'success' => true,
'message' => 'whispers returned successfully',
'whispers' => $whispers
];
$httpstatus = REST_Controller::HTTP_OK;
// Set the response and exit
$this->response($payload, $httpstatus);
}
/**
* Deletes a whisper
* @return string JSON that indicates success/failure of deleting whisper
* @example http://wsp.fortyseeds.at/backend/api/whisper/delete/session_id/d05434b3728bd2a525a1947c3ec4d754/device_id/abcdef123/whisper_id/7/reason/Gef%C3%A4llt%20mir%20nicht%20mehr
*/
public function delete_get()
{
if (!$this->session_model->validate($this->get('session_id'), $this->get('device_id')))
$this->response(array(['success' => false, 'message' => 'access denied']), REST_Controller::HTTP_UNAUTHORIZED);
$whisperId = $this->get('whisper_id');
$this->get('reason') == '' ? $reason = 'null' : $reason = "'" . urldecode($this->get('reason')) . "'";
$profile = $this->profile_model->loadBySession($this->get('session_id'));
$result = $this->whisper_model->delete($whisperId, $profile->user_id, $reason);
if ($result === 0)
{
$payload = [
'success' => false,
'message' => 'whisper does not exist or does not belong to user'
];
$httpstatus = REST_Controller::HTTP_BAD_REQUEST;
}
else
{
$payload = [
'success' => true,
'message' => 'whisper deleted successfully'
];
$httpstatus = REST_Controller::HTTP_OK;
}
// Set the response and exit
$this->response($payload, $httpstatus);
}
/**
* Decodes base64 image data and saves file to disk
* @param string $base64data
* @return string path and file name of picture
*/
private function _savePicture($base64data)
{
// decode data and get file type
$imgdata = base64_decode($base64data);
$fileinfo = finfo_open();
$mimetype = finfo_buffer($fileinfo, $imgdata, FILEINFO_MIME_TYPE);
$ext = str_replace('image/', '.', $mimetype);
$tmpfname = tempnam($this->config->item('whisperpic_path'), "wsp");
$picfname = $tmpfname . $ext;
// save pic to disk
$handle = fopen($picfname, "w");
fwrite($handle, $imgdata);
fclose($handle);
// delete tmp file
if (is_file($tmpfname))
unlink($tmpfname);
// return file name
return $picfname;
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php
/**
* Whisperocity
*
* @package Whisperocity
* @author WSP-Team
* @copyright Copyright (c) 2015, Whisperocity
* @license proprietary
* @link http://whisperocity.com/
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
defined('BASEPATH') OR exit('No direct script access allowed');
// This can be removed if you use __autoload() in config.php OR use Modular Extensions
require APPPATH . '/libraries/REST_Controller.php';
/**
* Handles ping attempts of applications
*/
class Ping extends REST_Controller {
/**
* Ping-Controller constructor.
* A more elaborate description of the constructor.
*/
function __construct()
{
// Construct the parent class
parent::__construct();
// Configure limits on our controller methods
// Ensure you have created the 'limits' table and enabled 'limits' within application/config/rest.php
$this->methods['ping_get']['limit'] = 500; // 500 requests per hour per user/key
}
/**
* Responds to ping attempts of applications
* @return string JSON which acknowledges the ping attempt
* @example http://wsp.fortyseeds.at/backend/api/ping
*/
public function index_get()
{
$payload = [
'success' => true,
'message' => 'ping received'
];
// Set the response and exit
$this->response($payload, REST_Controller::HTTP_OK);
}
}