Codeigniter Restrict Admin Page via URL - php

I am building a website wherein I have an admin and user page. I have a problem wherein I can access the admin page via URL even though I am logged in as a user. I have validation checks at the login page, however if I am already logged in as a user or as an admin, I can access all the pages. I want to restrict the pages to their roles only. Here's my code.
MY_Controller:
function __construct()
{
parent::__construct();
$this->is_logged_in();
$session_admin = $this->session->userdata('isAdmin');
$method = $this->router->fetch_method();
if(($session_admin == FALSE) && $method != 'login')
{
$this->session->set_flashdata( 'message', 'You need to login to access this location' );
redirect('user_home');
}
else
{
redirect('admin_ticketing/new_tickets');
}
}
function is_logged_in()
{
$is_logged_in = $this->session->userdata('is_logged_in');
if(!isset($is_logged_in) || $is_logged_in != true) {
redirect('login');
die();
}
}
Model:
function validate()
{
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', $this->input->post('password'));
$query = $this->db->get('accounts');
$result = $query->row();
if($query->num_rows() == 1)
{
return true;
}
else
{
return false;
}
}
function check_role()
{
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', $this->input->post('password'));
$this->db->where('role', 1);
$query = $this->db->get('accounts');
$result = $query->row();
if($query->num_rows() == 1)
{
$data = array(
'userid' => $result->userid,
'username' => $result->username,
'password' => $result->password,
'firstname' => $result->firstname,
'lastname' => $result->lastname,
'email' => $result->email,
'address' => $result->address,
'monthly_dues' => $result->monthly_dues,
'arrears' => $result->arrears,
'isAdmin' => true,
'contactnum' => $result->contactnum,
'role' => $result->role,
'is_logged_in' => true
);
$this->session->set_userdata($data);
return true;
}
else
{
return false;
}
}
function check_user()
{
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', $this->input->post('password'));
$this->db->where('role', 0);
$query = $this->db->get('accounts');
$result = $query->row();
if($query->num_rows() == 1)
{
$data = array(
'userid' => $result->userid,
'username' => $result->username,
'password' => $result->password,
'firstname' => $result->firstname,
'lastname' => $result->lastname,
'email' => $result->email,
'address' => $result->address,
'monthly_dues' => $result->monthly_dues,
'arrears' => $result->arrears,
'isAdmin' => false,
'contactnum' => $result->contactnum,
'role' => $result->role,
'is_logged_in' => true
);
$this->session->set_userdata($data);
return true;
}
else
{
return false;
}
}
function check_active()
{
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', $this->input->post('password'));
$this->db->where('isActive', 1);
$query = $this->db->get('accounts');
$result = $query->row();
if($query->num_rows() == 1)
{
return true;
}
else
{
return false;
}
}
Controller:
function validate_login()
{
$this->load->model('model_accounts');
$valid = $this->model_accounts->validate();
$isAdmin = $this->model_accounts->check_role();
$isUser = $this->model_accounts->check_user();
$isActive = $this->model_accounts->check_active();
if($valid && $isAdmin && $isActive) // Active Admin
{
redirect('admin_ticketing/new_tickets');
}
else if($valid && $isActive && $isUser) // Active User
{
redirect('user_home');
}
else if(($valid && $isAdmin) && $isActive == false) //Deactivated Admin
{
redirect('login/admindeact');
}
else if($valid && ($isActive && $isAdmin) == false) //Deactivated User
{
redirect('login/userdeact');
}
else if($valid == false) //Invalid Account
{
$data['message'] = "Sorry, the username and password you entered did not match our records. Please double-check and try again. ";
$this->template->load('template', 'view_login', $data);
}
}

You can check this in your controller, See this code,
function __construct()
{
parent::__construct();
$session_admin = $this->session->userdata('admin'); //getting admin session
$method = $this->router->fetch_method(); // get the current method
if(empty($session_admin) && $method != 'login'){ // check for admin session and methos is login
$this->session->set_flashdata( 'message', 'You need to login to access this location' );
redirect('admin/users/login');
}
}

If you only want to set roles for admin and front-user simply at the time of login, set a session value 'is_admin'
Then you can check if($is_admin) like that.

Related

Codeigniter - session data won't set

