用于删除和更新的RestFul API获取403禁止的Codeigniter 4

nbewdwxp  于 2022-12-07  发布在  其他
关注(0)|答案(3)|浏览(152)

记住这是 codeigniter 4号。
我在这里需要帮助。我正在学习如何在codeigniter 4中实现RestFul API。下面是我的详细代码。

路线:

$routes->resource('ApiManageMaintenance', ['controller' =>'App\Controllers\ApiData\ApiManageMaintenance']); // get, put, create, delete

ApiManageMaintenance.php文件夹:

<?php
 
namespace App\Controllers\ApiData;
use App\Controllers\BaseController;
use CodeIgniter\RESTful\ResourceController;

class ApiManageMaintenance extends ResourceController
{    

    function __construct()
    {       

        $model = new Dennis_setting_model();    
            

    }
    

    // equal to get    
    public function index()
    {          
        $Medoo = new \App\Models\Dennis_medoo_model();      
        $result = $Medoo->SelectAllMaintenance();   

        $response = [
            'status'   => 200,
            'error'    => null,
            'messages' => 'Pull Data Successfull',
            'data'     => $result
        ];            
        
        return json_encode($response); 
        
    }
    
        
    // equal to post
    public function create() {
        $version = $this->request->getVar('version');
        $reason = $this->request->getVar('reason');     

        if ($version == "" || $reason == "") {
            $response = [
                'status'   => 102,
                'error'    => 'Data Error',
                'messages' => 'Data Not Valid',
                'data' => null 
            ];         
            
            return json_encode($response);            
        }

        $array = array ('version' => $version,
                  'reason' => $reason
        );

        $Medoo = new \App\Models\Dennis_medoo_model();      
        $Medoo->InsertNewMaintenance($array);
        
        $response = [
            'status'   => 200,
            'error'    => null,
            'messages' => 'Create New Maintenance Successfull',
            'data'     => null
        ];            
        
        return json_encode($response);        

    }

    // equal to get
    public function show($id = null) {

        $Medoo = new \App\Models\Dennis_medoo_model();      
        $result = $Medoo->SelectAllMaintenance();   

        $response = [
            'status'   => 200,
            'error'    => null,
            'messages' => 'Pull Data Successfull',
            'data'     => $result
        ];            
        
        return json_encode($response); 
    }

    // equal to put    
    public function update($id = null) {
        $data = $this->request->getRawInput();
        $data['id'] = $id;

        $response = [
            'status'   => 200,
            'error'    => null,
            'messages' => 'Update Data Successfull',
            'data'     => null
        ];            
        
        return json_encode($response);
    }
    

    // equal to delete
    public function delete($id = null) {        
        $Medoo = new \App\Models\Dennis_medoo_model();
        $Medoo->DeleteMaintenance($id);
        $response = [
            'status'   => 200,
            'error'    => null,
            'messages' => 'Delete Data Successfull',
            'data'     => null
        ];            
        
        return json_encode($response);
        
    }

}

配置过滤器.php

<?php namespace Config;

use CodeIgniter\Config\BaseConfig;

class Filters extends BaseConfig
{
    // Makes reading things below nicer,
    // and simpler to change out script that's used.
    public $aliases = [
        'csrf'     => \CodeIgniter\Filters\CSRF::class,
        'toolbar'  => \CodeIgniter\Filters\DebugToolbar::class,
        'honeypot' => \CodeIgniter\Filters\Honeypot::class,
        'auth' => \App\Filters\Auth::class,
        'authaccess' => \App\Filters\AuthAccess::class
    ];

    // Always applied before every request
    public $globals = [
        'before' => [
            //'honeypot'
            'csrf' => ['except' => [
                    'api/ApiManageMaintenance/delete'
                ]
            ]           
        ],
        'after'  => [
            'toolbar',
            //'honeypot'
        ],
    ];

    // Works on all of a particular HTTP method
    // (GET, POST, etc) as BEFORE filters only
    //     like: 'post' => ['CSRF', 'throttle'],
    public $methods = [
        
    ];

    // List filter aliases and any before/after uri patterns
    // that they should run on, like:
    //    'isLoggedIn' => ['before' => ['account/*', 'profiles/*']],
    public $filters = [];
}

