Example 3 – admin and regular user log in

In this example we will see how the controller can coordinate using models and views a login session for a regular user, as well as an admin super user, so that each will have a distinct menu. In order to use the provided database file and successfully log in, use the following steps:

  • For regular user login:
    • User: reg_user
    • Password: 111111111 (9 x 1 s)
  • For admin user login:
    • User: admin_user
    • Password: 111111111 (9 x 1 s)

This example will be constructed from the following controller, models, and views:

  • application/controller/auth.php: This controller is used to control authentication checkup and redirect each user category to its view or notify of a login failure. Regular users and admin users will have different view menu, message, and logout options.
  • application/models/users_model.php: This is the model to validate the submitted user name and password (stored in the database via MD5) against the predefined database table of users.
  • application/views/login_view.php: This is the view shown to users that are not logged in, in order to log in.
  • application/views/logged_in_view.php: This is the view shown to users that were successfully logged in and performed their roles as reg_user/admin users.
  • MySQL database- USERS_DB.sql: This is a database table that we will upload to our database.

Let us assume the URI to the project root is http://mydomain.com/myproject.

Hence the URI to execute the auth controller for login will be http://mydomain.com/myproject/auth.

The controller file

The controller file, controller/auth.php, will initially load the CI form helper; this helper will be used to construct and operate the login form. For more on helper usage and scope, refer to Chapter 5, Helpers.

users_model, written especially to serve the controller for authenticating users credentials against the user table, will be loaded. The controller auth/index will be called from both the initial stage as well as after a login_view submission.

The session is a well known issue in PHP and is out of the scope of this book. However, CI enables the storing of operated sessions with served clients via the database in a table named ci_sessions.

This way the sessions are much more organized for the project to manipulate with search session and load session parameter. In order to use a database stored session, we shall edit /config/config.php.

$config['sess_use_database'] = TRUE;
/* Enforce storing sessions data in the database */

Also, we will add a session library as we want to use it for this example along with other commonly used /config/autoload.php libraries.

$autoload['libraries'] = array('database', 'session', 'xmlrpc'),

In case of a submission, the input post for the password will not be null and the controller will proceed with the credentials checkup using the users_model model. If successful, the user record fields will be kept in the session and the controller methods auth/admin_main_menu or auth/user_main_menu will be called as per the model returned user role. If the logged in user issues the logout anchor, auth/logout will be called to destroy the session and redirect the user to the login form.

The following is the code:

