php-crud-api
php-crud-api copied to clipboard
Public POST method on a single table
Hi. How can I allow guest users (so with no auth) to make a POST call to create a record on a specific table? I'd like to allow this only on this table, leaving all others configuration parameters as already set, so protected by authentication.
The easiest seems to be to configure a separate api.php (maybe rename it to guest.php) to provide access to that single table.
Use the api.include.php to minimize redundant files. Then have an api.php to contain config for accessing the tables securely /with authn and a guest.php to contain config for accessing the single table without authn.
├── project
├── api.include.php
├── api.php
├── guest.php
@chattago2002 any update?
@chattago2002 any update?
I'm going to have a test in short time, also if could be useful to have a more detailed example. I'm a newbie 😊
a more detailed example
Assumptions:
- You already know how to setup the api with authorization.
- You setup your project as suggested, i.e., use api.include.php.
To configue an api targeting only one table and allowing only POST (create) operation, you can setup guest.php as follows:
<?php
namespace Tqdev\PhpCrudApi;
use Tqdev\PhpCrudApi\Api;
use Tqdev\PhpCrudApi\Config\Config;
use Tqdev\PhpCrudApi\RequestFactory;
use Tqdev\PhpCrudApi\ResponseUtils;
require_once 'api.include.php';
$config = new Config([
'driver' => 'sqlite',
'address' => 'demodata.db',
'middlewares'=>'authorization',
'authorization.tableHandler' => function ($operation, $tableName) {
$allowed_operations = ['create'];// allow only POST operation
$allowed_tables = ['NameOfTable']; // name of your table
return (in_array($operation,$allowed_operations) && in_array($tableName,$allowed_tables));
},
"cacheType"=>"NoCache",
"debug"=>true
]);
$request = RequestFactory::fromGlobals();
$api = new Api($config);
$response = $api->handle($request);
ResponseUtils::output($response);
//filename: guest.php
The key parts are the contents of the authorization.tableHandler, particularly the $allowed_operations which will be an array of allowed operations (see documentation on authorizing operations ) as well as the $allowed_tables which will be an array of names of tables that you want to be accessible.
Perfect. Thank you, it seems to work fine as expected.
And what about if I would like to have similar behaviour with a custom controller? I have 3 custom controllers, 2 needs to be authorized but I'd like to have the other as public endpoint.
I have 3 custom controllers, 2 needs to be authorized but I'd like to have the other as public endpoint.
Same applies:
The easiest seems to be to configure a separate api.php
Closing for now.