注意:我使用的是第三方数据库库=〉Medoo,所以忽略它。由于某些原因,我没有在codeigniter中使用内置的框架数据库查询,因为Medoo对我来说看起来很轻很简单。
则For正在工作:

403 -禁止访问:访问被拒绝。您无权使用您提供的凭据查看此目录或页面。
我还在config =〉filter.php中添加了例外

public $globals = [
            'before' => [
                //'honeypot'
                'csrf' => ['except' => [
                        'api/ApiManageMaintenance/delete'
                    ]
                ]           
            ],
    
        ];

我不是很理解config filter.php,但看起来这行代码将使api删除工作。

'csrf' => ['except' => [
                'api/ApiManageMaintenance/delete'
            ]
    ]

"现在我的问题是"
1.是否有任何特定的设置或配置,我错过或我需要做的Restfu API,使API Restfull工作?
任何来自这个社区的帮助都是非常感谢的。

dxxyhpgq

dxxyhpgq1#

答案:
在Codeigniter 4中的文件夹Filters中创建文件筛选器

输入此代码:

<?php

namespace App\Filters;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
use Codeigniter\API\ResponseTrait;
use Config\Services;
use Exception;

class FilterBasicAuth implements FilterInterface
{

    use ResponseTrait;
    public function before(RequestInterface $request, $arguments = null)
    {               
        
        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization");
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
        
        $method = $_SERVER['REQUEST_METHOD'];
        if ($method == "OPTIONS") {
            die();
        }    
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        // Do something here
    }
}

主要代码为:

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");

        $method = $_SERVER['REQUEST_METHOD'];
        if ($method == "OPTIONS") {
            die();
        }

然后在configFilters.php
放置和添加别名此代码:

public $aliases = [             
        'cors'     => \App\Filters\FilterBasicAuth::class,
    ];

备注:

我使用过滤器名称FilterBasicAuth。您可以更改为您的名称,并确保在别名中也更改名称。
仅此而已。

kqlmhetl

kqlmhetl2#

好吧,最好的方法是implelemnet restfull apici4
API ctl

<?php

namespace Modules\Shared\Controllers;

/**
 * Class BaseController
 *
 * BaseController provides a convenient place for loading components
 * and performing functions that are needed by all your controllers.
 * Extend this class in any new controllers:
 *     class Home extends BaseController
 *
 * For security be sure to declare any new methods as protected or private.
 *
 * @package CodeIgniter
 */

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\RESTful\ResourceController;
use Modules\Auth\Config\Services;
use Myth\Auth\AuthTrait;
use Psr\Log\LoggerInterface;
use  Modules\Shared\Interfaces\UrlAggregationInterface;
use  Modules\Shared\Libraries\UrlAggregation;

class ApiController extends ResourceController
{
    use AuthTrait;

    protected $format = "";
    public object $userObject;
    public UrlAggregationInterface $urlAggregation;

    /**
     * An array of helpers to be loaded automatically upon
     * class instantiation. These helpers will be available
     * to all other controllers that extend BaseController.
     *
     * @var array
     */
    protected $helpers = [
        'cookie',
        'url',
        'from',
        'filesystem',
        'text',
        'shared'
    ];

    /**
     * Constructor.
     *
     * @param RequestInterface $request
     * @param ResponseInterface $response
     * @param LoggerInterface $logger
     */

    /**
     * @var string
     * Holds the session instance
     */
    protected $session;

    public function __construct()
    {

        $this->userObject = (object)[];
    }

    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        // Do Not Edit This Line
        parent::initController($request, $response, $logger);

        $this->urlAggregation = new UrlAggregation($request);

        $requestWithUser = Services::requestWithUser();
        $this->userObject = $requestWithUser->getUser();

    }

}

组ctl

<?php namespace Modules\Auth\Controllers;

use Modules\Auth\Config\Services;
use Modules\Auth\Entities\GroupEntity;
use CodeIgniter\HTTP\ResponseInterface;
use Modules\Shared\Controllers\ApiController;

