I am trying to load a controller (Dashboard) if session is ok.
if ($this->form_validation->run() == FALSE) {
if(isset($this->session->userdata['logged_in'])){
echo 'dashboard-01'; //test load
$this->load->controllers('Dashboard');//Not sure if syntax is ok.
Is this possible? are there better approaches on how to do this?
What I usually do is to load the controller and check on its constructor if the user has enough credentials:
class Sociedades extends CI_Controller {
var $globales = array();
function __construct()
{
parent::__construct();
$this->load->database();
$this->load->library(array('ion_auth','form_validation'));
// Elliot, if you see this, don't delete it!
$this->load->model('fSociety_model');
if (!$this->ion_auth->logged_in())
{
//redirect them to the login page if not authorized
redirect('auth/login', 'refresh');
}
}
// then the index and other methods...
}
By the way, I'm using Ben Edmund's IonAuth.
Related
I'm trying to implement basic section that only a logged-in user can access. I overrided CI_Controller, as follow:
//file created in application/core/MY_Controller.php
class Auth_Controller extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->library('session');
if ($this->session->userdata('user_logged') !== null){
redirect(base_url() . 'dashboard');
die();
} else {
redirect(base_url() . 'auth/login');
die();
}
}
And then I extend from Auth_Controller all the other controllers that are only available for the logged-in user, as follow:
class Dashboard extends Auth_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->view('dashboardView');
}
}
But after the login is successful, it doesn't redirect to dashboardView.
Anyone knows what is really happening?
You are redirecting infinitely to the Dashboard controller in this part of the code:
if ($this->session->userdata('user_logged') !== null){
redirect(base_url() . 'dashboard');
die();
}
Use this instead (redirect to the login form if the user is not logged in):
class Auth_controller extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->library('session');
// If the user is not logged in
if ($this->session->userdata('user_logged') === null){
// Redirect to http://yoursite/auth/login
// No need for the base_url function, redirect does it for you
redirect('auth/login');
// You don't have to exit/die, redirect() already does that
}
}
}
Opinions
If I check the null, will use like this != null. BUT in CI its a best option to check empty() rather null.
If I use redirect() will use it like this redirect('dashboard');
Code will be
if (!empty($this->session->userdata('user_logged'))) {
redirect('dashboard');
else {
redirect('auth/login');
}
Make sure your site will load without index.php in URL. If no search for .htaccess to your site.
In my header view I wrote this code:
<?php
if($this->session->userdata('logged_in')) {
$query = $this->db->get_where('instructors', array('id' => $this->session->userdata('id')));
$insdatacheck = $query->row_array();
if($insdatacheck['name'] == '') {
redirect(base_url().'user/continueregistration');
} else { ?>
<script type="text/javascript">alert('test');</script>
<?php
}
}
?>
But it does not redirect to the following page. However, if I write this in the controller, it works properly. I wrote it in header view because I want to check it in every page where enters the user. How can I improve it and write in a proper way? Thanks in advance
I think instead of your header you should put your check inside your controller constructor.
class Test extends CI_Controller {
function __construct() {
parent::__construct();
// if not logged-in redirect to login page
if ($this->session->userdata('logged_in') == false) {
redirect('login'); // where you want to redirect
}
}
}
Another option is to create a base controller. Place the function in the base controller and then inherit from this.
To achieve this in CodeIgniter, create a file called MY_Controller.php in the libraries folder of your application.
class MY_Controller extends Controller
{
public function __construct()
{
parent::__construct();
}
public function is_logged_in()
{
$user = $this->session->userdata('user_data');
return isset($user);
}
}
Then make your controller inherit from this base controller.
class X extends MY_Controller
{
public function __construct()
{
parent::__construct();
}
public function do_something()
{
if ($this->is_logged_in())
{
// User is logged in. Do something.
}
}
}
First create session in the controller only,
Then we access session in any page,
$this->load->library('session');
$user=$this->session->userdata('logged_in');
if (!isset($user)) {
redirect(base_url().'user/continueregistration');
}
else {
<script type="text/javascript">alert('test');</script>
}
I have a login helper in my CodeIgniter project.
In every constructor of a controller I call a function to check if the user is logged in.
However when calling a function(getSetup) when logged out the login_view appears but also the other view db_manage for example. But I don't want to show content when not logged in.. How to fix this ?
Thanks
function __construct() {
parent::__construct();
if (!is_logged_in()) {
$this->load->view('login_view');
}
}
public function getSetup() {
$this->load->view("db_manage");
}
this way:
function __construct() {
parent::__construct();
if (!is_logged_in()) {
echo $this->load->view('login_view', null, TRUE);
exit();
}
}
yes, you can't exit in the c'tor that will stop Codeigniter from doing its render process from the output buffer. You can't really do this from the c'tor, its not really what the c'tor is for, its meant for setting up the class variables..
you should check the logged in from the method, and return the login view from there.
class My_Controller {
function ensureLoggedIn() {
if(!is_logged_in()) {
$this->load->view('login_view');
return False;
}
return True;
}
function getSetup() {
if(!$this->ensureLoggedIn())
return;
.... rest of method ...
}
}
#egig - whats the point in using a framework if your going to bypass the stack?!
I have a controller where in the constructor function, I want to check if the user is logged in or not. If not, I want an error message to be displayed, and for the script to exit without running any other function in the controller. This controller will only be called by ajax so the error would be displayed via JSON and then the javascript on the client will display it to the user.
How can I do this? If I did this:
function __construct()
{
if (! $this->loggedIn() )
{
echo json_encode( array('error'=> true) );
die;
}
}
I don't think the message would be displayed because codeigniter uses output buffering. Any ideas?
i understood that your problem is the client expects for a json type of response, so two options to use:
public function __construct(){
$_bad_login_msg = 'please try again' ;
parent::__construct();
if(!userLoggedIn()){
$this->output
->set_content_type('application/json')
->set_output(json_encode($_bad_login_msg));
//or just use
// echo json_encode($_bad_login_msg);
die;
}
}
http://codeigniter.com/user_guide/libraries/output.html
you won't have any buffering problems, the buffer contents will be sent to the client after the die...
The best way is to redirect the user to login page.
As mentioned here : https://stackoverflow.com/a/10399199/876117
public function __construct(){
parent::__construct();
if(!userLoggedIn())
$this->load->view('promptlogin');
$this->output->_display();
exit();
}
public function index(){
// one will never reach here unless he is logged in
$this->load->view('actualcontent');
}
I'm pretty sure you can just use something like this:
function __construct()
{
if (! $this->loggedIn() )
{
exit('Please login before visiting this page');
}
}
MY_Controller is your top level/parent controller so its all done in there because every other controller will extend it. So if you have an auth controller(which extends MY_Controller) you will have access to its logic.
So MY_Controller
class MY_Controller extends CI_Controller{
protected $_user;
public function __construct(){
parent::__construct();
$this->_user = $this->session->userdata('uid')
? find_a_user : NULL;
// if a session of user_id exists and is found in DB
// we have a live user
}
}
Auth
class Auth extends MY_Controller{
public function __construct(){
parent::__construct();
// we now have access to $this->_user
if($this->_user !== NULL) // we have active user
}
}
I think you should use flashdata and redirect to a controller with it. Then you can control if any flashdata comes in session, after that write it in view.
Hey! I'm very new to Codeigniter, I'm trying to protect the entire admin controller. I figured I'd start here:
function Admin()
{
parent::Controller();
if(!isset($_SESSION['loggedin'])){
$this->login();
}
}
but this is obviously incomplete. How do I also stop the method that is trying to run ( ie index() ), and am I on the right track here??
Thanks for your help!!
there is
Extend the base controllers:
MY_Controller.php
<?php
class MY_Controller extends Controller {
function __construct()
{
parent::Controller();
$user_id = $this->session->userdata('user_id');
$this->data['user'] = $this->user_lib->get($user_id);
}
}
?>
you can store all kinds of info in this construct. This just gets the currently logged in users ID and assigns it the $data['user'] . This will be adjusted depending on which sort of auth library you use but you get the gist. You now have access to the current users ID, and all their details, from within any controller that extends "MY_Controller"
now you can create an "admin" controller, or any number of other ones to restrict access. like so:
Admin_Controller.php
<?php
class Admin_Controller extends MY_Controller {
function __construct()
{
parent::Controller();
if($this->data['user']['group'] !== 'admin')
{
show_error('Error - you need to be an admin.');
}
}
}
?>
Public_controller.php
<?php
class Public_Controller extends MY_Controller {
function __construct()
{
parent::Controller();
if($this->data['user']['group'] !== 'member')
{
show_error('You need to login to see this page...');
}
}
}
?>
as you can see..possibilities are endless
So, for admin only pages - use the admin controller
for member only pages - public
for "normal" pages - use the default controller.
I'll link to Phil Sturgeon's article as it's where I read about it first
put the checking session code in every function in Admin Controller that you want to protect.
that is the easiest way to do it..