I have an issue setting session data. I want to set the session data to a boolean 'loggedIn' and an id 'userID'. For some reason when submitting the login form, the login() function will reach the line where it redirects to the dashboard() function, but then stops at the dashboard function.
Controllers
public function login() {
// echo 'login page';
$this->session->set_userdata('userID', NULL);
$this->session->set_userdata('loggedIn', NULL);
$data['session_data'] = array(
'userID' => $this->session->userdata('userID'),
'loggedIn' => $this->session->userdata('loggedIn')
);
$this->load->view('navigation');
$this->load->view('login', $data);
if ($this->session->userdata('loggedIn') == TRUE) {
$this->session->set_flashdata('error_msg', 'please log out to access this page ');
echo 'Please log out to access this page!...';
sleep(2);
redirect('index.php/user/dashboard');
}
if ($this->input->post('login')) {
$this->form_validation->set_rules('username', 'username', 'required');
$this->form_validation->set_rules('password', 'password', 'required');
$login_details = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password')
);
if ($this->form_validation->run() == true) {
$this->session->set_flashdata('sucess_msg', 'form running ');
$verify_password = $this->user_model->verify_password($login_details);
if ($verify_password == true) {
$this->session->set_flashdata('error_msg', 'password verified true ');
$userID = $this->user_model->get_userID($login_details);
$data_session = array(
'loggedIn' => TRUE,
'userID' => $userID
);
$session_loggedIn = array('loggedIn' => TRUE);
$session_userID = array('userID' => $userID);
$this->session->set_userdata('loggedIn', $session_loggedIn);
$this->session->set_userdata('userID', $session_userID);
//$this->session->set_userdata('loggedIn', $data_session['loggedIn']);
//$this->session->set_userdata('userID', $data_session['userID']);
$this->session->set_flashdata('success_msg', 'loggedIn and userID changed to current log in account ');
echo 'USER ID: ' . $this->session->userdata('userID');
//$this->load->view('dashboard', $);
redirect('index.php/user/dashboard');
} else {
$this->session->set_flashdata('error_msg', 'wrong email or password, try again!...');
//redirect('index.php/user/login');
}
}
}
}
public function dashboard() {
if ($this->session->userdata('loggedIn') == FALSE) {
$this->session->set_flashdata('error_msg', 'please log in to access the dashboard page');
sleep(2);
redirect('index.php/user/login');
} else {
$data['user'] = array(
'user' => $this->user_model->get_user_data($this->session->userdata('userID'))
);
$this->load->view('navigation');
$this->load->view('dashboard', $data);
}
}
Models
public function verify_password($login_details){
$this->db->select('password');
$this->db->from('user_account');
$this->db->where('username', $login_details['username']);
$query = $this->db->get->result_array();
if($query[0] == $login_details['password']){
return true;
} else {
return false;
}
}
Config
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = APPPATH.'cache/sessions/';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = TRUE;
Result
session data: Array ( [userID] => [loggedIn] => )
session data: Array ( [__ci_last_regenerate] => 1522538883 [userID] => [loggedIn] => )
The program will reach the first condition of the dashboard function and then redirect back to the login page because it says that the session data 'loggedIn' is not set to TRUE.

CodeIgniter - Login is not working

I'm currently working with admin page. I logged in my username and password correctly but it says "404 Page Not Found - The page you requested was not found."
This is the controller:
public function login()
{
$header = array("title" => "Welcome - ");
$this->load->view('includes/header', $header);
$this->load->view('accounts/login');
$this->load->view('includes/footer');
}
public function login_submit()
{
$data = array(
'username' => $this->input->post('username'),
'password' => sha1($this->input->post('password'))
);
$this->form_validation->set_rules('username', 'Username', 'required|is_unique[accounts.username]|min_length[6]');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[6]');
$accountDetails = $this->accounts_model->fetch('accounts', $data);
if (!$accountDetails) {
echo "<script>alert('Account does not exist!'); window.location.href = '".base_url()."accounts/login';</script>";
} else {
$accountDetails = $accountDetails[0];
if ($accountDetails->status == 1) {
$header = array("title" => "Account - ");
$this->load->view('includes/header', $header);
$this->load->view('admin/home', $accountDetails);
$this->load->view('includes/footer');
} else {
echo "<script>alert('You account is blocked!'); window.location.href = '".base_url()."accounts/login';</script>";
}
}
}
I hope this code will help you..Works fine
plz set your form like this:
<form action='<?php echo base_url();?>index.php/accounts/login_submit' method='post' name='process'>
accounts Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/* Author: Pedram shabani
* Description: accounts controller class
*/
class accounts extends CI_Controller{
function __construct(){
parent::__construct();
}
public function login($msg = NULL)
{
$data['msg'] = $msg;
$this->load->helper('url');
$header = array("title" => "Welcome - ");
$this->load->view('includes/header', $header);
$this->load->view('accounts/login',$data);
$this->load->view('includes/footer');
}
public function login_submit()
{
$username = $this->security->xss_clean($this->input->post('username'));
$password = $this->security->xss_clean($this->input->post('password'));
$data = array(
'username' => $this->input->post('username'),
'password' => sha1($this->input->post('password'))
);
$this->load->model('accounts_model');
$accountDetails = $this->accounts_model->fetch($data);
if(! $accountDetails){
// If user did not validate, then show them login page again
$msg = '<font color=red>Invalid username and/or password.</font><br />';
$this->login($msg);
}else{
$this->load->helper('url');
$header = array("title" => "Welcome - ");
$this->load->view('includes/header', $header);
$this->load->view('accounts/login',$data);
$this->load->view('includes/footer');
}
}
}
?>
accounts_model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class accounts_model extends CI_Model{
function __construct(){
parent::__construct();
}
public function fetch ($data){
// die(var_dump($data));
$this->db->select('*');
$this->db->where('username', $data['username']);
$this->db->where('password', $data['password']);
$query = $this->db->get('users');
$num = $query->num_rows();
if($query->num_rows == 1)
{
$row = $query->row();
$data = array(
'userid' => $row->userid,
'fname' => $row->fname,
'lname' => $row->lname,
'username' => $row->username,
'validated' => true
);
$this->session->set_userdata($data);
return true;
}
return false;
}
}
?>
and at the end.plz set default controller
$route['default_controller'] = 'login';