class  Group extends ApiController
{
    /**
     * index function
     * @method : GET
     */
    public function index()
    {

        $groupEntity = new GroupEntity();

        $this->urlAggregation->dataMap($groupEntity->getDataMap());

        $groupService = Services::groupService();
        $findAllData = $groupService->index($this->urlAggregation);

        return $this->respond([
            'data' => $findAllData['data'],
            'pager' => $findAllData['pager']
        ], ResponseInterface::HTTP_OK, lang('Shared.api.receive'));

    }

    /**
     * show function
     * @method : GET with params ID
     */
    public function show($id = null)
    {
        $groupService = Services::groupService();
        $findOneData = $groupService->show($id);

        return $this->respond([
            'data' => $findOneData['data'],
            'pager' => $findOneData['pager']
        ], ResponseInterface::HTTP_OK, lang('Shared.api.receive'));

    }

    public function create()
    {

        $rules = [
            'name' => 'required|min_length[3]|max_length[255]|is_unique[auth_groups.name]',
            'description' => 'required|min_length[3]|max_length[255]',
        ];

        if (!$this->validate($rules)) {

            return $this->respond([
                'error' => $this->validator->getErrors(),
                
            ], ResponseInterface::HTTP_NOT_ACCEPTABLE, lang('Shared.api.validation'));

        }

        $groupEntity = new GroupEntity((array)$this->request->getVar());

        $groupService = Services::groupService();
        $groupService->create($groupEntity);

        return $this->respond([
            'data' => ''
        ], ResponseInterface::HTTP_CREATED, lang('Shared.api.save'));

    }

    /**
     * update function
     * @method : PUT or PATCH
     */
    public function update($id = null)
    {

        //get request from Vue Js

        //get request from Vue Js
        $json = $this->request->getJSON();
        if (!isset($id)) {
            $id = $json->id;
        }

        $rules = [
            'name' => 'if_exist|required|min_length[3]|max_length[255]',
            'description' => 'required|min_length[3]|max_length[255]',
        ];

        if (!$this->validate($rules)) {
            return $this->respond([
                'error' => $this->validator->getErrors(),
                
            ], ResponseInterface::HTTP_NOT_ACCEPTABLE, lang('Shared.api.validation'));

        }

        $groupEntity = new GroupEntity((array)$this->request->getVar());

        $groupService = Services::groupService();
        $groupService->update($id, $groupEntity);

        return $this->respond([
        ], ResponseInterface::HTTP_OK, lang('Shared.api.update'));

    }

    /**
     * edit function
     * @method : DELETE with params ID
     */
    public function delete($id = null)
    {

        $groupService = Services::groupService();
        $groupService->delete($id);

        return $this->respond([
        ], ResponseInterface::HTTP_OK, lang('Shared.api.remove'));

    }

}

实体

<?php namespace Modules\Auth\Entities;

use \CodeIgniter\Entity;
use CodeIgniter\I18n\Time;

class  GroupEntity extends Entity
{

   protected $id;
   protected $name;
   protected $description;

    //check type of data

//    protected $casts = ['
//    is_flag' => 'boolean'];

    protected $attributes = [
        'id' => null,
        'name' => null,
        'description' => null,

    ];
    protected $datamap = [
    ];

    protected $dates = [];

    protected $casts = [];

    protected $permissions = [];

    protected $roles = [];



}

服务负责人

<?php

namespace Modules\Auth\Services;

use Modules\Auth\Entities\GroupEntity;
use CodeIgniter\HTTP\ResponseInterface;
use Modules\Shared\Interfaces\UrlAggregationInterface;
use Modules\Shared\Libraries\MainService;
use Myth\Auth\Authorization\GroupModel;

class GroupService extends  MainService
{
    private  GroupModel $model;

    public function __construct()
    {
        $this->model = new  GroupModel();
    }

    /**
     * index function
     * @method : GET
     * @param UrlAggregationInterface $urlAggregation
     * @return array
     */
    public function index(UrlAggregationInterface $urlAggregation)
    {
        $pipeLine = $urlAggregation->decodeQueryParam()->getPipeLine();

        return $this->model->aggregatePagination($pipeLine);

    }

    /**
     * show function
     * @method : GET with params ID
     * @param $id
     * @return array
     */
    public function show($id)
    {
        if (is_null($id)) $this->httpException(lang('Shared.api.validation'), ResponseInterface::HTTP_NOT_FOUND);

        $result = $this->model->where('id', $id)->paginate(1, 'default');

        if (is_null($result)) $this->httpException(lang('Shared.api.exist'), ResponseInterface::HTTP_NOT_FOUND);

        $data = [
            'data' => $result,
            'pager' => $this->model->pager->getDetails()
        ];
        return $data;

    }

