0
votes

So I have a "dashboard" controller that points to the corresponding view. This file can be accessed at any time simply by going to http://domain.com/dashboard. However, I only want this URL to be accessed IF the user is logged in already. If not, they're redirected back to the home page.

So TWO part question:

  1. How do I prevent a user from accessing the "dashboard" if they're not logged in first (should redirect to home page otherwise)...EDIT: THIS ISSUE HAS BEEN FIXED AND CODE UPDATED BELOW

  2. On the register controller, instead of a user being directed to the thank() function (which brings them to a thank you for registering page), how do I log the user in automatically and take them to the dash?

Here's my "dashboard" controller. Edit: Now works as it should. Second (2) issue above still remains.

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

class Dashboard extends CI_Controller{

function __construct(){
    parent::__construct();
    $this -> load -> model('user_model');
}

public function index()
public function index()
{
    $session = $this->session->userdata('logged_in');

    if ($session == 1) 
    {
        $data['title'] = 'Dashboard';
        $this -> load -> view('shared/header_view', $data);
        $this -> load -> view('dash', $data);
        $this -> load -> view('shared/footer_view', $data);
    }
    else {
        redirect('register');
    }
}
}

Here's my registration controller that logins, logouts, and registers the user:

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

class Register extends CI_Controller {

public function __construct() 
{
    parent::__construct();
    $this -> load -> model('user_model');
}

public function index() 
{
    if (($this -> session -> userdata('user_name') != "")) {
        $this -> welcome();
    } 
    else
    {
        $data['title'] = 'Home';
        $this -> load -> view('shared/header_view', $data);
        $this -> load -> view("registration_view.php", $data);
        $this -> load -> view('shared/footer_view', $data);
    }
}

public function welcome() 
{
     redirect('/dashboard/', 'refresh');
}

public function login() 
{
    $email = $this -> input -> post('email');
    $password = md5($this -> input -> post('pass'));

    $result = $this -> user_model -> login($email, $password);
    if ($result)
        $this -> welcome();
    else
        $this -> index();
}

public function thank() 
{
    $data['title'] = 'You are now registered!';
    $this -> load -> view('shared/header_view', $data);
    $this -> load -> view('thank_view.php', $data);
    $this -> load -> view('shared/footer_view', $data);
}

public function registration() 
{
    $this -> load -> library('form_validation');
    // field name, error message, validation rules
    $this -> form_validation -> set_rules('user_name', 'User Name', 'trim|required|min_length[4]|xss_clean');
    $this -> form_validation -> set_rules('email_address', 'Your Email', 'trim|required|valid_email');
    $this -> form_validation -> set_rules('password', 'Password', 'trim|required|min_length[4]|max_length[32]');
    $this -> form_validation -> set_rules('con_password', 'Password Confirmation', 'trim|required|matches[password]');

    if ($this -> form_validation -> run() == FALSE) 
    {
        $this -> index();
    } 
    else 
    {
        $this -> user_model -> add_user();
        $this -> thank();
    }
}

public function logout() 
{
    $newdata = array('user_id' => '', 'user_name' => '', 'user_email' => '', 'logged_in' => FALSE, );
    $this -> session -> unset_userdata($newdata);
    $this -> session -> sess_destroy();
    redirect('/', 'refresh');
}

}

EDIT: AS Requested, here's the user_model:

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

class User_model extends CI_Model {

public function __construct() {
    parent::__construct();
}

function login($email, $password) 
{
    $this -> db -> where("email", $email);
    $this -> db -> where("password", $password);

    $query = $this -> db -> get("user");
    if ($query -> num_rows() > 0) 
    {
        foreach ($query->result() as $rows) 
        {
            //add all data to session
            $newdata = array(
                'user_id' => $rows -> id,
                'user_name' => $rows -> username,
                'user_email' => $rows -> email,
                'logged_in' => TRUE,
            );
        }
        $this -> session -> set_userdata($newdata);
        return true;
    }
    return false;
}

public function add_user() 
{
    $data = array(
        'username' => $this -> input -> post('user_name'),
        'email' => $this -> input -> post('email_address'),
        'password' => md5($this -> input -> post('password')),
    );
    $this -> db -> insert('user', $data);
}

}

Codeigniter newbie. What am I doing wrong?

1
Some...but some is also from a tutorial. Why do you ask mate? - Mike Barwick
Because you already done harder part and asking the easier ones. None the less, you aren't following a uniform manner to check whether the user is logged in or not. Some times it is zero, some times it is empty string.... - itachi
Okay, are you able to answer? - Mike Barwick

1 Answers

1
votes

This rule on the dashboard controller looks a bit weird:

if ($session == 0)

Is the username really 0?? Or are you storing a boolean in this session. You should probably post your user_model too so we can see what you are doing there.

You should try to login a user and set a session like so:

$qry = $this->db->query("Select * from users where username = '$username' AND password = '$password'");
if( $qry->num_results > 0 )
{
    $this->session->set_userdata(array('logged_in' => true);
    redirect('dashboard');
}

And When a user tries to go to the dashboard just perform a check like this:

if( !$this->session->userdate('logged_in') )
{
     redirect(base_url());
}

So when there is no session logged_in or the session is false => redirect.

You can do the same when registering a user. After the user was registered succesfull and added to the database, just create the session like you did on the login function and redirect to the dashboard.