stay in dashboard when the user is logged

how can I stay in dashboard when the user is logged even though when the user write localhost/storeLTE/login/ then stay home. but my code doesnt work.
public function getAccess(){
if ($this->session->set_userdata('username')) {
redirect('home');
}
$username = $this->security->xss_clean($this->input->post('username'));
$password = $this->security->xss_clean($this->input->post('password'));
$array = $this->User_model->login($username,$password);
if($array[0] == 0){
echo 0;
}else{
$data_session = array(
'id' => $array[0]['iduser'],
'username' => $array[0]['username'],
'password' => $array[0]['password'],
'name' => $array[0]['name'],
'last_name' => $array[0]['last_name'],
'type' => $array[0]['idType'],
'logged_in' => TRUE
);
$this->session->set_userdata('log',$data_session);
}
}
if ($this->session->set_userdata('username')) {
should be
if ($this->session->userdata('username')) {
or
if ($this->session->userdata('username') !== NULL) {
//since NULL is returned if item is not found
Docs.
FYI
Its is NOT a good sign of STORING PASSWORD IN THE SESSION. Its better to store name, type, logged_in, id.
In Controller
function getAccess(){
$this->load->library('session'); # load library here or in autoload.php
if($this->session->userdata('logged_in') == TRUE)
{
redirect('home');
}
else
{
$username = $this->security->xss_clean($this->input->post('username'));
$password = $this->security->xss_clean($this->input->post('password'));
$result = $this->User_model->login($username,$password);
if($result == FALSE)
{
echo 'Invalid Login';
}
else{
$data_session = array(
'id' => $result[0]['iduser'],
'username' => $result[0]['username'], # Better to remove
'password' => $result[0]['password'], # Better to remove
'name' => $result[0]['name'],
'last_name' => $result[0]['last_name'],
'type' => $result[0]['idType'],
'logged_in' => TRUE
);
$this->session->set_userdata('log',$data_session);
$this->load->view('home'); # Load the view
}
}
}
In Model
function login($username,$password)
{
$query = $this->db->query("SELECT * FROM table name WHERE username = '$username' AND password = '$password'");
$result = $query->result_array();
if (count($result) > 1 || empty($result))
{
return FALSE;
}
else {
return $result;
}
}
if ($this->session->set_userdata('username')) {
redirect('home');
}
change this to
if ($this->session->userdata('username') !='') {
redirect('home');
}

change password on codeigniter

I tried to make a change password function, but nothing happened.I actually adapted codeigniter change password code but again, nothing happened.Here I attached the code, any hep would be appreciated.
the controller -
function change_password_process()
{
$this->load->view('ubahpassword_view');
$this->load->library('form_validation');
$this->load->library('session');
$this->form_validation->set_rules('pass_lama','Password Lama','trim|required|min_length[4]|max_length[32]');
$this->form_validation->set_rules('pass_baru','Password Baru','trim|required|min_length[4]|max_length[32]');
$this->form_validation->set_rules('ulangpass_baru','Ulangi Password Baru','trim|required|min_length[4]|max_length[32]|matches[pass_baru]');
if ($this->form_validation->run() == FALSE)
{
redirect('ubahpassword');
}
else
{
$query = $this->rekammedis_model->change_password();
redirect('ubahpassword');
}
}
The model -
function change_password()
{
$this->db->select('id');
$this->db->where('username', $this->session->userdata('username'));
$this->db->where('id', $this->session->userdata('id'));
$this->db->where('password', md5($this->input->post('pass_lama')));
$query = $this->db->get('user');
if ($query->num_rows() > 0)
{
$row = $query->row();
if($row->id === $this->session->userdata('id'))
{
$data = array(
'password' => md5($this->input->post('pass_lama'))
);
$this->db->where('username', $this->session->userdata('username'));
$this->db->where('password', md5($this->input->post('pass_lama')));
if($this->db->update('user', $data))
{
return "Password berhasil diganti!";
}
else
{
return "Terdapat kesalahan, password tidak terganti";
}
}
else
{
return "Terdapat kesalahan, password tidak terganti";
}
}
else
{
return "Password lama salah";
}
}
Assuming baru means new and lama means old.
You were changing your old password with old password itself (pass_baru)
So Replace
$data = array('password' => md5($this->input->post('pass_lama')));
with
$data = array('password' => md5($this->input->post('pass_baru')));
UPDATE
Found Another Bug
if ($this->form_validation->run() == FALSE)
{
redirect('ubahpassword');
}
You can't redirect it, if you do, you won't get validated here.
Load your view here itself. Also update your code above if it does not work

Login section not working well in php codeigniter

I'm using php codeigniter for my project. In my login page if username and password is invalid just load the login page, else load the home. if invalid, First time it loads the login page again given the wrong details for login one controller name is added in url like local turns like localhost/project name/administrator/administrator/login_authentication
my code is
function index()
{
if($this->session->userdata('usertype') != '')
{
redirect('administrator/administrator_view');
}
else
{
$this->load->view('login');
}
}
function login_authentication()
{
$username=$this->input->post('username');
$password=$this->input->post('password');
$user = $this->administrator->admin_authentication($username,$password);
if(count($user) == 1)
{
foreach($user as $admin_value)
{
$user_name=$admin_value['UserName'];
$usertype=$admin_value['UserType'];
}
$session_data = array(
'username' => $user_name,
'usertype' => $usertype,
);
$this->session->set_userdata($session_data);
if($usertype == 1)
{
redirect('administrator/administrator_view');
}
}
else
{
$data['Invalid_Login']="Invalid Username and Password";
$this->load->view('login',$data);
}
}
function administrator_view()
{
if($this->session->userdata('usertype') == '')
{
redirect('administrator');
}
else
{
$data['heading'] = '';
$this->load->view('header', $data);
$this->load->view('dashboard', $data);
$this->load->view('footer');
}
}
Admin authentication function
function admin_authentication($username, $password)
{
$this->db->select('*');
$this->db->from('user');
$this->db->where('UserName',$username);
$this->db->where('Password',$password);
$query = $this->db->get();
return $query->result_array();
}
I'm trying more than one time given not correct information for login everytime one controller name added in url. Please help me.
Thanks in advance.
change
$this->session->set_userdata($session_data);
to
$this->session->set_userdata(('some_name', $session_data);
and change
if($this->session->userdata('usertype') == '')
in all area to
$ses = $this->session->userdata('some_name');
if($ses['usertype'] == '')
and try....
first of all check if there is an post request in your function login_authentication() like this:
function login_authentication()
{
if( $this->input->post(null) ){
//your authentication code here
}else{
//load the login view here
}
}
Here is your function:
function login_authentication(){
if( $this->input->post(null) ){ //check if there is an post request
$username=$this->input->post('username');
$password=$this->input->post('password');
$user = $this->administrator->admin_authentication($username,$password);
print_r( $user );die(); //the user array as returned from the model see if its correct or not
if(count($user) == 1)
{
foreach($user as $admin_value)
{
$user_name=$admin_value['UserName'];
$usertype=$admin_value['UserType'];
}
$session_data = array(
'username' => $user_name,
'usertype' => $usertype,
);
print_r( $session_data );die; //see if it builds the correct array or not
//$this->session->set_userdata($session_data);
$this->session->set_userdata('user_info',$session_data); //to read the username use like $this->session->userdata['user_info']['username'];
if($usertype == 1)
{
redirect('administrator/administrator_view');
}
}else{ //invalid credentials load the login view
$this->session->set_flashdata('Invalid_Login', 'Invalid username or password!'); //to echo in view use $this->session->flashdata('Invalid_Login');
redirect('administrator', 'refresh');
}
}else{ //redirect to index function now
redirect('administrator', 'refresh');
}
}
In your function administrator_view(),
function administrator_view(){
if( !$this->session->userdata('user_info') ){
print_r( $this->session->all_userdata() );die('no session set redirecting'); //the session is not set here
redirect('administrator');
}
else{
$data['heading'] = '';
$this->load->view('header', $data);
$this->load->view('dashboard', $data);
$this->load->view('footer');
}
}

Categories