    /**
     * create function
     * @method : POST
     * @param GroupEntity $entity
     * @throws \ReflectionException
     */
    public function create(GroupEntity $entity)
    {
        if (is_null($entity)) $this->httpException(lang('Shared.api.validation'), ResponseInterface::HTTP_NOT_FOUND);

        if (!$this->model->save($entity)) {
            helper('shared');
            $this->httpException(lang('Shared.api.reject'), ResponseInterface::HTTP_BAD_REQUEST,serializeMessages($this->model->errors()));

        }


    }

    /**
     * update function
     * @method : PUT or PATCH
     * @param $id
     * @param GroupEntity $entity
     * @throws \ReflectionException
     */
    public function update($id , GroupEntity $entity)
    {
        if (is_null($entity)) $this->httpException(lang('Shared.api.validation'), ResponseInterface::HTTP_NOT_FOUND);


        if (!$this->model->update($id, $entity)) {

            helper('shared');
            $this->httpException(lang('Shared.api.reject'), ResponseInterface::HTTP_BAD_REQUEST,serializeMessages($this->model->errors()));

        }

    }

    /**
     * edit function
     * @method : DELETE with params ID
     * @param $id
     */
    public function delete($id )
    {

        $deleteById = $this->model->find($id);

        if (is_null($deleteById)) $this->httpException(lang('Shared.api.exist'), ResponseInterface::HTTP_NOT_FOUND);

        $this->model->delete($id);

    }
    public function getInsertId()
    {
        return $this->model->getInsertID();
    }
}
jq6vz3qz

jq6vz3qz3#

这是第2部分

<?php namespace Modules\Auth\Config;

use CodeIgniter\HTTP\UserAgent;
use Config\App;
use Config\Services as AppServices;
use Config\Services as BaseService;
use Modules\Auth\Libraries\RequestWithUser;
use Modules\Auth\Services\AuthService;
use Modules\Auth\Services\GroupsPermissionService;
use Modules\Auth\Services\PermissionService;
use Modules\Auth\Services\RoleRouteService;
use Modules\Auth\Services\GroupService;
use Modules\Auth\Services\UsersPermissionService;

class Services extends BaseService
{
    //--------------------------------------------------------------------

    /**
     * The Request class models an HTTP request.
     *
     * @param App|null $config
     * @param boolean $getShared
     *
     * @return RequestWithUser
     */
    public static function requestWithUser(App $config = null, bool $getShared = true)
    {
        if ($getShared) {
            return static::getSharedInstance('requestWithUser', $config);
        }

        $config = $config ?? config('App');;
        return new RequestWithUser(
            $config,
            AppServices::uri(),
            'php://input',
            new UserAgent()
        );
    }

    //--------------------------------------------------------------------

    public static function roleRoute($getShared = true)
    {
        if ($getShared) {
            return static::getSharedInstance('roleRoute');
        }

        return new RoleRouteService();
    }
//--------------------------------------------------------------------

    public static function authService($getShared = false)
    {
        if (!$getShared) {
            return new AuthService();
        }
        return static::getSharedInstance('authService');

    }
//--------------------------------------------------------------------

    public static function groupService($getShared = false)
    {
        if (!$getShared) {

            return new GroupService();
        }

        return static::getSharedInstance('groupService');
    }
//--------------------------------------------------------------------

    public static function permissionService($getShared = false)
    {
        if (!$getShared) {

            return new PermissionService();
        }

        return static::getSharedInstance('permissionService');
    }
//--------------------------------------------------------------------

    public static function groupsPermissionService($getShared = false)
    {
        if (!$getShared) {

            return new GroupsPermissionService();
        }

        return static::getSharedInstance('groupsPermissionService');
    }
//--------------------------------------------------------------------

    public static function userPermissionService($getShared = false)
    {
        if (!$getShared) {

            return new UsersPermissionService();
        }

        return static::getSharedInstance('usersPermissionService');
    }

//--------------------------------------------------------------------

}

模型化
第一次

相关问题