Reputation: 342
I am relatively new to the codeigniter framework and so far I am adapting well. I am curious if there is a short-cut to achieving my end result. Well, here is the problem at hand.
I am using this piece of code $data['logged_in'] = $this->verify_min_level(1);
to verify if the user is logged in. What I am trying to avoid is using this code in every other method in the controller but instead declare it once and it applies globally to all methods in the controller.
I have tried using protected $data['logged_in'] = $this->verify_min_level(1);
without any luck. Where am I going wrong and how do i correct it? Thanks in advance.
Upvotes: 1
Views: 1880
Reputation: 1756
I think you should implement this using library.
Create library, that knows how to do user's authorization using sessions and/or cookies, database, knows to validate user's level.
Create file "Auth.php" in "system\application\libraries" directory.
class CI_Auth {
var $obj;
/**
* Constructor
*
* @access public
*/
function CI_Auth()
{
/* here you get application's instance
you can use it then as $this->obj->load->model('usermodel');
$this->obj->usermodel->login($name, $pass);
*/
$this->obj =& get_instance();
/* init code using sessions, cookies, database */
}
function getUserId() {
/* your code */
return $user_id;
}
function getAuthLevel() {
if ($this->getUserId()) {
/* Your code */
return $level;
}
return false;
}
}
Then in system\application\config\autoload.php enable this library:
$autoload['libraries'] = array('database', 'session', 'auth');
And now you can use it in any controller, model or view as:
if (!$this->auth->getUserId())
{
/* MUST LOG IN*/
}
if (!$this->auth->getAuthLevel() < 2)
{
/* NO PERMISSIONS */
}
Upvotes: 0
Reputation: 608
Declare a variable in class and access it ...
class Class_name extends CI_Controller
{
protected $logged_in;
public function __construct()
{
$this->logged_in = $this->verify_min_level(1); // assign the value to variable
}
public function another_method()
{
echo $this->logged_in; // access the defined variable
}
}
Upvotes: 1
Reputation: 9782
Make a helper file in helpers
directory. And define a function to check the user login. Like
if( ! function_exists('is_logged_in') ) {
function is_logged_in() {
$CI =& get_instance();
// Now you can load any module here with $CI
// Check user and return appropriate data
}
}
Now autoload this helper so that you don't need to load it everytime, go to the config/autoload.php
and navigate $autoload['helper']
array, Now load this helper class here.
After doing this all, Your is_logged_in()
function is available to controller
, model
and view
you can apply anywhere.
Upvotes: 0