class Auth extends CI_Controller {
  function __construct() {
    parent::__construct
    $this->load->helper ('form'),
    $this->load->model ('users_model'),
    }
  // called with auth is called with no specific method and // simply calls the login method
  function index() {
    $this->login();
    }
  functionlogin()
  {
    // The message to user in case of login failure
    $msg = "";
    if ($this->input->post('password'))
    {
      // The caller is from the form submission 
      // we will check credentials validity using the local method // check_login.
      $stat = $this->check_login();
      // Extract failure message to user if any
      $msg = $stat ['msg' ];
      if($stat['result'] == 'ok')
      {
        // Successful login!
        // See what We have
        // admin_user or regular user?
        if ($this->session->userdata ('role') == 'admin_user')
        // Issue the controller for admin user main menu
        redirect('auth/admin_main_menu'),
        else
        // Issue regular user main menu controller
        redirect('auth/user_main_menu'),
        return;
        }
      }
    else {
      // rendered with no submission 
      // let's destroy any previous session and challenge again // the user
      $this->session->sess_destroy();
      }
    // We can get here due to login failure or referring to auth // controller without any active submission.
    // Keep the msg return from the model into view view_setup
    ['msg'] = $msg; 
    // render the login view to challenge the user
    $this->load->view('login_view.php', $view_setup);
    }
  functioncheck_login() {
    // Extract the credentials from the submitted login_viewform
    $user_name = $this->input->post('user_name'),
    $password = $this->input->post('password'),
    // init an array to return
    $ret = array ();
    // Check if login is ok and get the $row using the loaded // users_model model.
    $user_record = $this->users_model->check_login ($user_name, $password);
    if ($user_record) {
      // User passed credentials checkup successfully
      // We have the user record. Let's use it to extract info // for the logged session buildup
      $this->session->set_userdata ('user_id', $user_record->id);
      $this->session->set_userdata ('user_name', $user_record->user_name);
      $this->session->set_userdata ('role', $user_record->role);
      $ret ['result'] = 'ok'; $ret ['msg' ] = 'Logged-in!';
      }
    else {
    // login failed!
    $ret ['result'] = 'notok';
    // inform the login form to alert user for the failure
    $ret ['msg' ] = 'Invalid User/Pass - Try Again!';
    }
  return $ret;
  }
// logout method called auth/logout
function logout() {
  // destroy the current session
  $this->session->sess_destroy();
  redirect('auth'),
  }
functionadmin_main_menu() {
  // Shall render an admin main menu page
  $view_setup ['uid'] = $this->session->userdata ('user_id'),
  $view_setup ['user_name'] = $this->session->userdata ('user_name'),
  $view_setup ['role'] = $this->session->userdata ('role'),
  $view_setup ['menu'] = "Add User/Modify User/Delete User";
  $this->load->view ('logged_in_view.php', $view_setup);
  }

functionuser_main_menu() {
  // Shall render a regular user
  $view_setup ['uid'] = $this->session->userdata ('user_id'),
  $view_setup ['user_name']= $this->session->userdata ('user_name'),
  $view_setup ['role']= $this->session->userdata ('role'),
  $view_setup ['menu']= "View Content/Modify Your Account/Logout";
  $this->load->view ('logged_in_view.php', $view_setup);
  }
}

The model file

The model file application/models/users_model.php will serve the controller for authenticating user credentials against the user table. If successful, the model will return the user database row to the caller.

auth/admin_main_menu or auth/user_main_menu will be called as per the model returned user role. If the logged in user issues the logout anchor, auth/logout will be called to destroy the session and redirect the user to the login form.

The following is the code:

class Users_model extends CI_Model {
  function __construct()
  {
    parent::__construct();
    }
  functioncheck_login ($user, $pass)
  {
  // Important notice.
  // Since the model extends the base CI model, it already got the // instance. However, we can use the $ci = &get_instance(); instead // $this-> anywhere in helpers, libraries, and so on.
  // convert the typed password in the login form to md5, same as // we do, when opening a user account.
  $md5_pass = md5($pass);
  // build up the query 
  $sql = "SELECT * FROM users WHERE user_name = '$user' AND password = '$md5_pass' ";
  $q = $this->db->query($sql);
  if ($q->num_rows()) {
    foreach ($q->result() as $row)
    return $row;
    }
  // In case no num_rows: return NULL;
  }
}

The database file to upload for this example

We shall upload this database file, provided as part of the book resources, into our database connected to CI.

The user table includes two users, namely reg_user and admin_user. Their passwords are stored as the md5 of the text passwords, where 111111111 and 222222222 are the passwords of the reg_user and admin_user users.

The following is the code:

-- phpMyAdmin SQL Dump
-- http://www.phpmyadmin.net
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
--
-- Table structure for table `users`
--
CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(128) NOT NULL,
  `password` varchar(128) NOT NULL,
  `role` varchar(128) NOT NULL,
  PRIMARY KEY (`id`)
  ) ENGINE=MyISAM DEFAULT CHARSET = utf8 AUTO_INCREMENT = 3;
--
-- Dumping data for table users
--
INSERT INTO `users` (`id`, `user_name`, `password`, `role`)
VALUES (1, 'reg_user', 'bbb8aae57c104cda40c93843ad5e6db8', 'regular_user'), (2, 'admin_user', '0d777e9e30b918e9034ab610712c90cf', 'admin_user'),

The login_view view file

The login_view view is rendered by the application/auth/index index method in order to show non-logged in web visitors to a login page, to enable to challenge them with a login stage.

