1
\$\begingroup\$

The User Model

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

class UserModel extends CI_Model 
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('PermissionModel');
        $this->load->database('default');
    }

    public function getUserById($userId)
    {
        $this->db->select('login, name');
        $this->db->where('id', $userId);
        $queryUser = $this->db->get('user');
        return $queryUser->row(0);
    }

    #Function that returns the user object from the actual session.
    public function getUserFromSession()
    {
        $userId = $this->session->userdata('userId');
        $user = getUserById($userId);
        return $user;
    }

    public function listUsers()
    {
        if ($this->PermissionModel->checkPermission(__METHOD__)) {
            $this->db->select('login, nome');
            $queryUser = $this->db->get('usuarios');
            return $queryUser->result();
        }            
    }
}

The PermissioModel

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

class PermissionModel extends CI_Model 
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('UserModel');
        $this->load->database('default');
    }

    #Essa função verifica se o usuário da sessão tem uma permissão para o método/ação passado como argumento.
    public function checkPermission($actionName)
    {
        $user = $this->UserModel->getUserFromSession();
        $this->db->select('user_id, action_id');
        $this->db->from('permission');
        $this->db->join('action','action.id=permission.action_id AND acao.nome='.'"'.$actionName.'"');
        $this->db->where('user_id',$user->id) 
        $queryPermission = $this->db->get();
        #Se retornou somento um resultado, significa que o usuário tem acesso.
        if ($queryPermission->num_rows() == 1) {
            return true;
        }
        return false;
    }

}

So is there any better way to do this? Is my code reasonable? How can I make it testable? I probably will use these models for all system here. So it will grow a lot and I'm omitting some of the details to simplify the example.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.