is it possible to check user authentication at constructor function of code igniter controller?
user controller
class user extends CI_Controller{
function __construct() {
parent::__construct();
$this -> load -> model('user_model');
if (!$this -> user_model -> logged_in()) {
$this -> load -> view('user/login');
} else {
return TRUE;
}
}
}
while i running this i got login view top of my dashboard after login. before login i get two login view. i tried this for minimize to repeatedly check is user loggedin or not.
If you want to show login page with out change the url, You should do forward method. But CI have not method for forward.
check following answers.
Internal forward action in CodeIgniter
Just do a simple session check like where you check the session validity of the user if set or not:
if(!$this->session->userdata('logged_user')){
redirect('controller/function', 'refresh');
}
In the controller:
public function function(){
$this->load->view('login');
}
Related
I have created a user login and logout system. After login the user gets redirected to his dashboard. Currently with the help of correct url, the user can go directly to dashboard without login. to restrict this i used the following code so that user can not access any internal pages before login
class User extends CI_Controller
{
public function __construct()
{
parent::__construct();
if(!$this->session->userdata('logged_in'))
{
$this->session->set_flashdata('no_access', 'sorry you are not allowed');
redirect('user/noaccess');
}
}
}
Now when i try to access the dashboard with a correct url, but without login i am not able to view it but is is also not etting redirected to noaccess. i am getting the following error
the page not redirecting properly
Can anyone please tell how to do this properly
Sam consider doing this
public function logged_in()
{
$logged_in = $this->session->userdata('logged_in');
if (!isset($logged_in) || $logged_in != true)
{
redirect("Checkin"); //insert your login page
}
}
Then in your controller for page access you can call this method
public function admin()
{
$this->logged_in();
//rest of controller here
}
This will prevent anyone from accessing your admin pages without login. The "logged_in" method will redirect them to the login page. That way you are not redirecting to yet another page(user/noaccess) or using flashdata. Use the $this->logged_in(); on any method that requires login
im doing this;
example core/MY_CONTROLLER.php
private $action_user=null;
public function __construct()
{
parent::__construct();
##listen for post attempts;
$this->validate();
##set action_user; return null if no session else return user object
$this->action_user = $this->session->userdata('loged_user');
##extra check step
if($this->user->pwd_has_changed($this->action_user)){
$this->session->sess_destroy();
alerts('error','the password you used to login has changed ! please relogin');
return $this->failed_login();
}
}
public function alerts(){return die(json_encode(alerts()));}#a helper function.. just ignore it for this example
public function logout(){$this->session->sess_destroy();redirect();}
#AUTH
private function failed_login(){
//$callers=debug_backtrace();
alerts('warning','failed login');//.' '.$callers[1]['function']);
ob_clean();//clear flush just to make sure !
if($this->input->is_ajax_request())$this->load->view('base/ajax/landing');
else $this->load->view('base/landing');
die($this->output->get_output());//kill request and load landing in same uri. this in case he attempt login again he will be at same url; also helps with partials views
}
private function success_login(){
unset($_POST['login'],$_POST['password']);
alerts('success','welcome '.$this->action_user->login);
//nothin much to do.. just dont die
}
private function validate(){
//listen to posts if so logout and relog in
if( !$this->input->post('login') || !$this->input->post('password'))return FALSE;
$this->session->sess_destroy();#destroy session
#1. validation
$this->form_validation->set_rules('login', 'User Login', 'required|min_length[4]|max_length[12]|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[4]|max_length[12]|xss_clean');
#1.2 Failed validation
if( ! $this->form_validation->run() )return alerts('error',$this->form_validation->error_string(),false);#set message and return false
#2. Login
$this->user->login(set_value('login'),set_value('password'));
//i dont want it to return anything ! $this->user->login should set messages of success OR fail + set user session
}
public function auth($role = null){
if(!isset($this->action_user->id))
return alerts('error',"this is a users restricted area",$this->failed_login());
//ACCESS LEVELS CONDITIONS
if($this->user->in_group($this->action_user->id,$role))return $this->success_login();
return alerts('error',"this is a {$role} restricted area",$this->failed_login());
}
#END AUTH
now in my controller constructor; since MY_CONTROLLER constructor is called first; so i should hv retrieved $action_user object; or already attempted to log him in.
if i want to restrict a page i just add
$this->auth();
//or $this->auth('admin');
to its constructor and if user is not allowed page will die and send him my view page without redirect;
the reason im using such approach is let user be able to login,logout from any controller;
if he visit http://localhost/RANDOMECONTROLLER/logout he will still logout.. same for login.
also its helpful that sometimes when i get page partials by ajax; it will just return a landing page into this div with login form.
example
a statistics page have 4 widgets, 1 of them is only viewable by admin;
then when ajax fitch 4 widgets, it will show 3 and a div with login form saying you need to be an admin to login..
...
so do you think this is a good way to do this ? or is it bug gable spaghetti ** ?
This is not a good practice. The best practice is to create a Secure_Controller that extends MY_Controller. If you have a controller with auth you need to extend Secure_Controller, but if you have another without auth you need yo extend MY_Controller.
There are lots of libraries for codeigniter auth easy to extend and adapt to your requirements, for example Ion Auth.
My Main Controller checks wheter the user is admin or not, then redirects to a user/login which is a child class of the main controller who again checks if the user is an admin or not...so then the redirect is in loop, I don't know where better to put the login function?
Admin_Controller -> {
child1_Controller -> {
function login()
{
//render login page, but can't because the main class constructor is checking login and redirecting again here
}
}
}
Look at running a pre_controller hook to check the user details instead of using the constructor
http://ellislab.com/codeigniter/user-guide/general/hooks.html
i have login form, and then i try to access the controller directly, it works ! how do i prevent this access ?
i got some class
class C_home extends CI_Controller{
public function __construct() {
parent::__construct();
$this->session->set_userdata('islogin'); //to set session islogin
}
function index()
{
if ($this->session->userdata('islogin') != TRUE)
{
redirect('c_home','refresh'); //caused infinite refresh
}
redirect('c_login', 'refresh');
}
}
then i try to direct access controller, the page show infinite refresh, i want the page to show the login form
how do i resolve this ?
A couple of comments:
On the $this->session->set_userdata('islogin'); line, you should pass a 2nd argument which is the value to be assigned (presumably, TRUE is what you meant to put)
I think your redirect lines are the wrong way around. If the user isn't logged in, then you want to redirect to login. Now what your code does is redirect to home if the user isn't logged in, hence the endless loop (since this code is in the home page!
The $this->session->set_userdata('islogin', TRUE); line should obviously be in your login controller, but I'm guessing you've put it here just for testing purposes?
I'd rather do this like so
class C_home extends CI_Controller {
public function __construct()
{
parent::__construct();
}
function index()
{
if ($this->session->userdata('islogin') != TRUE)
{
redirect('c_home/login','refresh'); // go for login
}
// do something for loged in users here
}
function login()
{
if ($this->session->userdata('islogin') == TRUE)
{
redirect('c_home','refresh'); // get back home
}
// perform some login logic here
// then, if successful
{
$this->session->set_userdata('islogin',TRUE);
redirect('c_home','refresh'); // get back home
}
// or else
// display login form here
}
Of course is always better to use third party login library like this one https://github.com/DaBourz/SimpleLoginSecure
You're supposed to access the controller, that is the point of them to control things. If you have specific functions you don't want accessed via URL then prefix the function name with an _ like _notForPublicFunction. As to the infinite refresh...
if(!$this->session->userdata('isLogin'))
{
redirect('c_login');
} else {
redirect('c_home');
}
What you need to do is set up a base controller that will look after the session for you and split your logged in controllers from your logged out ones via inheritance.
It is a common question on here how best to manage logged-in and logged-out states. Please refer to this answer for detailed explanation on how to do it.
I am really new to CodeIgniter.
I am trying to setup a website where the user must be logged in to view the pages. Coming from Java, I am taking the hierarchical approach to things.
My thought was to write my own Controller base:
<?php
class MY_Controller extends Controller
{
function Controller()
{
parent::Controller();
if(!$this->quickauth->logged_in())
{
//they need to login, send them to the login page.
}
}
}
?>
Now I can write controllers which extend it and I will be sure that they will always be logged in.
Here is the outline for the login page:
<?php
class login extends Controller
{
function index()
{
//Lets just double check, they might not have to login.
if ($this->quickauth->logged_in())
{
//send them to the main controller
}
}
}
?>
Well as you can see I have gotten this far. What do I need to replace:
1. //send them to the main controller
2. //they need to login, send them to the login page.
with?
Is there a better way of doing this?
Thanks,
Blake
Redirection is easy.
Just use:
redirect('controller/method');
Yes, load the url helper to access the redirect function.
$this->load->helper('url);
Since the url helper is used a lot, you should autoload it in config/autoload.
if you load the 'url_helper' you've got a redirect function in there. Read the docs about the url helper for more information.
You could also use soemthing like this
function is_logged_in()
{
$is_logged_in = $this->session->userdata('is_logged_in');
if (!isset($is_logged_in) || $is_logged_in != true)
{
echo 'You don't have permission to access this page. Login';
die();
//$this->load->view('login_form');
}
}
You could build on this