mirror of
https://github.com/silverstripe/silverstripe-restfulserver
synced 2024-10-22 14:05:58 +02:00
Converted to PSR-2
This commit is contained in:
parent
de3dc96d39
commit
96f868dbf5
@ -8,32 +8,34 @@
|
|||||||
* application accessing the RestfulServer to store logins in plain text (or in
|
* application accessing the RestfulServer to store logins in plain text (or in
|
||||||
* decrytable form)
|
* decrytable form)
|
||||||
*/
|
*/
|
||||||
class BasicRestfulAuthenticator {
|
class BasicRestfulAuthenticator
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* The authenticate function
|
||||||
|
*
|
||||||
|
* Takes the basic auth details and attempts to log a user in from the DB
|
||||||
|
*
|
||||||
|
* @return Member|false The Member object, or false if no member
|
||||||
|
*/
|
||||||
|
public static function authenticate()
|
||||||
|
{
|
||||||
|
//if there is no username or password, break
|
||||||
|
if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
//Attempt to authenticate with the default authenticator for the site
|
||||||
* The authenticate function
|
$authClass = Authenticator::get_default_authenticator();
|
||||||
*
|
$member = $authClass::authenticate(array(
|
||||||
* Takes the basic auth details and attempts to log a user in from the DB
|
'Email' => $_SERVER['PHP_AUTH_USER'],
|
||||||
*
|
'Password' => $_SERVER['PHP_AUTH_PW'],
|
||||||
* @return Member|false The Member object, or false if no member
|
));
|
||||||
*/
|
|
||||||
public static function authenticate() {
|
|
||||||
//if there is no username or password, break
|
|
||||||
if(!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) return false;
|
|
||||||
|
|
||||||
//Attempt to authenticate with the default authenticator for the site
|
|
||||||
$authClass = Authenticator::get_default_authenticator();
|
|
||||||
$member = $authClass::authenticate(array(
|
|
||||||
'Email' => $_SERVER['PHP_AUTH_USER'],
|
|
||||||
'Password' => $_SERVER['PHP_AUTH_PW'],
|
|
||||||
));
|
|
||||||
|
|
||||||
//Log the member in and return the member, if they were found
|
|
||||||
if($member) {
|
|
||||||
$member->LogIn(false);
|
|
||||||
return $member;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
//Log the member in and return the member, if they were found
|
||||||
|
if ($member) {
|
||||||
|
$member->LogIn(false);
|
||||||
|
return $member;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -26,560 +26,629 @@
|
|||||||
* @package framework
|
* @package framework
|
||||||
* @subpackage api
|
* @subpackage api
|
||||||
*/
|
*/
|
||||||
class RestfulServer extends Controller {
|
class RestfulServer extends Controller
|
||||||
static $url_handlers = array(
|
{
|
||||||
'$ClassName/$ID/$Relation' => 'handleAction'
|
public static $url_handlers = array(
|
||||||
#'$ClassName/#ID' => 'handleItem',
|
'$ClassName/$ID/$Relation' => 'handleAction'
|
||||||
#'$ClassName' => 'handleList',
|
#'$ClassName/#ID' => 'handleItem',
|
||||||
);
|
#'$ClassName' => 'handleList',
|
||||||
|
);
|
||||||
|
|
||||||
protected static $api_base = "api/v1/";
|
protected static $api_base = "api/v1/";
|
||||||
|
|
||||||
protected static $authenticator = 'BasicRestfulAuthenticator';
|
protected static $authenticator = 'BasicRestfulAuthenticator';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* If no extension is given in the request, resolve to this extension
|
* If no extension is given in the request, resolve to this extension
|
||||||
* (and subsequently the {@link self::$default_mimetype}.
|
* (and subsequently the {@link self::$default_mimetype}.
|
||||||
*
|
*
|
||||||
* @var string
|
* @var string
|
||||||
*/
|
*/
|
||||||
public static $default_extension = "xml";
|
public static $default_extension = "xml";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* If no extension is given, resolve the request to this mimetype.
|
* If no extension is given, resolve the request to this mimetype.
|
||||||
*
|
*
|
||||||
* @var string
|
* @var string
|
||||||
*/
|
*/
|
||||||
protected static $default_mimetype = "text/xml";
|
protected static $default_mimetype = "text/xml";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @uses authenticate()
|
* @uses authenticate()
|
||||||
* @var Member
|
* @var Member
|
||||||
*/
|
*/
|
||||||
protected $member;
|
protected $member;
|
||||||
|
|
||||||
public static $allowed_actions = array(
|
public static $allowed_actions = array(
|
||||||
'index'
|
'index'
|
||||||
);
|
);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
function handleItem($request) {
|
function handleItem($request) {
|
||||||
return new RestfulServer_Item(DataObject::get_by_id($request->param("ClassName"), $request->param("ID")));
|
return new RestfulServer_Item(DataObject::get_by_id($request->param("ClassName"), $request->param("ID")));
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleList($request) {
|
function handleList($request) {
|
||||||
return new RestfulServer_List(DataObject::get($request->param("ClassName"),""));
|
return new RestfulServer_List(DataObject::get($request->param("ClassName"),""));
|
||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
|
|
||||||
function init() {
|
public function init()
|
||||||
/* This sets up SiteTree the same as when viewing a page through the frontend. Versioned defaults
|
{
|
||||||
* to Stage, and then when viewing the front-end Versioned::choose_site_stage changes it to Live.
|
/* This sets up SiteTree the same as when viewing a page through the frontend. Versioned defaults
|
||||||
* TODO: In 3.2 we should make the default Live, then change to Stage in the admin area (with a nicer API)
|
* to Stage, and then when viewing the front-end Versioned::choose_site_stage changes it to Live.
|
||||||
*/
|
* TODO: In 3.2 we should make the default Live, then change to Stage in the admin area (with a nicer API)
|
||||||
if (class_exists('SiteTree')) singleton('SiteTree')->extend('modelascontrollerInit', $this);
|
*/
|
||||||
parent::init();
|
if (class_exists('SiteTree')) {
|
||||||
}
|
singleton('SiteTree')->extend('modelascontrollerInit', $this);
|
||||||
|
}
|
||||||
|
parent::init();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This handler acts as the switchboard for the controller.
|
* This handler acts as the switchboard for the controller.
|
||||||
* Since no $Action url-param is set, all requests are sent here.
|
* Since no $Action url-param is set, all requests are sent here.
|
||||||
*/
|
*/
|
||||||
function index() {
|
public function index()
|
||||||
if(!isset($this->urlParams['ClassName'])) return $this->notFound();
|
{
|
||||||
$className = $this->urlParams['ClassName'];
|
if (!isset($this->urlParams['ClassName'])) {
|
||||||
$id = (isset($this->urlParams['ID'])) ? $this->urlParams['ID'] : null;
|
return $this->notFound();
|
||||||
$relation = (isset($this->urlParams['Relation'])) ? $this->urlParams['Relation'] : null;
|
}
|
||||||
|
$className = $this->urlParams['ClassName'];
|
||||||
// Check input formats
|
$id = (isset($this->urlParams['ID'])) ? $this->urlParams['ID'] : null;
|
||||||
if(!class_exists($className)) return $this->notFound();
|
$relation = (isset($this->urlParams['Relation'])) ? $this->urlParams['Relation'] : null;
|
||||||
if($id && !is_numeric($id)) return $this->notFound();
|
|
||||||
if(
|
// Check input formats
|
||||||
$relation
|
if (!class_exists($className)) {
|
||||||
&& !preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $relation)
|
return $this->notFound();
|
||||||
) {
|
}
|
||||||
return $this->notFound();
|
if ($id && !is_numeric($id)) {
|
||||||
}
|
return $this->notFound();
|
||||||
|
}
|
||||||
// if api access is disabled, don't proceed
|
if (
|
||||||
$apiAccess = singleton($className)->stat('api_access');
|
$relation
|
||||||
if(!$apiAccess) return $this->permissionFailure();
|
&& !preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $relation)
|
||||||
|
) {
|
||||||
|
return $this->notFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
// if api access is disabled, don't proceed
|
||||||
|
$apiAccess = singleton($className)->stat('api_access');
|
||||||
|
if (!$apiAccess) {
|
||||||
|
return $this->permissionFailure();
|
||||||
|
}
|
||||||
|
|
||||||
// authenticate through HTTP BasicAuth
|
// authenticate through HTTP BasicAuth
|
||||||
$this->member = $this->authenticate();
|
$this->member = $this->authenticate();
|
||||||
|
|
||||||
// handle different HTTP verbs
|
// handle different HTTP verbs
|
||||||
if($this->request->isGET() || $this->request->isHEAD()) {
|
if ($this->request->isGET() || $this->request->isHEAD()) {
|
||||||
return $this->getHandler($className, $id, $relation);
|
return $this->getHandler($className, $id, $relation);
|
||||||
}
|
}
|
||||||
|
|
||||||
if($this->request->isPOST()) {
|
if ($this->request->isPOST()) {
|
||||||
return $this->postHandler($className, $id, $relation);
|
return $this->postHandler($className, $id, $relation);
|
||||||
}
|
}
|
||||||
|
|
||||||
if($this->request->isPUT()) {
|
if ($this->request->isPUT()) {
|
||||||
return $this->putHandler($className, $id, $relation);
|
return $this->putHandler($className, $id, $relation);
|
||||||
}
|
}
|
||||||
|
|
||||||
if($this->request->isDELETE()) {
|
if ($this->request->isDELETE()) {
|
||||||
return $this->deleteHandler($className, $id, $relation);
|
return $this->deleteHandler($className, $id, $relation);
|
||||||
}
|
}
|
||||||
|
|
||||||
// if no HTTP verb matches, return error
|
// if no HTTP verb matches, return error
|
||||||
return $this->methodNotAllowed();
|
return $this->methodNotAllowed();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handler for object read.
|
* Handler for object read.
|
||||||
*
|
*
|
||||||
* The data object will be returned in the following format:
|
* The data object will be returned in the following format:
|
||||||
*
|
*
|
||||||
* <ClassName>
|
* <ClassName>
|
||||||
* <FieldName>Value</FieldName>
|
* <FieldName>Value</FieldName>
|
||||||
* ...
|
* ...
|
||||||
* <HasOneRelName id="ForeignID" href="LinkToForeignRecordInAPI" />
|
* <HasOneRelName id="ForeignID" href="LinkToForeignRecordInAPI" />
|
||||||
* ...
|
* ...
|
||||||
* <HasManyRelName>
|
* <HasManyRelName>
|
||||||
* <ForeignClass id="ForeignID" href="LinkToForeignRecordInAPI" />
|
* <ForeignClass id="ForeignID" href="LinkToForeignRecordInAPI" />
|
||||||
* <ForeignClass id="ForeignID" href="LinkToForeignRecordInAPI" />
|
* <ForeignClass id="ForeignID" href="LinkToForeignRecordInAPI" />
|
||||||
* </HasManyRelName>
|
* </HasManyRelName>
|
||||||
* ...
|
* ...
|
||||||
* <ManyManyRelName>
|
* <ManyManyRelName>
|
||||||
* <ForeignClass id="ForeignID" href="LinkToForeignRecordInAPI" />
|
* <ForeignClass id="ForeignID" href="LinkToForeignRecordInAPI" />
|
||||||
* <ForeignClass id="ForeignID" href="LinkToForeignRecordInAPI" />
|
* <ForeignClass id="ForeignID" href="LinkToForeignRecordInAPI" />
|
||||||
* </ManyManyRelName>
|
* </ManyManyRelName>
|
||||||
* </ClassName>
|
* </ClassName>
|
||||||
*
|
*
|
||||||
* Access is controlled by two variables:
|
* Access is controlled by two variables:
|
||||||
*
|
*
|
||||||
* - static $api_access must be set. This enables the API on a class by class basis
|
* - static $api_access must be set. This enables the API on a class by class basis
|
||||||
* - $obj->canView() must return true. This lets you implement record-level security
|
* - $obj->canView() must return true. This lets you implement record-level security
|
||||||
*
|
*
|
||||||
* @todo Access checking
|
* @todo Access checking
|
||||||
*
|
*
|
||||||
* @param String $className
|
* @param String $className
|
||||||
* @param Int $id
|
* @param Int $id
|
||||||
* @param String $relation
|
* @param String $relation
|
||||||
* @return String The serialized representation of the requested object(s) - usually XML or JSON.
|
* @return String The serialized representation of the requested object(s) - usually XML or JSON.
|
||||||
*/
|
*/
|
||||||
protected function getHandler($className, $id, $relationName) {
|
protected function getHandler($className, $id, $relationName)
|
||||||
$sort = '';
|
{
|
||||||
|
$sort = '';
|
||||||
if($this->request->getVar('sort')) {
|
|
||||||
$dir = $this->request->getVar('dir');
|
if ($this->request->getVar('sort')) {
|
||||||
$sort = array($this->request->getVar('sort') => ($dir ? $dir : 'ASC'));
|
$dir = $this->request->getVar('dir');
|
||||||
}
|
$sort = array($this->request->getVar('sort') => ($dir ? $dir : 'ASC'));
|
||||||
|
}
|
||||||
$limit = array(
|
|
||||||
'start' => $this->request->getVar('start'),
|
$limit = array(
|
||||||
'limit' => $this->request->getVar('limit')
|
'start' => $this->request->getVar('start'),
|
||||||
);
|
'limit' => $this->request->getVar('limit')
|
||||||
|
);
|
||||||
$params = $this->request->getVars();
|
|
||||||
|
$params = $this->request->getVars();
|
||||||
$responseFormatter = $this->getResponseDataFormatter($className);
|
|
||||||
if(!$responseFormatter) return $this->unsupportedMediaType();
|
$responseFormatter = $this->getResponseDataFormatter($className);
|
||||||
|
if (!$responseFormatter) {
|
||||||
// $obj can be either a DataObject or a SS_List,
|
return $this->unsupportedMediaType();
|
||||||
// depending on the request
|
}
|
||||||
if($id) {
|
|
||||||
// Format: /api/v1/<MyClass>/<ID>
|
// $obj can be either a DataObject or a SS_List,
|
||||||
$obj = $this->getObjectQuery($className, $id, $params)->First();
|
// depending on the request
|
||||||
if(!$obj) return $this->notFound();
|
if ($id) {
|
||||||
if(!$obj->canView()) return $this->permissionFailure();
|
// Format: /api/v1/<MyClass>/<ID>
|
||||||
|
$obj = $this->getObjectQuery($className, $id, $params)->First();
|
||||||
|
if (!$obj) {
|
||||||
|
return $this->notFound();
|
||||||
|
}
|
||||||
|
if (!$obj->canView()) {
|
||||||
|
return $this->permissionFailure();
|
||||||
|
}
|
||||||
|
|
||||||
// Format: /api/v1/<MyClass>/<ID>/<Relation>
|
// Format: /api/v1/<MyClass>/<ID>/<Relation>
|
||||||
if($relationName) {
|
if ($relationName) {
|
||||||
$obj = $this->getObjectRelationQuery($obj, $params, $sort, $limit, $relationName);
|
$obj = $this->getObjectRelationQuery($obj, $params, $sort, $limit, $relationName);
|
||||||
if(!$obj) return $this->notFound();
|
if (!$obj) {
|
||||||
|
return $this->notFound();
|
||||||
// TODO Avoid creating data formatter again for relation class (see above)
|
}
|
||||||
$responseFormatter = $this->getResponseDataFormatter($obj->dataClass());
|
|
||||||
}
|
// TODO Avoid creating data formatter again for relation class (see above)
|
||||||
|
$responseFormatter = $this->getResponseDataFormatter($obj->dataClass());
|
||||||
} else {
|
}
|
||||||
// Format: /api/v1/<MyClass>
|
} else {
|
||||||
$obj = $this->getObjectsQuery($className, $params, $sort, $limit);
|
// Format: /api/v1/<MyClass>
|
||||||
}
|
$obj = $this->getObjectsQuery($className, $params, $sort, $limit);
|
||||||
|
}
|
||||||
$this->getResponse()->addHeader('Content-Type', $responseFormatter->getOutputContentType());
|
|
||||||
|
$this->getResponse()->addHeader('Content-Type', $responseFormatter->getOutputContentType());
|
||||||
$rawFields = $this->request->getVar('fields');
|
|
||||||
$fields = $rawFields ? explode(',', $rawFields) : null;
|
$rawFields = $this->request->getVar('fields');
|
||||||
|
$fields = $rawFields ? explode(',', $rawFields) : null;
|
||||||
|
|
||||||
if($obj instanceof SS_List) {
|
if ($obj instanceof SS_List) {
|
||||||
$responseFormatter->setTotalSize($obj->dataQuery()->query()->unlimitedRowCount());
|
$responseFormatter->setTotalSize($obj->dataQuery()->query()->unlimitedRowCount());
|
||||||
$objs = new ArrayList($obj->toArray());
|
$objs = new ArrayList($obj->toArray());
|
||||||
foreach($objs as $obj) if(!$obj->canView()) $objs->remove($obj);
|
foreach ($objs as $obj) {
|
||||||
return $responseFormatter->convertDataObjectSet($objs, $fields);
|
if (!$obj->canView()) {
|
||||||
} else if(!$obj) {
|
$objs->remove($obj);
|
||||||
$responseFormatter->setTotalSize(0);
|
}
|
||||||
return $responseFormatter->convertDataObjectSet(new ArrayList(), $fields);
|
}
|
||||||
} else {
|
return $responseFormatter->convertDataObjectSet($objs, $fields);
|
||||||
return $responseFormatter->convertDataObject($obj, $fields);
|
} elseif (!$obj) {
|
||||||
}
|
$responseFormatter->setTotalSize(0);
|
||||||
}
|
return $responseFormatter->convertDataObjectSet(new ArrayList(), $fields);
|
||||||
|
} else {
|
||||||
/**
|
return $responseFormatter->convertDataObject($obj, $fields);
|
||||||
* Uses the default {@link SearchContext} specified through
|
}
|
||||||
* {@link DataObject::getDefaultSearchContext()} to augument
|
}
|
||||||
* an existing query object (mostly a component query from {@link DataObject})
|
|
||||||
* with search clauses.
|
/**
|
||||||
*
|
* Uses the default {@link SearchContext} specified through
|
||||||
* @todo Allow specifying of different searchcontext getters on model-by-model basis
|
* {@link DataObject::getDefaultSearchContext()} to augument
|
||||||
*
|
* an existing query object (mostly a component query from {@link DataObject})
|
||||||
* @param string $className
|
* with search clauses.
|
||||||
* @param array $params
|
*
|
||||||
* @return SS_List
|
* @todo Allow specifying of different searchcontext getters on model-by-model basis
|
||||||
*/
|
*
|
||||||
protected function getSearchQuery($className, $params = null, $sort = null,
|
* @param string $className
|
||||||
$limit = null, $existingQuery = null
|
* @param array $params
|
||||||
) {
|
* @return SS_List
|
||||||
if(singleton($className)->hasMethod('getRestfulSearchContext')) {
|
*/
|
||||||
$searchContext = singleton($className)->{'getRestfulSearchContext'}();
|
protected function getSearchQuery($className, $params = null, $sort = null,
|
||||||
} else {
|
$limit = null, $existingQuery = null
|
||||||
$searchContext = singleton($className)->getDefaultSearchContext();
|
) {
|
||||||
}
|
if (singleton($className)->hasMethod('getRestfulSearchContext')) {
|
||||||
return $searchContext->getQuery($params, $sort, $limit, $existingQuery);
|
$searchContext = singleton($className)->{'getRestfulSearchContext'}();
|
||||||
}
|
} else {
|
||||||
|
$searchContext = singleton($className)->getDefaultSearchContext();
|
||||||
/**
|
}
|
||||||
* Returns a dataformatter instance based on the request
|
return $searchContext->getQuery($params, $sort, $limit, $existingQuery);
|
||||||
* extension or mimetype. Falls back to {@link self::$default_extension}.
|
}
|
||||||
*
|
|
||||||
* @param boolean $includeAcceptHeader Determines wether to inspect and prioritize any HTTP Accept headers
|
/**
|
||||||
* @param String Classname of a DataObject
|
* Returns a dataformatter instance based on the request
|
||||||
* @return DataFormatter
|
* extension or mimetype. Falls back to {@link self::$default_extension}.
|
||||||
*/
|
*
|
||||||
protected function getDataFormatter($includeAcceptHeader = false, $className = null) {
|
* @param boolean $includeAcceptHeader Determines wether to inspect and prioritize any HTTP Accept headers
|
||||||
$extension = $this->request->getExtension();
|
* @param String Classname of a DataObject
|
||||||
$contentTypeWithEncoding = $this->request->getHeader('Content-Type');
|
* @return DataFormatter
|
||||||
preg_match('/([^;]*)/',$contentTypeWithEncoding, $contentTypeMatches);
|
*/
|
||||||
$contentType = $contentTypeMatches[0];
|
protected function getDataFormatter($includeAcceptHeader = false, $className = null)
|
||||||
$accept = $this->request->getHeader('Accept');
|
{
|
||||||
$mimetypes = $this->request->getAcceptMimetypes();
|
$extension = $this->request->getExtension();
|
||||||
if(!$className) $className = $this->urlParams['ClassName'];
|
$contentTypeWithEncoding = $this->request->getHeader('Content-Type');
|
||||||
|
preg_match('/([^;]*)/', $contentTypeWithEncoding, $contentTypeMatches);
|
||||||
|
$contentType = $contentTypeMatches[0];
|
||||||
|
$accept = $this->request->getHeader('Accept');
|
||||||
|
$mimetypes = $this->request->getAcceptMimetypes();
|
||||||
|
if (!$className) {
|
||||||
|
$className = $this->urlParams['ClassName'];
|
||||||
|
}
|
||||||
|
|
||||||
// get formatter
|
// get formatter
|
||||||
if(!empty($extension)) {
|
if (!empty($extension)) {
|
||||||
$formatter = DataFormatter::for_extension($extension);
|
$formatter = DataFormatter::for_extension($extension);
|
||||||
}elseif($includeAcceptHeader && !empty($accept) && $accept != '*/*') {
|
} elseif ($includeAcceptHeader && !empty($accept) && $accept != '*/*') {
|
||||||
$formatter = DataFormatter::for_mimetypes($mimetypes);
|
$formatter = DataFormatter::for_mimetypes($mimetypes);
|
||||||
if(!$formatter) $formatter = DataFormatter::for_extension(self::$default_extension);
|
if (!$formatter) {
|
||||||
} elseif(!empty($contentType)) {
|
$formatter = DataFormatter::for_extension(self::$default_extension);
|
||||||
$formatter = DataFormatter::for_mimetype($contentType);
|
}
|
||||||
} else {
|
} elseif (!empty($contentType)) {
|
||||||
$formatter = DataFormatter::for_extension(self::$default_extension);
|
$formatter = DataFormatter::for_mimetype($contentType);
|
||||||
}
|
} else {
|
||||||
|
$formatter = DataFormatter::for_extension(self::$default_extension);
|
||||||
|
}
|
||||||
|
|
||||||
if(!$formatter) return false;
|
if (!$formatter) {
|
||||||
|
return false;
|
||||||
// set custom fields
|
}
|
||||||
if($customAddFields = $this->request->getVar('add_fields')) {
|
|
||||||
$formatter->setCustomAddFields(explode(',',$customAddFields));
|
// set custom fields
|
||||||
}
|
if ($customAddFields = $this->request->getVar('add_fields')) {
|
||||||
if($customFields = $this->request->getVar('fields')) {
|
$formatter->setCustomAddFields(explode(',', $customAddFields));
|
||||||
$formatter->setCustomFields(explode(',',$customFields));
|
}
|
||||||
}
|
if ($customFields = $this->request->getVar('fields')) {
|
||||||
$formatter->setCustomRelations($this->getAllowedRelations($className));
|
$formatter->setCustomFields(explode(',', $customFields));
|
||||||
|
}
|
||||||
$apiAccess = singleton($className)->stat('api_access');
|
$formatter->setCustomRelations($this->getAllowedRelations($className));
|
||||||
if(is_array($apiAccess)) {
|
|
||||||
$formatter->setCustomAddFields(
|
$apiAccess = singleton($className)->stat('api_access');
|
||||||
array_intersect((array)$formatter->getCustomAddFields(), (array)$apiAccess['view'])
|
if (is_array($apiAccess)) {
|
||||||
);
|
$formatter->setCustomAddFields(
|
||||||
if($formatter->getCustomFields()) {
|
array_intersect((array)$formatter->getCustomAddFields(), (array)$apiAccess['view'])
|
||||||
$formatter->setCustomFields(
|
);
|
||||||
array_intersect((array)$formatter->getCustomFields(), (array)$apiAccess['view'])
|
if ($formatter->getCustomFields()) {
|
||||||
);
|
$formatter->setCustomFields(
|
||||||
} else {
|
array_intersect((array)$formatter->getCustomFields(), (array)$apiAccess['view'])
|
||||||
$formatter->setCustomFields((array)$apiAccess['view']);
|
);
|
||||||
}
|
} else {
|
||||||
if($formatter->getCustomRelations()) {
|
$formatter->setCustomFields((array)$apiAccess['view']);
|
||||||
$formatter->setCustomRelations(
|
}
|
||||||
array_intersect((array)$formatter->getCustomRelations(), (array)$apiAccess['view'])
|
if ($formatter->getCustomRelations()) {
|
||||||
);
|
$formatter->setCustomRelations(
|
||||||
} else {
|
array_intersect((array)$formatter->getCustomRelations(), (array)$apiAccess['view'])
|
||||||
$formatter->setCustomRelations((array)$apiAccess['view']);
|
);
|
||||||
}
|
} else {
|
||||||
|
$formatter->setCustomRelations((array)$apiAccess['view']);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// set relation depth
|
// set relation depth
|
||||||
$relationDepth = $this->request->getVar('relationdepth');
|
$relationDepth = $this->request->getVar('relationdepth');
|
||||||
if(is_numeric($relationDepth)) $formatter->relationDepth = (int)$relationDepth;
|
if (is_numeric($relationDepth)) {
|
||||||
|
$formatter->relationDepth = (int)$relationDepth;
|
||||||
return $formatter;
|
}
|
||||||
}
|
|
||||||
|
return $formatter;
|
||||||
/**
|
}
|
||||||
* @param String Classname of a DataObject
|
|
||||||
* @return DataFormatter
|
/**
|
||||||
*/
|
* @param String Classname of a DataObject
|
||||||
protected function getRequestDataFormatter($className = null) {
|
* @return DataFormatter
|
||||||
return $this->getDataFormatter(false, $className);
|
*/
|
||||||
}
|
protected function getRequestDataFormatter($className = null)
|
||||||
|
{
|
||||||
/**
|
return $this->getDataFormatter(false, $className);
|
||||||
* @param String Classname of a DataObject
|
}
|
||||||
* @return DataFormatter
|
|
||||||
*/
|
/**
|
||||||
protected function getResponseDataFormatter($className = null) {
|
* @param String Classname of a DataObject
|
||||||
return $this->getDataFormatter(true, $className);
|
* @return DataFormatter
|
||||||
}
|
*/
|
||||||
|
protected function getResponseDataFormatter($className = null)
|
||||||
/**
|
{
|
||||||
* Handler for object delete
|
return $this->getDataFormatter(true, $className);
|
||||||
*/
|
}
|
||||||
protected function deleteHandler($className, $id) {
|
|
||||||
$obj = DataObject::get_by_id($className, $id);
|
/**
|
||||||
if(!$obj) return $this->notFound();
|
* Handler for object delete
|
||||||
if(!$obj->canDelete()) return $this->permissionFailure();
|
*/
|
||||||
|
protected function deleteHandler($className, $id)
|
||||||
$obj->delete();
|
{
|
||||||
|
$obj = DataObject::get_by_id($className, $id);
|
||||||
$this->getResponse()->setStatusCode(204); // No Content
|
if (!$obj) {
|
||||||
return true;
|
return $this->notFound();
|
||||||
}
|
}
|
||||||
|
if (!$obj->canDelete()) {
|
||||||
|
return $this->permissionFailure();
|
||||||
|
}
|
||||||
|
|
||||||
|
$obj->delete();
|
||||||
|
|
||||||
|
$this->getResponse()->setStatusCode(204); // No Content
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handler for object write
|
* Handler for object write
|
||||||
*/
|
*/
|
||||||
protected function putHandler($className, $id) {
|
protected function putHandler($className, $id)
|
||||||
$obj = DataObject::get_by_id($className, $id);
|
{
|
||||||
if(!$obj) return $this->notFound();
|
$obj = DataObject::get_by_id($className, $id);
|
||||||
if(!$obj->canEdit()) return $this->permissionFailure();
|
if (!$obj) {
|
||||||
|
return $this->notFound();
|
||||||
$reqFormatter = $this->getRequestDataFormatter($className);
|
}
|
||||||
if(!$reqFormatter) return $this->unsupportedMediaType();
|
if (!$obj->canEdit()) {
|
||||||
|
return $this->permissionFailure();
|
||||||
$responseFormatter = $this->getResponseDataFormatter($className);
|
}
|
||||||
if(!$responseFormatter) return $this->unsupportedMediaType();
|
|
||||||
|
$reqFormatter = $this->getRequestDataFormatter($className);
|
||||||
$obj = $this->updateDataObject($obj, $reqFormatter);
|
if (!$reqFormatter) {
|
||||||
|
return $this->unsupportedMediaType();
|
||||||
$this->getResponse()->setStatusCode(200); // Success
|
}
|
||||||
$this->getResponse()->addHeader('Content-Type', $responseFormatter->getOutputContentType());
|
|
||||||
|
$responseFormatter = $this->getResponseDataFormatter($className);
|
||||||
|
if (!$responseFormatter) {
|
||||||
|
return $this->unsupportedMediaType();
|
||||||
|
}
|
||||||
|
|
||||||
|
$obj = $this->updateDataObject($obj, $reqFormatter);
|
||||||
|
|
||||||
|
$this->getResponse()->setStatusCode(200); // Success
|
||||||
|
$this->getResponse()->addHeader('Content-Type', $responseFormatter->getOutputContentType());
|
||||||
|
|
||||||
// Append the default extension for the output format to the Location header
|
// Append the default extension for the output format to the Location header
|
||||||
// or else we'll use the default (XML)
|
// or else we'll use the default (XML)
|
||||||
$types = $responseFormatter->supportedExtensions();
|
$types = $responseFormatter->supportedExtensions();
|
||||||
$type = '';
|
$type = '';
|
||||||
if (count($types)) {
|
if (count($types)) {
|
||||||
$type = ".{$types[0]}";
|
$type = ".{$types[0]}";
|
||||||
}
|
}
|
||||||
|
|
||||||
$objHref = Director::absoluteURL(self::$api_base . "$obj->class/$obj->ID" . $type);
|
$objHref = Director::absoluteURL(self::$api_base . "$obj->class/$obj->ID" . $type);
|
||||||
$this->getResponse()->addHeader('Location', $objHref);
|
$this->getResponse()->addHeader('Location', $objHref);
|
||||||
|
|
||||||
return $responseFormatter->convertDataObject($obj);
|
return $responseFormatter->convertDataObject($obj);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handler for object append / method call.
|
* Handler for object append / method call.
|
||||||
*
|
*
|
||||||
* @todo Posting to an existing URL (without a relation)
|
* @todo Posting to an existing URL (without a relation)
|
||||||
* current resolves in creatig a new element,
|
* current resolves in creatig a new element,
|
||||||
* rather than a "Conflict" message.
|
* rather than a "Conflict" message.
|
||||||
*/
|
*/
|
||||||
protected function postHandler($className, $id, $relation) {
|
protected function postHandler($className, $id, $relation)
|
||||||
if($id) {
|
{
|
||||||
if(!$relation) {
|
if ($id) {
|
||||||
$this->response->setStatusCode(409);
|
if (!$relation) {
|
||||||
return 'Conflict';
|
$this->response->setStatusCode(409);
|
||||||
}
|
return 'Conflict';
|
||||||
|
}
|
||||||
$obj = DataObject::get_by_id($className, $id);
|
|
||||||
if(!$obj) return $this->notFound();
|
$obj = DataObject::get_by_id($className, $id);
|
||||||
|
if (!$obj) {
|
||||||
if(!$obj->hasMethod($relation)) {
|
return $this->notFound();
|
||||||
return $this->notFound();
|
}
|
||||||
}
|
|
||||||
|
if (!$obj->hasMethod($relation)) {
|
||||||
if(!$obj->stat('allowed_actions') || !in_array($relation, $obj->stat('allowed_actions'))) {
|
return $this->notFound();
|
||||||
return $this->permissionFailure();
|
}
|
||||||
}
|
|
||||||
|
if (!$obj->stat('allowed_actions') || !in_array($relation, $obj->stat('allowed_actions'))) {
|
||||||
$obj->$relation();
|
return $this->permissionFailure();
|
||||||
|
}
|
||||||
$this->getResponse()->setStatusCode(204); // No Content
|
|
||||||
return true;
|
$obj->$relation();
|
||||||
} else {
|
|
||||||
if(!singleton($className)->canCreate()) return $this->permissionFailure();
|
$this->getResponse()->setStatusCode(204); // No Content
|
||||||
$obj = new $className();
|
return true;
|
||||||
|
} else {
|
||||||
$reqFormatter = $this->getRequestDataFormatter($className);
|
if (!singleton($className)->canCreate()) {
|
||||||
if(!$reqFormatter) return $this->unsupportedMediaType();
|
return $this->permissionFailure();
|
||||||
|
}
|
||||||
$responseFormatter = $this->getResponseDataFormatter($className);
|
$obj = new $className();
|
||||||
|
|
||||||
$obj = $this->updateDataObject($obj, $reqFormatter);
|
$reqFormatter = $this->getRequestDataFormatter($className);
|
||||||
|
if (!$reqFormatter) {
|
||||||
$this->getResponse()->setStatusCode(201); // Created
|
return $this->unsupportedMediaType();
|
||||||
$this->getResponse()->addHeader('Content-Type', $responseFormatter->getOutputContentType());
|
}
|
||||||
|
|
||||||
|
$responseFormatter = $this->getResponseDataFormatter($className);
|
||||||
|
|
||||||
|
$obj = $this->updateDataObject($obj, $reqFormatter);
|
||||||
|
|
||||||
|
$this->getResponse()->setStatusCode(201); // Created
|
||||||
|
$this->getResponse()->addHeader('Content-Type', $responseFormatter->getOutputContentType());
|
||||||
|
|
||||||
// Append the default extension for the output format to the Location header
|
// Append the default extension for the output format to the Location header
|
||||||
// or else we'll use the default (XML)
|
// or else we'll use the default (XML)
|
||||||
$types = $responseFormatter->supportedExtensions();
|
$types = $responseFormatter->supportedExtensions();
|
||||||
$type = '';
|
$type = '';
|
||||||
if (count($types)) {
|
if (count($types)) {
|
||||||
$type = ".{$types[0]}";
|
$type = ".{$types[0]}";
|
||||||
}
|
}
|
||||||
|
|
||||||
$objHref = Director::absoluteURL(self::$api_base . "$obj->class/$obj->ID" . $type);
|
$objHref = Director::absoluteURL(self::$api_base . "$obj->class/$obj->ID" . $type);
|
||||||
$this->getResponse()->addHeader('Location', $objHref);
|
$this->getResponse()->addHeader('Location', $objHref);
|
||||||
|
|
||||||
return $responseFormatter->convertDataObject($obj);
|
return $responseFormatter->convertDataObject($obj);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Converts either the given HTTP Body into an array
|
* Converts either the given HTTP Body into an array
|
||||||
* (based on the DataFormatter instance), or returns
|
* (based on the DataFormatter instance), or returns
|
||||||
* the POST variables.
|
* the POST variables.
|
||||||
* Automatically filters out certain critical fields
|
* Automatically filters out certain critical fields
|
||||||
* that shouldn't be set by the client (e.g. ID).
|
* that shouldn't be set by the client (e.g. ID).
|
||||||
*
|
*
|
||||||
* @param DataObject $obj
|
* @param DataObject $obj
|
||||||
* @param DataFormatter $formatter
|
* @param DataFormatter $formatter
|
||||||
* @return DataObject The passed object
|
* @return DataObject The passed object
|
||||||
*/
|
*/
|
||||||
protected function updateDataObject($obj, $formatter) {
|
protected function updateDataObject($obj, $formatter)
|
||||||
// if neither an http body nor POST data is present, return error
|
{
|
||||||
$body = $this->request->getBody();
|
// if neither an http body nor POST data is present, return error
|
||||||
if(!$body && !$this->request->postVars()) {
|
$body = $this->request->getBody();
|
||||||
$this->getResponse()->setStatusCode(204); // No Content
|
if (!$body && !$this->request->postVars()) {
|
||||||
return 'No Content';
|
$this->getResponse()->setStatusCode(204); // No Content
|
||||||
}
|
return 'No Content';
|
||||||
|
}
|
||||||
if(!empty($body)) {
|
|
||||||
$data = $formatter->convertStringToArray($body);
|
if (!empty($body)) {
|
||||||
} else {
|
$data = $formatter->convertStringToArray($body);
|
||||||
// assume application/x-www-form-urlencoded which is automatically parsed by PHP
|
} else {
|
||||||
$data = $this->request->postVars();
|
// assume application/x-www-form-urlencoded which is automatically parsed by PHP
|
||||||
}
|
$data = $this->request->postVars();
|
||||||
|
}
|
||||||
// @todo Disallow editing of certain keys in database
|
|
||||||
$data = array_diff_key($data, array('ID','Created'));
|
// @todo Disallow editing of certain keys in database
|
||||||
|
$data = array_diff_key($data, array('ID', 'Created'));
|
||||||
$apiAccess = singleton($this->urlParams['ClassName'])->stat('api_access');
|
|
||||||
if(is_array($apiAccess) && isset($apiAccess['edit'])) {
|
$apiAccess = singleton($this->urlParams['ClassName'])->stat('api_access');
|
||||||
$data = array_intersect_key($data, array_combine($apiAccess['edit'],$apiAccess['edit']));
|
if (is_array($apiAccess) && isset($apiAccess['edit'])) {
|
||||||
}
|
$data = array_intersect_key($data, array_combine($apiAccess['edit'], $apiAccess['edit']));
|
||||||
|
}
|
||||||
|
|
||||||
$obj->update($data);
|
$obj->update($data);
|
||||||
$obj->write();
|
$obj->write();
|
||||||
|
|
||||||
return $obj;
|
return $obj;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets a single DataObject by ID,
|
* Gets a single DataObject by ID,
|
||||||
* through a request like /api/v1/<MyClass>/<MyID>
|
* through a request like /api/v1/<MyClass>/<MyID>
|
||||||
*
|
*
|
||||||
* @param string $className
|
* @param string $className
|
||||||
* @param int $id
|
* @param int $id
|
||||||
* @param array $params
|
* @param array $params
|
||||||
* @return DataList
|
* @return DataList
|
||||||
*/
|
*/
|
||||||
protected function getObjectQuery($className, $id, $params) {
|
protected function getObjectQuery($className, $id, $params)
|
||||||
return DataList::create($className)->byIDs(array($id));
|
{
|
||||||
}
|
return DataList::create($className)->byIDs(array($id));
|
||||||
|
}
|
||||||
/**
|
|
||||||
* @param DataObject $obj
|
/**
|
||||||
* @param array $params
|
* @param DataObject $obj
|
||||||
* @param int|array $sort
|
* @param array $params
|
||||||
* @param int|array $limit
|
* @param int|array $sort
|
||||||
* @return SQLQuery
|
* @param int|array $limit
|
||||||
*/
|
* @return SQLQuery
|
||||||
protected function getObjectsQuery($className, $params, $sort, $limit) {
|
*/
|
||||||
return $this->getSearchQuery($className, $params, $sort, $limit);
|
protected function getObjectsQuery($className, $params, $sort, $limit)
|
||||||
}
|
{
|
||||||
|
return $this->getSearchQuery($className, $params, $sort, $limit);
|
||||||
|
}
|
||||||
/**
|
|
||||||
* @param DataObject $obj
|
|
||||||
* @param array $params
|
/**
|
||||||
* @param int|array $sort
|
* @param DataObject $obj
|
||||||
* @param int|array $limit
|
* @param array $params
|
||||||
* @param string $relationName
|
* @param int|array $sort
|
||||||
* @return SQLQuery|boolean
|
* @param int|array $limit
|
||||||
*/
|
* @param string $relationName
|
||||||
protected function getObjectRelationQuery($obj, $params, $sort, $limit, $relationName) {
|
* @return SQLQuery|boolean
|
||||||
// The relation method will return a DataList, that getSearchQuery subsequently manipulates
|
*/
|
||||||
if($obj->hasMethod($relationName)) {
|
protected function getObjectRelationQuery($obj, $params, $sort, $limit, $relationName)
|
||||||
if($relationClass = $obj->has_one($relationName)) {
|
{
|
||||||
$joinField = $relationName . 'ID';
|
// The relation method will return a DataList, that getSearchQuery subsequently manipulates
|
||||||
$list = DataList::create($relationClass)->byIDs(array($obj->$joinField));
|
if ($obj->hasMethod($relationName)) {
|
||||||
} else {
|
if ($relationClass = $obj->has_one($relationName)) {
|
||||||
$list = $obj->$relationName();
|
$joinField = $relationName . 'ID';
|
||||||
}
|
$list = DataList::create($relationClass)->byIDs(array($obj->$joinField));
|
||||||
|
} else {
|
||||||
$apiAccess = singleton($list->dataClass())->stat('api_access');
|
$list = $obj->$relationName();
|
||||||
if(!$apiAccess) return false;
|
}
|
||||||
|
|
||||||
return $this->getSearchQuery($list->dataClass(), $params, $sort, $limit, $list);
|
$apiAccess = singleton($list->dataClass())->stat('api_access');
|
||||||
}
|
if (!$apiAccess) {
|
||||||
}
|
return false;
|
||||||
|
}
|
||||||
protected function permissionFailure() {
|
|
||||||
// return a 401
|
return $this->getSearchQuery($list->dataClass(), $params, $sort, $limit, $list);
|
||||||
$this->getResponse()->setStatusCode(401);
|
}
|
||||||
$this->getResponse()->addHeader('WWW-Authenticate', 'Basic realm="API Access"');
|
}
|
||||||
$this->getResponse()->addHeader('Content-Type', 'text/plain');
|
|
||||||
return "You don't have access to this item through the API.";
|
protected function permissionFailure()
|
||||||
}
|
{
|
||||||
|
// return a 401
|
||||||
|
$this->getResponse()->setStatusCode(401);
|
||||||
|
$this->getResponse()->addHeader('WWW-Authenticate', 'Basic realm="API Access"');
|
||||||
|
$this->getResponse()->addHeader('Content-Type', 'text/plain');
|
||||||
|
return "You don't have access to this item through the API.";
|
||||||
|
}
|
||||||
|
|
||||||
protected function notFound() {
|
protected function notFound()
|
||||||
// return a 404
|
{
|
||||||
$this->getResponse()->setStatusCode(404);
|
// return a 404
|
||||||
$this->getResponse()->addHeader('Content-Type', 'text/plain');
|
$this->getResponse()->setStatusCode(404);
|
||||||
return "That object wasn't found";
|
$this->getResponse()->addHeader('Content-Type', 'text/plain');
|
||||||
}
|
return "That object wasn't found";
|
||||||
|
}
|
||||||
protected function methodNotAllowed() {
|
|
||||||
$this->getResponse()->setStatusCode(405);
|
protected function methodNotAllowed()
|
||||||
$this->getResponse()->addHeader('Content-Type', 'text/plain');
|
{
|
||||||
return "Method Not Allowed";
|
$this->getResponse()->setStatusCode(405);
|
||||||
}
|
$this->getResponse()->addHeader('Content-Type', 'text/plain');
|
||||||
|
return "Method Not Allowed";
|
||||||
protected function unsupportedMediaType() {
|
}
|
||||||
$this->response->setStatusCode(415); // Unsupported Media Type
|
|
||||||
$this->getResponse()->addHeader('Content-Type', 'text/plain');
|
protected function unsupportedMediaType()
|
||||||
return "Unsupported Media Type";
|
{
|
||||||
}
|
$this->response->setStatusCode(415); // Unsupported Media Type
|
||||||
|
$this->getResponse()->addHeader('Content-Type', 'text/plain');
|
||||||
/**
|
return "Unsupported Media Type";
|
||||||
* A function to authenticate a user
|
}
|
||||||
*
|
|
||||||
* @return Member|false the logged in member
|
/**
|
||||||
*/
|
* A function to authenticate a user
|
||||||
protected function authenticate() {
|
*
|
||||||
$authClass = self::config()->authenticator;
|
* @return Member|false the logged in member
|
||||||
return $authClass::authenticate();
|
*/
|
||||||
}
|
protected function authenticate()
|
||||||
|
{
|
||||||
/**
|
$authClass = self::config()->authenticator;
|
||||||
* Return only relations which have $api_access enabled.
|
return $authClass::authenticate();
|
||||||
* @todo Respect field level permissions once they are available in core
|
}
|
||||||
*
|
|
||||||
* @param string $class
|
/**
|
||||||
* @param Member $member
|
* Return only relations which have $api_access enabled.
|
||||||
* @return array
|
* @todo Respect field level permissions once they are available in core
|
||||||
*/
|
*
|
||||||
protected function getAllowedRelations($class, $member = null) {
|
* @param string $class
|
||||||
$allowedRelations = array();
|
* @param Member $member
|
||||||
$obj = singleton($class);
|
* @return array
|
||||||
$relations = (array)$obj->has_one() + (array)$obj->has_many() + (array)$obj->many_many();
|
*/
|
||||||
if($relations) foreach($relations as $relName => $relClass) {
|
protected function getAllowedRelations($class, $member = null)
|
||||||
if(singleton($relClass)->stat('api_access')) {
|
{
|
||||||
$allowedRelations[] = $relName;
|
$allowedRelations = array();
|
||||||
}
|
$obj = singleton($class);
|
||||||
}
|
$relations = (array)$obj->has_one() + (array)$obj->has_many() + (array)$obj->many_many();
|
||||||
return $allowedRelations;
|
if ($relations) {
|
||||||
}
|
foreach ($relations as $relName => $relClass) {
|
||||||
|
if (singleton($relClass)->stat('api_access')) {
|
||||||
|
$allowedRelations[] = $relName;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return $allowedRelations;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -588,18 +657,21 @@ class RestfulServer extends Controller {
|
|||||||
* @package framework
|
* @package framework
|
||||||
* @subpackage api
|
* @subpackage api
|
||||||
*/
|
*/
|
||||||
class RestfulServer_List {
|
class RestfulServer_List
|
||||||
static $url_handlers = array(
|
{
|
||||||
'#ID' => 'handleItem',
|
public static $url_handlers = array(
|
||||||
);
|
'#ID' => 'handleItem',
|
||||||
|
);
|
||||||
|
|
||||||
function __construct($list) {
|
public function __construct($list)
|
||||||
$this->list = $list;
|
{
|
||||||
}
|
$this->list = $list;
|
||||||
|
}
|
||||||
function handleItem($request) {
|
|
||||||
return new RestulServer_Item($this->list->getById($request->param('ID')));
|
public function handleItem($request)
|
||||||
}
|
{
|
||||||
|
return new RestulServer_Item($this->list->getById($request->param('ID')));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -608,20 +680,26 @@ class RestfulServer_List {
|
|||||||
* @package framework
|
* @package framework
|
||||||
* @subpackage api
|
* @subpackage api
|
||||||
*/
|
*/
|
||||||
class RestfulServer_Item {
|
class RestfulServer_Item
|
||||||
static $url_handlers = array(
|
{
|
||||||
'$Relation' => 'handleRelation',
|
public static $url_handlers = array(
|
||||||
);
|
'$Relation' => 'handleRelation',
|
||||||
|
);
|
||||||
|
|
||||||
function __construct($item) {
|
public function __construct($item)
|
||||||
$this->item = $item;
|
{
|
||||||
}
|
$this->item = $item;
|
||||||
|
}
|
||||||
function handleRelation($request) {
|
|
||||||
$funcName = $request('Relation');
|
public function handleRelation($request)
|
||||||
$relation = $this->item->$funcName();
|
{
|
||||||
|
$funcName = $request('Relation');
|
||||||
|
$relation = $this->item->$funcName();
|
||||||
|
|
||||||
if($relation instanceof SS_List) return new RestfulServer_List($relation);
|
if ($relation instanceof SS_List) {
|
||||||
else return new RestfulServer_Item($relation);
|
return new RestfulServer_List($relation);
|
||||||
}
|
} else {
|
||||||
|
return new RestfulServer_Item($relation);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -19,4 +19,6 @@ MySQLDatabase::set_connection_charset('utf8');
|
|||||||
SSViewer::set_theme('simple');
|
SSViewer::set_theme('simple');
|
||||||
|
|
||||||
// Enable nested URLs for this site (e.g. page/sub-page/)
|
// Enable nested URLs for this site (e.g. page/sub-page/)
|
||||||
if(class_exists('SiteTree')) SiteTree::enable_nested_urls();
|
if (class_exists('SiteTree')) {
|
||||||
|
SiteTree::enable_nested_urls();
|
||||||
|
}
|
||||||
|
@ -5,33 +5,33 @@ define('SS_ENVIRONMENT_TYPE', 'dev');
|
|||||||
|
|
||||||
/* Database connection */
|
/* Database connection */
|
||||||
$db = getenv('TESTDB');
|
$db = getenv('TESTDB');
|
||||||
switch($db) {
|
switch ($db) {
|
||||||
case "PGSQL";
|
case "PGSQL";
|
||||||
define('SS_DATABASE_CLASS', 'PostgreSQLDatabase');
|
define('SS_DATABASE_CLASS', 'PostgreSQLDatabase');
|
||||||
define('SS_DATABASE_USERNAME', 'postgres');
|
define('SS_DATABASE_USERNAME', 'postgres');
|
||||||
define('SS_DATABASE_PASSWORD', '');
|
define('SS_DATABASE_PASSWORD', '');
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case "MYSQL":
|
case "MYSQL":
|
||||||
define('SS_DATABASE_CLASS', 'MySQLDatabase');
|
define('SS_DATABASE_CLASS', 'MySQLDatabase');
|
||||||
define('SS_DATABASE_USERNAME', 'root');
|
define('SS_DATABASE_USERNAME', 'root');
|
||||||
define('SS_DATABASE_PASSWORD', '');
|
define('SS_DATABASE_PASSWORD', '');
|
||||||
break;
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
define('SS_DATABASE_CLASS', 'SQLitePDODatabase');
|
define('SS_DATABASE_CLASS', 'SQLitePDODatabase');
|
||||||
define('SS_DATABASE_USERNAME', 'root');
|
define('SS_DATABASE_USERNAME', 'root');
|
||||||
define('SS_DATABASE_PASSWORD', '');
|
define('SS_DATABASE_PASSWORD', '');
|
||||||
}
|
}
|
||||||
|
|
||||||
echo SS_DATABASE_CLASS;
|
echo SS_DATABASE_CLASS;
|
||||||
|
|
||||||
define('SS_DATABASE_SERVER', 'localhost');
|
define('SS_DATABASE_SERVER', 'localhost');
|
||||||
define('SS_DATABASE_CHOOSE_NAME', true);
|
define('SS_DATABASE_CHOOSE_NAME', true);
|
||||||
|
|
||||||
|
|
||||||
/* Configure a default username and password to access the CMS on all sites in this environment. */
|
/* Configure a default username and password to access the CMS on all sites in this environment. */
|
||||||
define('SS_DEFAULT_ADMIN_USERNAME', 'username');
|
define('SS_DEFAULT_ADMIN_USERNAME', 'username');
|
||||||
define('SS_DEFAULT_ADMIN_PASSWORD', 'password');
|
define('SS_DEFAULT_ADMIN_PASSWORD', 'password');
|
||||||
|
|
||||||
$_FILE_TO_URL_MAPPING[dirname(__FILE__)] = 'http://localhost';
|
$_FILE_TO_URL_MAPPING[dirname(__FILE__)] = 'http://localhost';
|
||||||
|
@ -6,452 +6,474 @@
|
|||||||
* @todo Test DELETE verb
|
* @todo Test DELETE verb
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
class RestfulServerTest extends SapphireTest {
|
class RestfulServerTest extends SapphireTest
|
||||||
|
{
|
||||||
static $fixture_file = 'RestfulServerTest.yml';
|
public static $fixture_file = 'RestfulServerTest.yml';
|
||||||
|
|
||||||
protected $extraDataObjects = array(
|
protected $extraDataObjects = array(
|
||||||
'RestfulServerTest_Comment',
|
'RestfulServerTest_Comment',
|
||||||
'RestfulServerTest_SecretThing',
|
'RestfulServerTest_SecretThing',
|
||||||
'RestfulServerTest_Page',
|
'RestfulServerTest_Page',
|
||||||
'RestfulServerTest_Author',
|
'RestfulServerTest_Author',
|
||||||
'RestfulServerTest_AuthorRating',
|
'RestfulServerTest_AuthorRating',
|
||||||
);
|
);
|
||||||
|
|
||||||
public function testApiAccess() {
|
public function testApiAccess()
|
||||||
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
|
{
|
||||||
$page1 = $this->objFromFixture('RestfulServerTest_Page', 'page1');
|
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
|
||||||
|
$page1 = $this->objFromFixture('RestfulServerTest_Page', 'page1');
|
||||||
// normal GET should succeed with $api_access enabled
|
|
||||||
$url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID;
|
// normal GET should succeed with $api_access enabled
|
||||||
$response = Director::test($url, null, null, 'GET');
|
$url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID;
|
||||||
$this->assertEquals($response->getStatusCode(), 200);
|
$response = Director::test($url, null, null, 'GET');
|
||||||
|
$this->assertEquals($response->getStatusCode(), 200);
|
||||||
$_SERVER['PHP_AUTH_USER'] = 'user@test.com';
|
|
||||||
$_SERVER['PHP_AUTH_PW'] = 'user';
|
$_SERVER['PHP_AUTH_USER'] = 'user@test.com';
|
||||||
|
$_SERVER['PHP_AUTH_PW'] = 'user';
|
||||||
// even with logged in user a GET with $api_access disabled should fail
|
|
||||||
$url = "/api/v1/RestfulServerTest_Page/" . $page1->ID;
|
// even with logged in user a GET with $api_access disabled should fail
|
||||||
$response = Director::test($url, null, null, 'GET');
|
$url = "/api/v1/RestfulServerTest_Page/" . $page1->ID;
|
||||||
$this->assertEquals($response->getStatusCode(), 401);
|
$response = Director::test($url, null, null, 'GET');
|
||||||
|
$this->assertEquals($response->getStatusCode(), 401);
|
||||||
unset($_SERVER['PHP_AUTH_USER']);
|
|
||||||
unset($_SERVER['PHP_AUTH_PW']);
|
unset($_SERVER['PHP_AUTH_USER']);
|
||||||
}
|
unset($_SERVER['PHP_AUTH_PW']);
|
||||||
|
}
|
||||||
public function testApiAccessBoolean() {
|
|
||||||
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
|
public function testApiAccessBoolean()
|
||||||
|
{
|
||||||
$url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID;
|
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
|
||||||
$response = Director::test($url, null, null, 'GET');
|
|
||||||
$this->assertContains('<ID>', $response->getBody());
|
$url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID;
|
||||||
$this->assertContains('<Name>', $response->getBody());
|
$response = Director::test($url, null, null, 'GET');
|
||||||
$this->assertContains('<Comment>', $response->getBody());
|
$this->assertContains('<ID>', $response->getBody());
|
||||||
$this->assertContains('<Page', $response->getBody());
|
$this->assertContains('<Name>', $response->getBody());
|
||||||
$this->assertContains('<Author', $response->getBody());
|
$this->assertContains('<Comment>', $response->getBody());
|
||||||
}
|
$this->assertContains('<Page', $response->getBody());
|
||||||
|
$this->assertContains('<Author', $response->getBody());
|
||||||
public function testAuthenticatedGET() {
|
}
|
||||||
$thing1 = $this->objFromFixture('RestfulServerTest_SecretThing', 'thing1');
|
|
||||||
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
|
public function testAuthenticatedGET()
|
||||||
|
{
|
||||||
|
$thing1 = $this->objFromFixture('RestfulServerTest_SecretThing', 'thing1');
|
||||||
|
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
|
||||||
|
|
||||||
// @todo create additional mock object with authenticated VIEW permissions
|
// @todo create additional mock object with authenticated VIEW permissions
|
||||||
$url = "/api/v1/RestfulServerTest_SecretThing/" . $thing1->ID;
|
$url = "/api/v1/RestfulServerTest_SecretThing/" . $thing1->ID;
|
||||||
$response = Director::test($url, null, null, 'GET');
|
$response = Director::test($url, null, null, 'GET');
|
||||||
$this->assertEquals($response->getStatusCode(), 401);
|
$this->assertEquals($response->getStatusCode(), 401);
|
||||||
|
|
||||||
$_SERVER['PHP_AUTH_USER'] = 'user@test.com';
|
$_SERVER['PHP_AUTH_USER'] = 'user@test.com';
|
||||||
$_SERVER['PHP_AUTH_PW'] = 'user';
|
$_SERVER['PHP_AUTH_PW'] = 'user';
|
||||||
|
|
||||||
$url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID;
|
$url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID;
|
||||||
$response = Director::test($url, null, null, 'GET');
|
$response = Director::test($url, null, null, 'GET');
|
||||||
$this->assertEquals($response->getStatusCode(), 200);
|
$this->assertEquals($response->getStatusCode(), 200);
|
||||||
|
|
||||||
unset($_SERVER['PHP_AUTH_USER']);
|
unset($_SERVER['PHP_AUTH_USER']);
|
||||||
unset($_SERVER['PHP_AUTH_PW']);
|
unset($_SERVER['PHP_AUTH_PW']);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testAuthenticatedPUT() {
|
public function testAuthenticatedPUT()
|
||||||
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
|
{
|
||||||
|
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
|
||||||
$url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID;
|
|
||||||
$data = array('Comment' => 'created');
|
$url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID;
|
||||||
|
$data = array('Comment' => 'created');
|
||||||
$response = Director::test($url, $data, null, 'PUT');
|
|
||||||
$this->assertEquals($response->getStatusCode(), 401); // Permission failure
|
$response = Director::test($url, $data, null, 'PUT');
|
||||||
|
$this->assertEquals($response->getStatusCode(), 401); // Permission failure
|
||||||
$_SERVER['PHP_AUTH_USER'] = 'editor@test.com';
|
|
||||||
$_SERVER['PHP_AUTH_PW'] = 'editor';
|
|
||||||
$response = Director::test($url, $data, null, 'PUT');
|
|
||||||
$this->assertEquals($response->getStatusCode(), 200); // Success
|
|
||||||
|
|
||||||
unset($_SERVER['PHP_AUTH_USER']);
|
|
||||||
unset($_SERVER['PHP_AUTH_PW']);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function testGETRelationshipsXML() {
|
|
||||||
$author1 = $this->objFromFixture('RestfulServerTest_Author', 'author1');
|
|
||||||
$rating1 = $this->objFromFixture('RestfulServerTest_AuthorRating', 'rating1');
|
|
||||||
$rating2 = $this->objFromFixture('RestfulServerTest_AuthorRating', 'rating2');
|
|
||||||
|
|
||||||
// @todo should be set up by fixtures, doesn't work for some reason...
|
|
||||||
$author1->Ratings()->add($rating1);
|
|
||||||
$author1->Ratings()->add($rating2);
|
|
||||||
|
|
||||||
$url = "/api/v1/RestfulServerTest_Author/" . $author1->ID;
|
|
||||||
$response = Director::test($url, null, null, 'GET');
|
|
||||||
$this->assertEquals($response->getStatusCode(), 200);
|
|
||||||
|
|
||||||
$responseArr = Convert::xml2array($response->getBody());
|
|
||||||
$ratingsArr = $responseArr['Ratings']['RestfulServerTest_AuthorRating'];
|
|
||||||
$this->assertEquals(count($ratingsArr), 2);
|
|
||||||
$ratingIDs = array(
|
|
||||||
(int)$ratingsArr[0]['@attributes']['id'],
|
|
||||||
(int)$ratingsArr[1]['@attributes']['id']
|
|
||||||
);
|
|
||||||
$this->assertContains($rating1->ID, $ratingIDs);
|
|
||||||
$this->assertContains($rating2->ID, $ratingIDs);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function testGETManyManyRelationshipsXML() {
|
|
||||||
// author4 has related authors author2 and author3
|
|
||||||
$author2 = $this->objFromFixture('RestfulServerTest_Author', 'author2');
|
|
||||||
$author3 = $this->objFromFixture('RestfulServerTest_Author', 'author3');
|
|
||||||
$author4 = $this->objFromFixture('RestfulServerTest_Author', 'author4');
|
|
||||||
|
|
||||||
$url = "/api/v1/RestfulServerTest_Author/" . $author4->ID . '/RelatedAuthors';
|
|
||||||
$response = Director::test($url, null, null, 'GET');
|
|
||||||
$this->assertEquals(200, $response->getStatusCode());
|
|
||||||
$arr = Convert::xml2array($response->getBody());
|
|
||||||
$authorsArr = $arr['RestfulServerTest_Author'];
|
|
||||||
|
|
||||||
$this->assertEquals(count($authorsArr), 2);
|
|
||||||
$ratingIDs = array(
|
|
||||||
(int)$authorsArr[0]['ID'],
|
|
||||||
(int)$authorsArr[1]['ID']
|
|
||||||
);
|
|
||||||
$this->assertContains($author2->ID, $ratingIDs);
|
|
||||||
$this->assertContains($author3->ID, $ratingIDs);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function testPUTWithFormEncoded() {
|
$_SERVER['PHP_AUTH_USER'] = 'editor@test.com';
|
||||||
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
|
$_SERVER['PHP_AUTH_PW'] = 'editor';
|
||||||
|
$response = Director::test($url, $data, null, 'PUT');
|
||||||
$_SERVER['PHP_AUTH_USER'] = 'editor@test.com';
|
$this->assertEquals($response->getStatusCode(), 200); // Success
|
||||||
$_SERVER['PHP_AUTH_PW'] = 'editor';
|
|
||||||
|
|
||||||
$url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID;
|
|
||||||
$body = 'Name=Updated Comment&Comment=updated';
|
|
||||||
$headers = array(
|
|
||||||
'Content-Type' => 'application/x-www-form-urlencoded'
|
|
||||||
);
|
|
||||||
$response = Director::test($url, null, null, 'PUT', $body, $headers);
|
|
||||||
$this->assertEquals($response->getStatusCode(), 200); // Success
|
|
||||||
// Assumption: XML is default output
|
|
||||||
$responseArr = Convert::xml2array($response->getBody());
|
|
||||||
$this->assertEquals($responseArr['ID'], $comment1->ID);
|
|
||||||
$this->assertEquals($responseArr['Comment'], 'updated');
|
|
||||||
$this->assertEquals($responseArr['Name'], 'Updated Comment');
|
|
||||||
|
|
||||||
unset($_SERVER['PHP_AUTH_USER']);
|
|
||||||
unset($_SERVER['PHP_AUTH_PW']);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function testPOSTWithFormEncoded() {
|
|
||||||
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
|
|
||||||
|
|
||||||
$_SERVER['PHP_AUTH_USER'] = 'editor@test.com';
|
|
||||||
$_SERVER['PHP_AUTH_PW'] = 'editor';
|
|
||||||
|
|
||||||
$url = "/api/v1/RestfulServerTest_Comment";
|
|
||||||
$body = 'Name=New Comment&Comment=created';
|
|
||||||
$headers = array(
|
|
||||||
'Content-Type' => 'application/x-www-form-urlencoded'
|
|
||||||
);
|
|
||||||
$response = Director::test($url, null, null, 'POST', $body, $headers);
|
|
||||||
$this->assertEquals($response->getStatusCode(), 201); // Created
|
|
||||||
// Assumption: XML is default output
|
|
||||||
$responseArr = Convert::xml2array($response->getBody());
|
|
||||||
$this->assertTrue($responseArr['ID'] > 0);
|
|
||||||
$this->assertNotEquals($responseArr['ID'], $comment1->ID);
|
|
||||||
$this->assertEquals($responseArr['Comment'], 'created');
|
|
||||||
$this->assertEquals($responseArr['Name'], 'New Comment');
|
|
||||||
$this->assertEquals(
|
|
||||||
$response->getHeader('Location'),
|
|
||||||
Controller::join_links(Director::absoluteBaseURL(), $url, $responseArr['ID'])
|
|
||||||
);
|
|
||||||
|
|
||||||
unset($_SERVER['PHP_AUTH_USER']);
|
|
||||||
unset($_SERVER['PHP_AUTH_PW']);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function testPUTwithJSON() {
|
|
||||||
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
|
|
||||||
|
|
||||||
$_SERVER['PHP_AUTH_USER'] = 'editor@test.com';
|
|
||||||
$_SERVER['PHP_AUTH_PW'] = 'editor';
|
|
||||||
|
|
||||||
// by mimetype
|
|
||||||
$url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID;
|
|
||||||
$body = '{"Comment":"updated"}';
|
|
||||||
$response = Director::test($url, null, null, 'PUT', $body, array('Content-Type'=>'application/json'));
|
|
||||||
$this->assertEquals($response->getStatusCode(), 200); // Updated
|
|
||||||
$obj = Convert::json2obj($response->getBody());
|
|
||||||
$this->assertEquals($obj->ID, $comment1->ID);
|
|
||||||
$this->assertEquals($obj->Comment, 'updated');
|
|
||||||
|
|
||||||
// by extension
|
|
||||||
$url = sprintf("/api/v1/RestfulServerTest_Comment/%d.json", $comment1->ID);
|
|
||||||
$body = '{"Comment":"updated"}';
|
|
||||||
$response = Director::test($url, null, null, 'PUT', $body);
|
|
||||||
$this->assertEquals($response->getStatusCode(), 200); // Updated
|
|
||||||
$this->assertEquals(
|
|
||||||
$response->getHeader('Location'),
|
|
||||||
Controller::join_links(Director::absoluteBaseURL(), $url)
|
|
||||||
);
|
|
||||||
$obj = Convert::json2obj($response->getBody());
|
|
||||||
$this->assertEquals($obj->ID, $comment1->ID);
|
|
||||||
$this->assertEquals($obj->Comment, 'updated');
|
|
||||||
|
|
||||||
unset($_SERVER['PHP_AUTH_USER']);
|
|
||||||
unset($_SERVER['PHP_AUTH_PW']);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function testPUTwithXML() {
|
|
||||||
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
|
|
||||||
|
|
||||||
$_SERVER['PHP_AUTH_USER'] = 'editor@test.com';
|
|
||||||
$_SERVER['PHP_AUTH_PW'] = 'editor';
|
|
||||||
|
|
||||||
// by mimetype
|
|
||||||
$url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID;
|
|
||||||
$body = '<RestfulServerTest_Comment><Comment>updated</Comment></RestfulServerTest_Comment>';
|
|
||||||
$response = Director::test($url, null, null, 'PUT', $body, array('Content-Type'=>'text/xml'));
|
|
||||||
$this->assertEquals($response->getStatusCode(), 200); // Updated
|
|
||||||
$obj = Convert::xml2array($response->getBody());
|
|
||||||
$this->assertEquals($obj['ID'], $comment1->ID);
|
|
||||||
$this->assertEquals($obj['Comment'], 'updated');
|
|
||||||
|
|
||||||
// by extension
|
|
||||||
$url = sprintf("/api/v1/RestfulServerTest_Comment/%d.xml", $comment1->ID);
|
|
||||||
$body = '<RestfulServerTest_Comment><Comment>updated</Comment></RestfulServerTest_Comment>';
|
|
||||||
$response = Director::test($url, null, null, 'PUT', $body);
|
|
||||||
$this->assertEquals($response->getStatusCode(), 200); // Updated
|
|
||||||
$this->assertEquals(
|
|
||||||
$response->getHeader('Location'),
|
|
||||||
Controller::join_links(Director::absoluteBaseURL(), $url)
|
|
||||||
);
|
|
||||||
$obj = Convert::xml2array($response->getBody());
|
|
||||||
$this->assertEquals($obj['ID'], $comment1->ID);
|
|
||||||
$this->assertEquals($obj['Comment'], 'updated');
|
|
||||||
|
|
||||||
unset($_SERVER['PHP_AUTH_USER']);
|
|
||||||
unset($_SERVER['PHP_AUTH_PW']);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function testHTTPAcceptAndContentType() {
|
|
||||||
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
|
|
||||||
|
|
||||||
$url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID;
|
|
||||||
|
|
||||||
$headers = array('Accept' => 'application/json');
|
|
||||||
$response = Director::test($url, null, null, 'GET', null, $headers);
|
|
||||||
$this->assertEquals($response->getStatusCode(), 200); // Success
|
|
||||||
$obj = Convert::json2obj($response->getBody());
|
|
||||||
$this->assertEquals($obj->ID, $comment1->ID);
|
|
||||||
$this->assertEquals($response->getHeader('Content-Type'), 'application/json');
|
|
||||||
}
|
|
||||||
|
|
||||||
public function testNotFound(){
|
|
||||||
$_SERVER['PHP_AUTH_USER'] = 'user@test.com';
|
|
||||||
$_SERVER['PHP_AUTH_PW'] = 'user';
|
|
||||||
|
|
||||||
$url = "/api/v1/RestfulServerTest_Comment/99";
|
|
||||||
$response = Director::test($url, null, null, 'GET');
|
|
||||||
$this->assertEquals($response->getStatusCode(), 404);
|
|
||||||
|
|
||||||
unset($_SERVER['PHP_AUTH_USER']);
|
|
||||||
unset($_SERVER['PHP_AUTH_PW']);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function testMethodNotAllowed() {
|
|
||||||
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
|
|
||||||
|
|
||||||
$url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID;
|
|
||||||
$response = Director::test($url, null, null, 'UNKNOWNHTTPMETHOD');
|
|
||||||
$this->assertEquals($response->getStatusCode(), 405);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function testConflictOnExistingResourceWhenUsingPost() {
|
|
||||||
$rating1 = $this->objFromFixture('RestfulServerTest_AuthorRating', 'rating1');
|
|
||||||
|
|
||||||
$url = "/api/v1/RestfulServerTest_AuthorRating/" . $rating1->ID;
|
|
||||||
$response = Director::test($url, null, null, 'POST');
|
|
||||||
$this->assertEquals($response->getStatusCode(), 409);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function testUnsupportedMediaType() {
|
|
||||||
$_SERVER['PHP_AUTH_USER'] = 'user@test.com';
|
|
||||||
$_SERVER['PHP_AUTH_PW'] = 'user';
|
|
||||||
|
|
||||||
$url = "/api/v1/RestfulServerTest_Comment";
|
|
||||||
$data = "Comment||\/||updated"; // weird format
|
|
||||||
$headers = array('Content-Type' => 'text/weirdformat');
|
|
||||||
$response = Director::test($url, null, null, 'POST', $data, $headers);
|
|
||||||
$this->assertEquals($response->getStatusCode(), 415);
|
|
||||||
|
|
||||||
unset($_SERVER['PHP_AUTH_USER']);
|
|
||||||
unset($_SERVER['PHP_AUTH_PW']);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function testXMLValueFormatting() {
|
|
||||||
$rating1 = $this->objFromFixture('RestfulServerTest_AuthorRating','rating1');
|
|
||||||
|
|
||||||
$url = "/api/v1/RestfulServerTest_AuthorRating/" . $rating1->ID;
|
|
||||||
$response = Director::test($url, null, null, 'GET');
|
|
||||||
$this->assertContains('<ID>' . $rating1->ID . '</ID>', $response->getBody());
|
|
||||||
$this->assertContains('<Rating>' . $rating1->Rating . '</Rating>', $response->getBody());
|
|
||||||
}
|
|
||||||
|
|
||||||
public function testApiAccessFieldRestrictions() {
|
|
||||||
$author1 = $this->objFromFixture('RestfulServerTest_Author','author1');
|
|
||||||
$rating1 = $this->objFromFixture('RestfulServerTest_AuthorRating','rating1');
|
|
||||||
|
|
||||||
$url = "/api/v1/RestfulServerTest_AuthorRating/" . $rating1->ID;
|
|
||||||
$response = Director::test($url, null, null, 'GET');
|
|
||||||
$this->assertContains('<ID>', $response->getBody());
|
|
||||||
$this->assertContains('<Rating>', $response->getBody());
|
|
||||||
$this->assertContains('<Author', $response->getBody());
|
|
||||||
$this->assertNotContains('<SecretField>', $response->getBody());
|
|
||||||
$this->assertNotContains('<SecretRelation>', $response->getBody());
|
|
||||||
|
|
||||||
$url = "/api/v1/RestfulServerTest_AuthorRating/" . $rating1->ID . '?add_fields=SecretField,SecretRelation';
|
|
||||||
$response = Director::test($url, null, null, 'GET');
|
|
||||||
$this->assertNotContains('<SecretField>', $response->getBody(),
|
|
||||||
'"add_fields" URL parameter filters out disallowed fields from $api_access'
|
|
||||||
);
|
|
||||||
$this->assertNotContains('<SecretRelation>', $response->getBody(),
|
|
||||||
'"add_fields" URL parameter filters out disallowed relations from $api_access'
|
|
||||||
);
|
|
||||||
|
|
||||||
$url = "/api/v1/RestfulServerTest_AuthorRating/" . $rating1->ID . '?fields=SecretField,SecretRelation';
|
|
||||||
$response = Director::test($url, null, null, 'GET');
|
|
||||||
$this->assertNotContains('<SecretField>', $response->getBody(),
|
|
||||||
'"fields" URL parameter filters out disallowed fields from $api_access'
|
|
||||||
);
|
|
||||||
$this->assertNotContains('<SecretRelation>', $response->getBody(),
|
|
||||||
'"fields" URL parameter filters out disallowed relations from $api_access'
|
|
||||||
);
|
|
||||||
|
|
||||||
$url = "/api/v1/RestfulServerTest_Author/" . $author1->ID . '/Ratings';
|
|
||||||
$response = Director::test($url, null, null, 'GET');
|
|
||||||
$this->assertContains('<Rating>', $response->getBody(),
|
|
||||||
'Relation viewer shows fields allowed through $api_access'
|
|
||||||
);
|
|
||||||
$this->assertNotContains('<SecretField>', $response->getBody(),
|
|
||||||
'Relation viewer on has-many filters out disallowed fields from $api_access'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function testApiAccessRelationRestrictionsInline() {
|
|
||||||
$author1 = $this->objFromFixture('RestfulServerTest_Author','author1');
|
|
||||||
|
|
||||||
$url = "/api/v1/RestfulServerTest_Author/" . $author1->ID;
|
|
||||||
$response = Director::test($url, null, null, 'GET');
|
|
||||||
$this->assertNotContains('<RelatedPages', $response->getBody(), 'Restricts many-many with api_access=false');
|
|
||||||
$this->assertNotContains('<PublishedPages', $response->getBody(), 'Restricts has-many with api_access=false');
|
|
||||||
}
|
|
||||||
|
|
||||||
public function testApiAccessRelationRestrictionsOnEndpoint() {
|
|
||||||
$author1 = $this->objFromFixture('RestfulServerTest_Author','author1');
|
|
||||||
|
|
||||||
$url = "/api/v1/RestfulServerTest_Author/" . $author1->ID . "/ProfilePage";
|
|
||||||
$response = Director::test($url, null, null, 'GET');
|
|
||||||
$this->assertEquals(404, $response->getStatusCode(), 'Restricts has-one with api_access=false');
|
|
||||||
|
|
||||||
$url = "/api/v1/RestfulServerTest_Author/" . $author1->ID . "/RelatedPages";
|
|
||||||
$response = Director::test($url, null, null, 'GET');
|
|
||||||
$this->assertEquals(404, $response->getStatusCode(), 'Restricts many-many with api_access=false');
|
|
||||||
|
|
||||||
$url = "/api/v1/RestfulServerTest_Author/" . $author1->ID . "/PublishedPages";
|
|
||||||
$response = Director::test($url, null, null, 'GET');
|
|
||||||
$this->assertEquals(404, $response->getStatusCode(), 'Restricts has-many with api_access=false');
|
|
||||||
}
|
|
||||||
|
|
||||||
public function testApiAccessWithPUT() {
|
|
||||||
$rating1 = $this->objFromFixture('RestfulServerTest_AuthorRating','rating1');
|
|
||||||
|
|
||||||
$url = "/api/v1/RestfulServerTest_AuthorRating/" . $rating1->ID;
|
|
||||||
$data = array(
|
|
||||||
'Rating' => '42',
|
|
||||||
'WriteProtectedField' => 'haxx0red'
|
|
||||||
);
|
|
||||||
$response = Director::test($url, $data, null, 'PUT');
|
|
||||||
// Assumption: XML is default output
|
|
||||||
$responseArr = Convert::xml2array($response->getBody());
|
|
||||||
$this->assertEquals($responseArr['Rating'], 42);
|
|
||||||
$this->assertNotEquals($responseArr['WriteProtectedField'], 'haxx0red');
|
|
||||||
}
|
|
||||||
|
|
||||||
public function testJSONDataFormatter() {
|
unset($_SERVER['PHP_AUTH_USER']);
|
||||||
$formatter = new JSONDataFormatter();
|
unset($_SERVER['PHP_AUTH_PW']);
|
||||||
$editor = $this->objFromFixture('Member', 'editor');
|
}
|
||||||
$user = $this->objFromFixture('Member', 'user');
|
|
||||||
|
public function testGETRelationshipsXML()
|
||||||
|
{
|
||||||
|
$author1 = $this->objFromFixture('RestfulServerTest_Author', 'author1');
|
||||||
|
$rating1 = $this->objFromFixture('RestfulServerTest_AuthorRating', 'rating1');
|
||||||
|
$rating2 = $this->objFromFixture('RestfulServerTest_AuthorRating', 'rating2');
|
||||||
|
|
||||||
|
// @todo should be set up by fixtures, doesn't work for some reason...
|
||||||
|
$author1->Ratings()->add($rating1);
|
||||||
|
$author1->Ratings()->add($rating2);
|
||||||
|
|
||||||
|
$url = "/api/v1/RestfulServerTest_Author/" . $author1->ID;
|
||||||
|
$response = Director::test($url, null, null, 'GET');
|
||||||
|
$this->assertEquals($response->getStatusCode(), 200);
|
||||||
|
|
||||||
|
$responseArr = Convert::xml2array($response->getBody());
|
||||||
|
$ratingsArr = $responseArr['Ratings']['RestfulServerTest_AuthorRating'];
|
||||||
|
$this->assertEquals(count($ratingsArr), 2);
|
||||||
|
$ratingIDs = array(
|
||||||
|
(int)$ratingsArr[0]['@attributes']['id'],
|
||||||
|
(int)$ratingsArr[1]['@attributes']['id']
|
||||||
|
);
|
||||||
|
$this->assertContains($rating1->ID, $ratingIDs);
|
||||||
|
$this->assertContains($rating2->ID, $ratingIDs);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testGETManyManyRelationshipsXML()
|
||||||
|
{
|
||||||
|
// author4 has related authors author2 and author3
|
||||||
|
$author2 = $this->objFromFixture('RestfulServerTest_Author', 'author2');
|
||||||
|
$author3 = $this->objFromFixture('RestfulServerTest_Author', 'author3');
|
||||||
|
$author4 = $this->objFromFixture('RestfulServerTest_Author', 'author4');
|
||||||
|
|
||||||
|
$url = "/api/v1/RestfulServerTest_Author/" . $author4->ID . '/RelatedAuthors';
|
||||||
|
$response = Director::test($url, null, null, 'GET');
|
||||||
|
$this->assertEquals(200, $response->getStatusCode());
|
||||||
|
$arr = Convert::xml2array($response->getBody());
|
||||||
|
$authorsArr = $arr['RestfulServerTest_Author'];
|
||||||
|
|
||||||
|
$this->assertEquals(count($authorsArr), 2);
|
||||||
|
$ratingIDs = array(
|
||||||
|
(int)$authorsArr[0]['ID'],
|
||||||
|
(int)$authorsArr[1]['ID']
|
||||||
|
);
|
||||||
|
$this->assertContains($author2->ID, $ratingIDs);
|
||||||
|
$this->assertContains($author3->ID, $ratingIDs);
|
||||||
|
}
|
||||||
|
|
||||||
$this->assertEquals(
|
public function testPUTWithFormEncoded()
|
||||||
$formatter->convertDataObject($editor, array("FirstName", "Email")),
|
{
|
||||||
'{"FirstName":"Editor","Email":"editor@test.com"}',
|
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
|
||||||
"Correct JSON formatting with field subset");
|
|
||||||
|
$_SERVER['PHP_AUTH_USER'] = 'editor@test.com';
|
||||||
|
$_SERVER['PHP_AUTH_PW'] = 'editor';
|
||||||
|
|
||||||
|
$url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID;
|
||||||
|
$body = 'Name=Updated Comment&Comment=updated';
|
||||||
|
$headers = array(
|
||||||
|
'Content-Type' => 'application/x-www-form-urlencoded'
|
||||||
|
);
|
||||||
|
$response = Director::test($url, null, null, 'PUT', $body, $headers);
|
||||||
|
$this->assertEquals($response->getStatusCode(), 200); // Success
|
||||||
|
// Assumption: XML is default output
|
||||||
|
$responseArr = Convert::xml2array($response->getBody());
|
||||||
|
$this->assertEquals($responseArr['ID'], $comment1->ID);
|
||||||
|
$this->assertEquals($responseArr['Comment'], 'updated');
|
||||||
|
$this->assertEquals($responseArr['Name'], 'Updated Comment');
|
||||||
|
|
||||||
|
unset($_SERVER['PHP_AUTH_USER']);
|
||||||
|
unset($_SERVER['PHP_AUTH_PW']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testPOSTWithFormEncoded()
|
||||||
|
{
|
||||||
|
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
|
||||||
|
|
||||||
|
$_SERVER['PHP_AUTH_USER'] = 'editor@test.com';
|
||||||
|
$_SERVER['PHP_AUTH_PW'] = 'editor';
|
||||||
|
|
||||||
|
$url = "/api/v1/RestfulServerTest_Comment";
|
||||||
|
$body = 'Name=New Comment&Comment=created';
|
||||||
|
$headers = array(
|
||||||
|
'Content-Type' => 'application/x-www-form-urlencoded'
|
||||||
|
);
|
||||||
|
$response = Director::test($url, null, null, 'POST', $body, $headers);
|
||||||
|
$this->assertEquals($response->getStatusCode(), 201); // Created
|
||||||
|
// Assumption: XML is default output
|
||||||
|
$responseArr = Convert::xml2array($response->getBody());
|
||||||
|
$this->assertTrue($responseArr['ID'] > 0);
|
||||||
|
$this->assertNotEquals($responseArr['ID'], $comment1->ID);
|
||||||
|
$this->assertEquals($responseArr['Comment'], 'created');
|
||||||
|
$this->assertEquals($responseArr['Name'], 'New Comment');
|
||||||
|
$this->assertEquals(
|
||||||
|
$response->getHeader('Location'),
|
||||||
|
Controller::join_links(Director::absoluteBaseURL(), $url, $responseArr['ID'])
|
||||||
|
);
|
||||||
|
|
||||||
|
unset($_SERVER['PHP_AUTH_USER']);
|
||||||
|
unset($_SERVER['PHP_AUTH_PW']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testPUTwithJSON()
|
||||||
|
{
|
||||||
|
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
|
||||||
|
|
||||||
|
$_SERVER['PHP_AUTH_USER'] = 'editor@test.com';
|
||||||
|
$_SERVER['PHP_AUTH_PW'] = 'editor';
|
||||||
|
|
||||||
|
// by mimetype
|
||||||
|
$url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID;
|
||||||
|
$body = '{"Comment":"updated"}';
|
||||||
|
$response = Director::test($url, null, null, 'PUT', $body, array('Content-Type'=>'application/json'));
|
||||||
|
$this->assertEquals($response->getStatusCode(), 200); // Updated
|
||||||
|
$obj = Convert::json2obj($response->getBody());
|
||||||
|
$this->assertEquals($obj->ID, $comment1->ID);
|
||||||
|
$this->assertEquals($obj->Comment, 'updated');
|
||||||
|
|
||||||
|
// by extension
|
||||||
|
$url = sprintf("/api/v1/RestfulServerTest_Comment/%d.json", $comment1->ID);
|
||||||
|
$body = '{"Comment":"updated"}';
|
||||||
|
$response = Director::test($url, null, null, 'PUT', $body);
|
||||||
|
$this->assertEquals($response->getStatusCode(), 200); // Updated
|
||||||
|
$this->assertEquals(
|
||||||
|
$response->getHeader('Location'),
|
||||||
|
Controller::join_links(Director::absoluteBaseURL(), $url)
|
||||||
|
);
|
||||||
|
$obj = Convert::json2obj($response->getBody());
|
||||||
|
$this->assertEquals($obj->ID, $comment1->ID);
|
||||||
|
$this->assertEquals($obj->Comment, 'updated');
|
||||||
|
|
||||||
|
unset($_SERVER['PHP_AUTH_USER']);
|
||||||
|
unset($_SERVER['PHP_AUTH_PW']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testPUTwithXML()
|
||||||
|
{
|
||||||
|
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
|
||||||
|
|
||||||
|
$_SERVER['PHP_AUTH_USER'] = 'editor@test.com';
|
||||||
|
$_SERVER['PHP_AUTH_PW'] = 'editor';
|
||||||
|
|
||||||
|
// by mimetype
|
||||||
|
$url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID;
|
||||||
|
$body = '<RestfulServerTest_Comment><Comment>updated</Comment></RestfulServerTest_Comment>';
|
||||||
|
$response = Director::test($url, null, null, 'PUT', $body, array('Content-Type'=>'text/xml'));
|
||||||
|
$this->assertEquals($response->getStatusCode(), 200); // Updated
|
||||||
|
$obj = Convert::xml2array($response->getBody());
|
||||||
|
$this->assertEquals($obj['ID'], $comment1->ID);
|
||||||
|
$this->assertEquals($obj['Comment'], 'updated');
|
||||||
|
|
||||||
|
// by extension
|
||||||
|
$url = sprintf("/api/v1/RestfulServerTest_Comment/%d.xml", $comment1->ID);
|
||||||
|
$body = '<RestfulServerTest_Comment><Comment>updated</Comment></RestfulServerTest_Comment>';
|
||||||
|
$response = Director::test($url, null, null, 'PUT', $body);
|
||||||
|
$this->assertEquals($response->getStatusCode(), 200); // Updated
|
||||||
|
$this->assertEquals(
|
||||||
|
$response->getHeader('Location'),
|
||||||
|
Controller::join_links(Director::absoluteBaseURL(), $url)
|
||||||
|
);
|
||||||
|
$obj = Convert::xml2array($response->getBody());
|
||||||
|
$this->assertEquals($obj['ID'], $comment1->ID);
|
||||||
|
$this->assertEquals($obj['Comment'], 'updated');
|
||||||
|
|
||||||
|
unset($_SERVER['PHP_AUTH_USER']);
|
||||||
|
unset($_SERVER['PHP_AUTH_PW']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testHTTPAcceptAndContentType()
|
||||||
|
{
|
||||||
|
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
|
||||||
|
|
||||||
|
$url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID;
|
||||||
|
|
||||||
|
$headers = array('Accept' => 'application/json');
|
||||||
|
$response = Director::test($url, null, null, 'GET', null, $headers);
|
||||||
|
$this->assertEquals($response->getStatusCode(), 200); // Success
|
||||||
|
$obj = Convert::json2obj($response->getBody());
|
||||||
|
$this->assertEquals($obj->ID, $comment1->ID);
|
||||||
|
$this->assertEquals($response->getHeader('Content-Type'), 'application/json');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testNotFound()
|
||||||
|
{
|
||||||
|
$_SERVER['PHP_AUTH_USER'] = 'user@test.com';
|
||||||
|
$_SERVER['PHP_AUTH_PW'] = 'user';
|
||||||
|
|
||||||
|
$url = "/api/v1/RestfulServerTest_Comment/99";
|
||||||
|
$response = Director::test($url, null, null, 'GET');
|
||||||
|
$this->assertEquals($response->getStatusCode(), 404);
|
||||||
|
|
||||||
|
unset($_SERVER['PHP_AUTH_USER']);
|
||||||
|
unset($_SERVER['PHP_AUTH_PW']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testMethodNotAllowed()
|
||||||
|
{
|
||||||
|
$comment1 = $this->objFromFixture('RestfulServerTest_Comment', 'comment1');
|
||||||
|
|
||||||
|
$url = "/api/v1/RestfulServerTest_Comment/" . $comment1->ID;
|
||||||
|
$response = Director::test($url, null, null, 'UNKNOWNHTTPMETHOD');
|
||||||
|
$this->assertEquals($response->getStatusCode(), 405);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testConflictOnExistingResourceWhenUsingPost()
|
||||||
|
{
|
||||||
|
$rating1 = $this->objFromFixture('RestfulServerTest_AuthorRating', 'rating1');
|
||||||
|
|
||||||
|
$url = "/api/v1/RestfulServerTest_AuthorRating/" . $rating1->ID;
|
||||||
|
$response = Director::test($url, null, null, 'POST');
|
||||||
|
$this->assertEquals($response->getStatusCode(), 409);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testUnsupportedMediaType()
|
||||||
|
{
|
||||||
|
$_SERVER['PHP_AUTH_USER'] = 'user@test.com';
|
||||||
|
$_SERVER['PHP_AUTH_PW'] = 'user';
|
||||||
|
|
||||||
|
$url = "/api/v1/RestfulServerTest_Comment";
|
||||||
|
$data = "Comment||\/||updated"; // weird format
|
||||||
|
$headers = array('Content-Type' => 'text/weirdformat');
|
||||||
|
$response = Director::test($url, null, null, 'POST', $data, $headers);
|
||||||
|
$this->assertEquals($response->getStatusCode(), 415);
|
||||||
|
|
||||||
|
unset($_SERVER['PHP_AUTH_USER']);
|
||||||
|
unset($_SERVER['PHP_AUTH_PW']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testXMLValueFormatting()
|
||||||
|
{
|
||||||
|
$rating1 = $this->objFromFixture('RestfulServerTest_AuthorRating', 'rating1');
|
||||||
|
|
||||||
|
$url = "/api/v1/RestfulServerTest_AuthorRating/" . $rating1->ID;
|
||||||
|
$response = Director::test($url, null, null, 'GET');
|
||||||
|
$this->assertContains('<ID>' . $rating1->ID . '</ID>', $response->getBody());
|
||||||
|
$this->assertContains('<Rating>' . $rating1->Rating . '</Rating>', $response->getBody());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testApiAccessFieldRestrictions()
|
||||||
|
{
|
||||||
|
$author1 = $this->objFromFixture('RestfulServerTest_Author', 'author1');
|
||||||
|
$rating1 = $this->objFromFixture('RestfulServerTest_AuthorRating', 'rating1');
|
||||||
|
|
||||||
|
$url = "/api/v1/RestfulServerTest_AuthorRating/" . $rating1->ID;
|
||||||
|
$response = Director::test($url, null, null, 'GET');
|
||||||
|
$this->assertContains('<ID>', $response->getBody());
|
||||||
|
$this->assertContains('<Rating>', $response->getBody());
|
||||||
|
$this->assertContains('<Author', $response->getBody());
|
||||||
|
$this->assertNotContains('<SecretField>', $response->getBody());
|
||||||
|
$this->assertNotContains('<SecretRelation>', $response->getBody());
|
||||||
|
|
||||||
|
$url = "/api/v1/RestfulServerTest_AuthorRating/" . $rating1->ID . '?add_fields=SecretField,SecretRelation';
|
||||||
|
$response = Director::test($url, null, null, 'GET');
|
||||||
|
$this->assertNotContains('<SecretField>', $response->getBody(),
|
||||||
|
'"add_fields" URL parameter filters out disallowed fields from $api_access'
|
||||||
|
);
|
||||||
|
$this->assertNotContains('<SecretRelation>', $response->getBody(),
|
||||||
|
'"add_fields" URL parameter filters out disallowed relations from $api_access'
|
||||||
|
);
|
||||||
|
|
||||||
|
$url = "/api/v1/RestfulServerTest_AuthorRating/" . $rating1->ID . '?fields=SecretField,SecretRelation';
|
||||||
|
$response = Director::test($url, null, null, 'GET');
|
||||||
|
$this->assertNotContains('<SecretField>', $response->getBody(),
|
||||||
|
'"fields" URL parameter filters out disallowed fields from $api_access'
|
||||||
|
);
|
||||||
|
$this->assertNotContains('<SecretRelation>', $response->getBody(),
|
||||||
|
'"fields" URL parameter filters out disallowed relations from $api_access'
|
||||||
|
);
|
||||||
|
|
||||||
|
$url = "/api/v1/RestfulServerTest_Author/" . $author1->ID . '/Ratings';
|
||||||
|
$response = Director::test($url, null, null, 'GET');
|
||||||
|
$this->assertContains('<Rating>', $response->getBody(),
|
||||||
|
'Relation viewer shows fields allowed through $api_access'
|
||||||
|
);
|
||||||
|
$this->assertNotContains('<SecretField>', $response->getBody(),
|
||||||
|
'Relation viewer on has-many filters out disallowed fields from $api_access'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testApiAccessRelationRestrictionsInline()
|
||||||
|
{
|
||||||
|
$author1 = $this->objFromFixture('RestfulServerTest_Author', 'author1');
|
||||||
|
|
||||||
|
$url = "/api/v1/RestfulServerTest_Author/" . $author1->ID;
|
||||||
|
$response = Director::test($url, null, null, 'GET');
|
||||||
|
$this->assertNotContains('<RelatedPages', $response->getBody(), 'Restricts many-many with api_access=false');
|
||||||
|
$this->assertNotContains('<PublishedPages', $response->getBody(), 'Restricts has-many with api_access=false');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testApiAccessRelationRestrictionsOnEndpoint()
|
||||||
|
{
|
||||||
|
$author1 = $this->objFromFixture('RestfulServerTest_Author', 'author1');
|
||||||
|
|
||||||
|
$url = "/api/v1/RestfulServerTest_Author/" . $author1->ID . "/ProfilePage";
|
||||||
|
$response = Director::test($url, null, null, 'GET');
|
||||||
|
$this->assertEquals(404, $response->getStatusCode(), 'Restricts has-one with api_access=false');
|
||||||
|
|
||||||
|
$url = "/api/v1/RestfulServerTest_Author/" . $author1->ID . "/RelatedPages";
|
||||||
|
$response = Director::test($url, null, null, 'GET');
|
||||||
|
$this->assertEquals(404, $response->getStatusCode(), 'Restricts many-many with api_access=false');
|
||||||
|
|
||||||
|
$url = "/api/v1/RestfulServerTest_Author/" . $author1->ID . "/PublishedPages";
|
||||||
|
$response = Director::test($url, null, null, 'GET');
|
||||||
|
$this->assertEquals(404, $response->getStatusCode(), 'Restricts has-many with api_access=false');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testApiAccessWithPUT()
|
||||||
|
{
|
||||||
|
$rating1 = $this->objFromFixture('RestfulServerTest_AuthorRating', 'rating1');
|
||||||
|
|
||||||
|
$url = "/api/v1/RestfulServerTest_AuthorRating/" . $rating1->ID;
|
||||||
|
$data = array(
|
||||||
|
'Rating' => '42',
|
||||||
|
'WriteProtectedField' => 'haxx0red'
|
||||||
|
);
|
||||||
|
$response = Director::test($url, $data, null, 'PUT');
|
||||||
|
// Assumption: XML is default output
|
||||||
|
$responseArr = Convert::xml2array($response->getBody());
|
||||||
|
$this->assertEquals($responseArr['Rating'], 42);
|
||||||
|
$this->assertNotEquals($responseArr['WriteProtectedField'], 'haxx0red');
|
||||||
|
}
|
||||||
|
|
||||||
$set = DataObject::get(
|
public function testJSONDataFormatter()
|
||||||
"Member",
|
{
|
||||||
sprintf('"Member"."ID" IN (%s)', implode(',', array($editor->ID, $user->ID))),
|
$formatter = new JSONDataFormatter();
|
||||||
'"Email" ASC' // for sorting for postgres
|
$editor = $this->objFromFixture('Member', 'editor');
|
||||||
);
|
$user = $this->objFromFixture('Member', 'user');
|
||||||
$this->assertEquals(
|
|
||||||
$formatter->convertDataObjectSet($set, array("FirstName", "Email")),
|
|
||||||
'{"totalSize":null,"items":[{"FirstName":"Editor","Email":"editor@test.com"},' .
|
|
||||||
'{"FirstName":"User","Email":"user@test.com"}]}',
|
|
||||||
"Correct JSON formatting on a dataobjectset with field filter");
|
|
||||||
}
|
|
||||||
|
|
||||||
public function testApiAccessWithPOST() {
|
|
||||||
$url = "/api/v1/RestfulServerTest_AuthorRating";
|
|
||||||
$data = array(
|
|
||||||
'Rating' => '42',
|
|
||||||
'WriteProtectedField' => 'haxx0red'
|
|
||||||
);
|
|
||||||
$response = Director::test($url, $data, null, 'POST');
|
|
||||||
// Assumption: XML is default output
|
|
||||||
$responseArr = Convert::xml2array($response->getBody());
|
|
||||||
$this->assertEquals($responseArr['Rating'], 42);
|
|
||||||
$this->assertNotEquals($responseArr['WriteProtectedField'], 'haxx0red');
|
|
||||||
}
|
|
||||||
|
|
||||||
public function testCanViewRespectedInList() {
|
$this->assertEquals(
|
||||||
// Default content type
|
$formatter->convertDataObject($editor, array("FirstName", "Email")),
|
||||||
$url = "/api/v1/RestfulServerTest_SecretThing/";
|
'{"FirstName":"Editor","Email":"editor@test.com"}',
|
||||||
$response = Director::test($url, null, null, 'GET');
|
"Correct JSON formatting with field subset");
|
||||||
$this->assertEquals($response->getStatusCode(), 200);
|
|
||||||
$this->assertNotContains('Unspeakable', $response->getBody());
|
|
||||||
|
|
||||||
// JSON content type
|
$set = DataObject::get(
|
||||||
$url = "/api/v1/RestfulServerTest_SecretThing.json";
|
"Member",
|
||||||
$response = Director::test($url, null, null, 'GET');
|
sprintf('"Member"."ID" IN (%s)', implode(',', array($editor->ID, $user->ID))),
|
||||||
$this->assertEquals($response->getStatusCode(), 200);
|
'"Email" ASC' // for sorting for postgres
|
||||||
$this->assertNotContains('Unspeakable', $response->getBody());
|
);
|
||||||
|
$this->assertEquals(
|
||||||
|
$formatter->convertDataObjectSet($set, array("FirstName", "Email")),
|
||||||
|
'{"totalSize":null,"items":[{"FirstName":"Editor","Email":"editor@test.com"},' .
|
||||||
|
'{"FirstName":"User","Email":"user@test.com"}]}',
|
||||||
|
"Correct JSON formatting on a dataobjectset with field filter");
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testApiAccessWithPOST()
|
||||||
|
{
|
||||||
|
$url = "/api/v1/RestfulServerTest_AuthorRating";
|
||||||
|
$data = array(
|
||||||
|
'Rating' => '42',
|
||||||
|
'WriteProtectedField' => 'haxx0red'
|
||||||
|
);
|
||||||
|
$response = Director::test($url, $data, null, 'POST');
|
||||||
|
// Assumption: XML is default output
|
||||||
|
$responseArr = Convert::xml2array($response->getBody());
|
||||||
|
$this->assertEquals($responseArr['Rating'], 42);
|
||||||
|
$this->assertNotEquals($responseArr['WriteProtectedField'], 'haxx0red');
|
||||||
|
}
|
||||||
|
|
||||||
// With authentication
|
public function testCanViewRespectedInList()
|
||||||
$_SERVER['PHP_AUTH_USER'] = 'editor@test.com';
|
{
|
||||||
$_SERVER['PHP_AUTH_PW'] = 'editor';
|
// Default content type
|
||||||
$url = "/api/v1/RestfulServerTest_SecretThing/";
|
$url = "/api/v1/RestfulServerTest_SecretThing/";
|
||||||
$response = Director::test($url, null, null, 'GET');
|
$response = Director::test($url, null, null, 'GET');
|
||||||
$this->assertEquals($response->getStatusCode(), 200);
|
$this->assertEquals($response->getStatusCode(), 200);
|
||||||
$this->assertContains('Unspeakable', $response->getBody());
|
$this->assertNotContains('Unspeakable', $response->getBody());
|
||||||
unset($_SERVER['PHP_AUTH_USER']);
|
|
||||||
unset($_SERVER['PHP_AUTH_PW']);
|
// JSON content type
|
||||||
}
|
$url = "/api/v1/RestfulServerTest_SecretThing.json";
|
||||||
|
$response = Director::test($url, null, null, 'GET');
|
||||||
|
$this->assertEquals($response->getStatusCode(), 200);
|
||||||
|
$this->assertNotContains('Unspeakable', $response->getBody());
|
||||||
|
|
||||||
|
// With authentication
|
||||||
|
$_SERVER['PHP_AUTH_USER'] = 'editor@test.com';
|
||||||
|
$_SERVER['PHP_AUTH_PW'] = 'editor';
|
||||||
|
$url = "/api/v1/RestfulServerTest_SecretThing/";
|
||||||
|
$response = Director::test($url, null, null, 'GET');
|
||||||
|
$this->assertEquals($response->getStatusCode(), 200);
|
||||||
|
$this->assertContains('Unspeakable', $response->getBody());
|
||||||
|
unset($_SERVER['PHP_AUTH_USER']);
|
||||||
|
unset($_SERVER['PHP_AUTH_PW']);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -459,143 +481,153 @@ class RestfulServerTest extends SapphireTest {
|
|||||||
* but only "editors" can edit or delete them.
|
* but only "editors" can edit or delete them.
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
class RestfulServerTest_Comment extends DataObject implements PermissionProvider,TestOnly {
|
class RestfulServerTest_Comment extends DataObject implements PermissionProvider,TestOnly
|
||||||
|
{
|
||||||
static $api_access = true;
|
public static $api_access = true;
|
||||||
|
|
||||||
static $db = array(
|
public static $db = array(
|
||||||
"Name" => "Varchar(255)",
|
"Name" => "Varchar(255)",
|
||||||
"Comment" => "Text"
|
"Comment" => "Text"
|
||||||
);
|
);
|
||||||
|
|
||||||
static $has_one = array(
|
public static $has_one = array(
|
||||||
'Page' => 'RestfulServerTest_Page',
|
'Page' => 'RestfulServerTest_Page',
|
||||||
'Author' => 'RestfulServerTest_Author',
|
'Author' => 'RestfulServerTest_Author',
|
||||||
);
|
);
|
||||||
|
|
||||||
public function providePermissions(){
|
public function providePermissions()
|
||||||
return array(
|
{
|
||||||
'EDIT_Comment' => 'Edit Comment Objects',
|
return array(
|
||||||
'CREATE_Comment' => 'Create Comment Objects',
|
'EDIT_Comment' => 'Edit Comment Objects',
|
||||||
'DELETE_Comment' => 'Delete Comment Objects',
|
'CREATE_Comment' => 'Create Comment Objects',
|
||||||
);
|
'DELETE_Comment' => 'Delete Comment Objects',
|
||||||
}
|
);
|
||||||
|
}
|
||||||
public function canView($member = null) {
|
|
||||||
return true;
|
public function canView($member = null)
|
||||||
}
|
{
|
||||||
|
return true;
|
||||||
public function canEdit($member = null) {
|
}
|
||||||
return Permission::checkMember($member, 'EDIT_Comment');
|
|
||||||
}
|
public function canEdit($member = null)
|
||||||
|
{
|
||||||
public function canDelete($member = null) {
|
return Permission::checkMember($member, 'EDIT_Comment');
|
||||||
return Permission::checkMember($member, 'DELETE_Comment');
|
}
|
||||||
}
|
|
||||||
|
public function canDelete($member = null)
|
||||||
public function canCreate($member = null) {
|
{
|
||||||
return Permission::checkMember($member, 'CREATE_Comment');
|
return Permission::checkMember($member, 'DELETE_Comment');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function canCreate($member = null)
|
||||||
|
{
|
||||||
|
return Permission::checkMember($member, 'CREATE_Comment');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class RestfulServerTest_SecretThing extends DataObject implements TestOnly,PermissionProvider{
|
class RestfulServerTest_SecretThing extends DataObject implements TestOnly,PermissionProvider
|
||||||
static $api_access = true;
|
{
|
||||||
|
public static $api_access = true;
|
||||||
static $db = array(
|
|
||||||
"Name" => "Varchar(255)",
|
public static $db = array(
|
||||||
);
|
"Name" => "Varchar(255)",
|
||||||
|
);
|
||||||
public function canView($member = null) {
|
|
||||||
return Permission::checkMember($member, 'VIEW_SecretThing');
|
public function canView($member = null)
|
||||||
}
|
{
|
||||||
|
return Permission::checkMember($member, 'VIEW_SecretThing');
|
||||||
public function providePermissions(){
|
}
|
||||||
return array(
|
|
||||||
'VIEW_SecretThing' => 'View Secret Things',
|
public function providePermissions()
|
||||||
);
|
{
|
||||||
}
|
return array(
|
||||||
|
'VIEW_SecretThing' => 'View Secret Things',
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class RestfulServerTest_Page extends DataObject implements TestOnly {
|
class RestfulServerTest_Page extends DataObject implements TestOnly
|
||||||
|
{
|
||||||
static $api_access = false;
|
public static $api_access = false;
|
||||||
|
|
||||||
static $db = array(
|
public static $db = array(
|
||||||
'Title' => 'Text',
|
'Title' => 'Text',
|
||||||
'Content' => 'HTMLText',
|
'Content' => 'HTMLText',
|
||||||
);
|
);
|
||||||
|
|
||||||
static $has_one = array(
|
public static $has_one = array(
|
||||||
'Author' => 'RestfulServerTest_Author',
|
'Author' => 'RestfulServerTest_Author',
|
||||||
);
|
);
|
||||||
|
|
||||||
static $has_many = array(
|
public static $has_many = array(
|
||||||
'TestComments' => 'RestfulServerTest_Comment'
|
'TestComments' => 'RestfulServerTest_Comment'
|
||||||
);
|
);
|
||||||
|
|
||||||
static $belongs_many_many = array(
|
public static $belongs_many_many = array(
|
||||||
'RelatedAuthors' => 'RestfulServerTest_Author',
|
'RelatedAuthors' => 'RestfulServerTest_Author',
|
||||||
);
|
);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class RestfulServerTest_Author extends DataObject implements TestOnly {
|
class RestfulServerTest_Author extends DataObject implements TestOnly
|
||||||
|
{
|
||||||
static $api_access = true;
|
public static $api_access = true;
|
||||||
|
|
||||||
static $db = array(
|
public static $db = array(
|
||||||
'Name' => 'Text',
|
'Name' => 'Text',
|
||||||
);
|
);
|
||||||
|
|
||||||
static $many_many = array(
|
public static $many_many = array(
|
||||||
'RelatedPages' => 'RestfulServerTest_Page',
|
'RelatedPages' => 'RestfulServerTest_Page',
|
||||||
'RelatedAuthors' => 'RestfulServerTest_Author',
|
'RelatedAuthors' => 'RestfulServerTest_Author',
|
||||||
);
|
);
|
||||||
|
|
||||||
static $has_many = array(
|
public static $has_many = array(
|
||||||
'PublishedPages' => 'RestfulServerTest_Page',
|
'PublishedPages' => 'RestfulServerTest_Page',
|
||||||
'Ratings' => 'RestfulServerTest_AuthorRating',
|
'Ratings' => 'RestfulServerTest_AuthorRating',
|
||||||
);
|
);
|
||||||
|
|
||||||
public function canView($member = null) {
|
public function canView($member = null)
|
||||||
return true;
|
{
|
||||||
}
|
return true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class RestfulServerTest_AuthorRating extends DataObject implements TestOnly {
|
class RestfulServerTest_AuthorRating extends DataObject implements TestOnly
|
||||||
static $api_access = array(
|
{
|
||||||
'view' => array(
|
public static $api_access = array(
|
||||||
'Rating',
|
'view' => array(
|
||||||
'WriteProtectedField',
|
'Rating',
|
||||||
'Author'
|
'WriteProtectedField',
|
||||||
),
|
'Author'
|
||||||
'edit' => array(
|
),
|
||||||
'Rating'
|
'edit' => array(
|
||||||
)
|
'Rating'
|
||||||
);
|
)
|
||||||
|
);
|
||||||
static $db = array(
|
|
||||||
'Rating' => 'Int',
|
public static $db = array(
|
||||||
'SecretField' => 'Text',
|
'Rating' => 'Int',
|
||||||
'WriteProtectedField' => 'Text',
|
'SecretField' => 'Text',
|
||||||
);
|
'WriteProtectedField' => 'Text',
|
||||||
|
);
|
||||||
static $has_one = array(
|
|
||||||
'Author' => 'RestfulServerTest_Author',
|
public static $has_one = array(
|
||||||
'SecretRelation' => 'RestfulServerTest_Author',
|
'Author' => 'RestfulServerTest_Author',
|
||||||
);
|
'SecretRelation' => 'RestfulServerTest_Author',
|
||||||
|
);
|
||||||
public function canView($member = null) {
|
|
||||||
return true;
|
public function canView($member = null)
|
||||||
}
|
{
|
||||||
|
return true;
|
||||||
public function canEdit($member = null) {
|
}
|
||||||
return true;
|
|
||||||
}
|
public function canEdit($member = null)
|
||||||
|
{
|
||||||
public function canCreate($member = null) {
|
return true;
|
||||||
return true;
|
}
|
||||||
}
|
|
||||||
|
public function canCreate($member = null)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user