Welcome Guest, Not a member yet? Register   Sign In
restrict access to methods or url by profile
#1
Question 

Hi,
The question is the following, codeginiter 4.1.2 has some library which facilitates the restriction to a url method by profile or user.

Since I am developing a site which will have different profiles and these will be able to access different url methods.

Using the filters in the routes would not be an option.

Thanks,
Reply
#2

Yes you can do this with filters. Look at Myth:Auth's code on GitHub for an example.

PHP Code:
$routes->get('admin/users''UserController::index', ['filter' => 'permission:manage-user'])
$routes->get('admin/users''UserController::index', ['filter' => 'role:admin,superadmin']) 

Or if  you really don't want to use filters, look at its helper functions, like has_permission() or in_group()...
CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
/*** NO support in private message - Use the forum! ***/
Reply
#3

premission base on http resuqst  get post put delete

PHP Code:
<?php namespace CoreAuth\Filters;

use 
CoreAuth\Enums\FilterErrorType;
use 
CodeIgniter\HTTP\RequestInterface;
use 
CodeIgniter\HTTP\Response;
use 
CodeIgniter\HTTP\ResponseInterface;
use 
CodeIgniter\Filters\FilterInterface;


class 
AuthFilter implements FilterInterface
{
    public function after(RequestInterface $requestResponseInterface $response$arguments null)
    {

    }

    public function before(RequestInterface $request$arguments null)
    {

        $ruleRoute = \CoreAuth\Config\Services::ruleRoute();

        if ($ruleRoute->ignoreRoute()) {
            return;
        }
        $response = \CodeIgniter\Config\Services::response();

        $uri uri_string();

        $authenticate = \Myth\Auth\Config\Services::authentication();
        $authorize = \Myth\Auth\Config\Services::authorization();

        $explode explode('/'$uri);

        $controller strtolower($explode[1]);

        $controllerRule $ruleRoute->getRuleAccess(explode('/'$uri)[1]);

        $isGroup false;
        $isAccess false;
        $counterPermission 0;
        if (!function_exists('logged_in')) {
            //  helper('Myth\Auth\Helpers\Auth');
            helper('auth');
        }

        $current = (string)current_url(true)
            ->setHost('')
            ->setScheme('')
            ->stripQuery('token');

        // Make sure this isn't already a login route
        if (in_array((string)$current, [route_to('login'), route_to('forgot'), route_to('reset-password'), route_to('register'), route_to('activate-account')])) {

            return;
        }

        // if no user is logged in then send to the login form

        if (!$authenticate->check()) {
            return $response->setJSON(['success' => false,
                'type' => FilterErrorType::Login,
                'error' => lang('Authenticate.filter.login')])->setContentType('application/json')
                ->setStatusCode(Response::HTTP_UNAUTHORIZEDlang('Authenticate.filter.login'));
        }


        if (empty($controllerRule)) {

            return;
        }

        // Check each requested permission
        foreach ($controllerRule as $group) {
            if ($authorize->inGroup($group$authenticate->id())) {
                $isGroup true;
                // return;
            }
        }


        $method strtolower($_SERVER['REQUEST_METHOD']);
        // permission by http request post put delete
        $permissions permissionMethod($method);

        if ($isGroup == true && !empty($permissions)) {

            foreach ($permissions as $item) {

                if ($authorize->permission($controller "" $item)) {
                    $counterPermission++;
                    if ($authorize->hasPermission($controller "" $item$authenticate->id())) {
                        $isAccess true;
                        break;
                    }
                }

            }
        }
        // it get request  dont need any permission
        //or dont have permission in database for http request
        if (empty($permissions) || $counterPermission == 0) {


            $isAccess true;
        }


        if ($isGroup == true and $isAccess == true) {
            return;
        }


        if ($authenticate->silent()) {
            $redirectURL session('redirect_url') ?? '/';
            unset($_SESSION['redirect_url']);
        }

        return $response->setJSON(['success' => false,
            'type' => FilterErrorType::Permission,
            'error' => lang('Auth.notEnoughPrivilege')])->setContentType('application/json')
            ->setStatusCode(Response::HTTP_UNAUTHORIZEDlang('Auth.notEnoughPrivilege'));


    }




hepler/auth_helper
PHP Code:
<?php


use Myth\Auth\Config\Services;

if (!
function_exists('logged_in')) {
    /**
    * Checks to see if the user is logged in.
    *
    * @return bool
    */
    function logged_in()
    {
        return Services::authentication()->check();
    }
}

if (!
function_exists('user')) {
    /**
    * Returns the User instance for the current logged in user.
    *
    * @return \Myth\Auth\Entities\User|null
    */
    function user()
    {
        $authenticate Services::authentication();
        $authenticate->check();
        return $authenticate->user();
    }
}

if (!
function_exists('user_id')) {
    /**
    * Returns the User ID for the current logged in user.
    *
    * @return int|null
    */
    function user_id()
    {
        $authenticate Services::authentication();
        $authenticate->check();
        return $authenticate->id();
    }
}

if (!
function_exists('in_groups')) {
    /**
    * Ensures that the current user is in at least one of the passed in
    * groups. The groups can be passed in as either ID's or group names.
    * You can pass either a single item or an array of items.
    *
    * Example:
    *  in_groups([1, 2, 3]);
    *  in_groups(14);
    *  in_groups('admins');
    *  in_groups( ['admins', 'moderators'] );
    *
    * @param mixed $groups
    *
    * @return bool
    */
    function in_groups($groups): bool
    
{
        $authenticate Services::authentication();
        $authorize Services::authorization();

        if ($authenticate->check()) {
            return $authorize->inGroup($groups$authenticate->id());
        }

        return false;
    }
}

if (!
function_exists('has_permission')) {
    /**
    * Ensures that the current user has the passed in permission.
    * The permission can be passed in either as an ID or name.
    *
    * @param int|string $permission
    *
    * @return bool
    */
    function has_permission($permission): bool
    
{
        $authenticate Services::authentication();
        $authorize Services::authorization();

        if ($authenticate->check()) {
            return $authorize->hasPermission($permission$authenticate->id()) ?? false;
        }

        return false;
    }


}


if (!
function_exists('permissionMethod')) {
    /**
    * return permission by http request put post delete
    * @param string $method
    *
    * @return array
    */
    function permissionMethod(string $method): array
    {

        switch ($method) {

            case "post":
                return ["-post-put-delete""-post-put""-post-delete""-post"];
            case "put":
                return ["-post-put-delete""-post-put""-put-delete""-put"];
            case "delete":
                return ["-post-put-delete""-put-delete""-post-delete""-delete"];
            default:
                return [];
        }


    }



Enlightenment  Is  Freedom
Reply




Theme © iAndrew 2016 - Forum software by © MyBB