Following a user entering the user name and password and submitting the login_view view form the application/auth/login will be called and will check the credentials using the users model. In case of a successful login, and based on the logged in user category fetch from the users model, one of the auth methods will be called as follows:

  • auth/admin_main_menu: In case the user has the admin role to render the successful login view for the admin user
  • auth/user_main_menu: In case the user has the admin role to render the successful login view for the regular user

The view is located at application/views/login_view.php. This view uses many of the CI form helper functions loaded by the auth controller. When a user issues a submission, the input is initially checked at the client side before issuing a submission call to application/auth.

The following is the code:

<!DOCTYPE html">
<meta http-equiv = "Content-type" content = "text/html; charset=utf-8"/>
<html>
<head>
<script src = http://code.jquery.com/jquery-latest.js type = 'text/javascript'></script>
</head>
<body>
<H1>Login Here</H1>
<!—Building the login form using the form helper-->
<?php
// Define the form attributes
// We will use the 'form' helper 'auth' will // be called on submission only, if check_if_valid()// will return true!
$submit_attributes = array('onsubmit' =>"return check_if_valid();", 'id' => 'auth'),
echoform_open('auth', $submit_attributes);
echo "<table><tr><td>";
// The attributes of the <input tag>
echoform_label("User Name");
echo "</td><td>";
echoform_input(array('name' => 'user_name', 'value' => ''));
echo "</td><td>";

// The error message holders – hidden by default echo
<label id='user_name_err' style = 'color:red; display:none'>name is too short </label>";
echo "</td></tr><tr><td>';
echoform_label("Password");
echo "</td><td>";
echoform_password("password","");
echo "</td><td>";
// The error message holders – hidden by default echo
<label id='password_err' style = 'color: red; display: none'> password is too short </label>";
echo "</td></tr>";
echo "</table>";
// The submit button echo
form_input(array('type' => 'submit', 'value' =>'Login'));
echoform_close(); ?>
<HR></HR>
<!-- Server Credentials failure message -->
<p style = "color: red"><?php echo $msg; ?></p>
</body>
<!-- Local JavaScript service -->
<script type='text/javascript'>
functioncheck_if_valid() {
  var submit = true;
  varuser_name = $('[name="user_name"]').val();
  var password = $('[name="password"]').val();
  if (user_name.length< 2) {
    $('#user_name_err').show();
    submit = false;
    }
  else $('#user_name_err').hide();
  if (password.length< 6) {
    $('#password_err').show();
    submit = false;
    }
  else $('#password_err').hide();
  return submit;
  }
</script>
</html>

The login_in_view view file

The login_in_view view is rendered following a successful login by either application/auth/admin_main_menu controller method or application/auth/user_main_menu method base on the user category with the info of the logged in user.

Both the controllers uses the users_model model to validate the login attempt and fetch the logged in user. The view shows the logged in user some information about its account, such as the user name and role as well as the menu available for its user category.

The view is located at application/views/login_in_view.php. This view is using parameters provided by the $user_nam, $uid, $role, and $menu controller to be shown to the logged in user. From this view, the user may issue a logout anchor that calls auth/logout to destroy the session and redirect the logged in user to the login view.

Many of the CI form helper functions are loaded by the auth controller. When user issues are submitted, the input is initially checked at the client side before issuing a submission call to application/auth.

The following is the code:

<!DOCTYPE html">
<meta http-equiv = "Content-type" content = "text/html; charset<!DOCTYPE html">
<meta http-equiv = "Content-type" content = "text/html; charset=utf-8"/>
<html>
<body>
<H1>Welcome <? = $user_name; ?>!</H1>
<H1>You are logged in!</H1>
<HR></HR>
<H3>Your User ID is: <? = $uid; ?></H3>
<H3>Your System Role is:<? = $role; ?></H3>
<H3>Your Menu options: <? = $menu; ?></H3>
<?php echo anchor ('auth/logout', 'Logout') ?>
</body>
</html>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.168.203