2

I'm looking to add in some modifications to my application so that on my MY_Controller it checks to see if the user is allowed to access the current page or not. This is an example of one of my controllers. All of mine have a read, edit, create, delete functions. I just need to figure out how to globally set up permissions to allow or disallow a user from accessing it the function other than doing if statements on every function.

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Content_pages extends MY_Controller
{  
    /**
     * Account::__construct()
     * 
     * Load the parent construct and any additional models, helper, libraries available. 
     * 
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $this->load->model('content_page_model', 'content_page');
    }

    /**
     * Content_pages::read()
     * 
     * @return
     */
    public function read()
    {     
        //vardump($this->user_data);
        // Checks to see if the user has a role id of four and if they do then it shows the admin dashboard and if not then shows the user dashboard.
        if ($this->user_data->access_level_id >= 4)
        {
            // Retrieve all the users from the database that handle characters and assign it to the users variable.
            $content_pages = $this->content_page->get_all();

            // Place to dump the users array to verify it is the expected value.
            // vardump($users);

            // Checks to verify that there is data inside of the users array and that it is not empty.
            if (!empty($content_pages))
            {
                $this->template->set('content_pages', $content_pages);
            }

            // Add the breadcrumbs to the view.
            $this->breadcrumb->add_crumb('<li><a href="' . base_url() . 'wrestling-manager/control-panel" class="glyphicons home"><i></i> Control Panel</a></li>');
            $this->breadcrumb->add_crumb('<li><i></i> Content Pages</li>');
            $this->breadcrumb->change_link('<li class="divider"></li>');

            // Sets all the properites for the template view.
            $this->template
                ->set_theme('smashing')
                ->set_layout('control_panel_view')
                ->set_partial('header', 'partials/header')
                ->set_partial('sidebar','partials/sidebar')
                ->set_partial('footer', 'partials/footer')
                ->title('Content Pages')
                ->set('user_data', $this->user_data)
                ->build('content_pages_view');    
        }
        else
        {
            echo 'haha';
            //redirect('wrestling-manager/control-panel');
        }
    }

    /**
     * Content_pages::edit()
     * 
     * @return void
     */
    public function create()
    {
        echo 'testing for create function';
    }

    /**
     * Content_pages::edit()
     * 
     * @return void
     */
    public function edit($content_page_id)
    {
        vardump($content_page_id);
    }

    public function delete($content_page_id)
    {
        vardump($content_page_id);
    }

    /**
     * Content_pages::save()
     *  
     * @return
     */
    public function save()
    {
        echo 'testing for save function';
    }

    /**
     * Content_pages::update()
     * 
     * @return
     */
    public function update()
    {
        echo 'testing for update function';
    }
}

2 Answers 2

1

You could have your permissions set up either in a configuration file or in database.

With permission checking you'd probably be better off using interceptors/filters right before invoking any controller.

For the controllers, I have to say you're doing it a bit wrong as they're generally not intended to carry out CRUD operations, but domain-specific operations on a far higher level (or, in lower level case, a single common handleRequest method).

  • Have a list of roles and a list of permissions. (e.g. GUEST, USER, ADMIN roles; permissions are domain-specific)
  • Associate roles with permissions as per your needs.
  • Assign each user a role

You can then, via an AuthorizationService, check whether the current user is allowed to do something or not. This service, for example could iterate over all the permissions a given operation requires an verify that the role for the current user does have those; for example:

class AuthorizationFilter {

    public function verifyAccess($user, $request) {
        $role = $user->getRole();
        $permissions = $authorization->getPermissionsFor($request);
        $allowed = true;    // true as a missing permission will later set it to false
        for ($i = 0; $i < size($permissions); $i++) {
            $allowed &= $role->hasPermission($permissions[$i]);
        }
        return $allowed;
    }
}

Afterwards, you can invoke the controller for the original request or a "fallback" one based on the result of the authorization, e.g.:

class RequestDispatcher {

    public function dispatch() {
        // ...
        if ($authFilter->verifyAccess($user, $request)) {
            // invoke proper request controller
        } else {
            // invoke "you're not allowed to do this" controller
        }
        // ...
    }
}

WARNING: The code above is sample code only and by no means complete or otherwise suitable for production environment!!!

7
  • Is that what's going on in this link? github.com/EllisLab/CodeIgniter/wiki/Permission-Class Aug 29, 2013 at 11:04
  • @user2576961 God, how I hate CodeIgniter :) Well, it is something similar. If you take a closer look at the code you linked you can see a summary of each method as a comment right above them. The solution shown there is pretty ugly and unprofessional, but the concepts are the same. You're intercepting the request before servicing and ask an access control facility first to decide whether to allow or disallow the operation the user has requested. With the example, it is carried out inside the controller. I'd recommend against it (and CI in general), but it'll rather be a matter of your taste.
    – Powerslave
    Aug 29, 2013 at 11:11
  • Will you help me understand what I should do about the naming of my controller functions so they don't actually do the CRUD operations? Aug 29, 2013 at 11:19
  • @user2576961 Well, for your controllers, either a common-named handleRequest method or (for a controller mapped to several related requests) multiple operation-specifically named methods are the most suitable. For example, you could have the /attack/ and /defend/ URIs mapped to different methods (e.g. attack()/defend()) of the very same FightController (or BattleController if you like) or if you're going with the first approach, you'd have a separate AttackController and DefendController both having a handleRequest method.
    – Powerslave
    Aug 29, 2013 at 11:31
  • Since when is having CRUD operations inside a controller BAD practice?!?! I would say that you are forcing a personal preference and a bad one at that. Look at Rails and Yii and many other frameworks which by default have CRUD operations in the controller. In today's day and age of js framework frontends and api framework backends having CRUD operations in your controller is not only normal but RECOMMENDED. idk where you came up with this. Apr 9, 2014 at 13:43
1

Well, that's what MY_Controller is all about - you have to make all the checking there - create functions there and call them in the constructor, according to URL and/or GET/POST/SESSION parameters. And if user has no rights to access it, just add some flag or error text in SESSION. And then in your main controllers check only for that SESSION flag.

3
  • So I would have to do that for all 30+ controllers inside of the my controller? Aug 29, 2013 at 10:43
  • Another option would be from MY_Controller to redirect to some error page (or load view with error) and then exit; Aug 29, 2013 at 10:50
  • I did some searching and found some libraries that use ACL for user roles an privileges. For example this. github.com/EllisLab/CodeIgniter/wiki/Permission-Class Aug 29, 2013 at 11:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.