authorization in codeigniter - php

I'm working with codeigniter, I'm doing an auth system - user can log in, he can see all pages, after he can log out. The problem is next: why logged out user can see all pages without to be logged in. how can I correct it? This is my controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('url', 'form'));
$this->load->model("usermodel");
$this->load->library('session');
}
private function view($page, $data=false) {
if($page == "auth/login" ){
$this->load->view("auth/header_auth.php");
}else{
$this->load->view("header.php");
}
$this->load->view($page, $data);
$this->load->view("footer.php");
}
public function index() {
if ($this->session->userdata("user")) {
redirect("dashboard", "refresh");
return;
}
$this->view("auth/login");
}
public function fail() {
$this->view("auth/login");
}
public function dashboard() {
$this->view("auth/dashboard");
}
public function login() {
$login = $this->input->post("login");
$password = $this->input->post("password");
if ($this->usermodel->login($login, $password)) {
$this->session->set_userdata("user", $login);
redirect("dashboard", "refresh");
} else {
redirect("fail", "refresh");
}
}
public function logout() {
$this->session->unset_userdata('user');
session_destroy();
redirect('index', 'refresh');
}
}

you must check if user is logged in at beginning of each function which must have user privileges to view
if (!$this->session->userdata("user")) {
redirect("auth/login", "refresh");
}
I am assuming that your view function can only be viewed if a user is logged in, change
private function view($page, $data=false) {
if($page == "auth/login" ){
$this->load->view("auth/header_auth.php");
}else{
$this->load->view("header.php");
}
$this->load->view($page, $data);
$this->load->view("footer.php");
}
to this
private function view($page, $data=false) {
if (!$this->session->userdata("user")) {
redirect("auth/login", "refresh");
}
if($page == "auth/login" ){
$this->load->view("auth/header_auth.php");
}else{
$this->load->view("header.php");
}
$this->load->view($page, $data);
$this->load->view("footer.php");
}
Update
also your dashboard can be viewed by everyone, to make it viewable only by logged in user do this:
public function dashboard() {
if (!$this->session->userdata("user")) {
redirect("auth/login", "refresh");
}
$this->view("auth/dashboard");
}

Related

Codeigniter can't login into home admin

Here is the controller, when I click the login button, nothing happens. What I want is to load the success screen when user data is validated and show error messages when user data is not validated.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller {
function __construct(){
parent::__construct();
}
public function index() {
$this->load->view('login');
}
function getlogin() {
$user = $this->input->post('username');
$pass = $this->input->post('password');
$user = $this->auth->log_admin($user,$pass);
if($user==true){
$this->session->set_userdata($user);
$data['hasil']=1;
echo json_encode($data);
}else{
$data['hasil'] = 0;
echo json_encode($data);
}
}
function logout(){
//helper_log("logout", "Logout");
$this->session->sess_destroy();
redirect('Login','refresh');
}
}
Here the log_admin
function log_admin($user,$pass)
{
$cek=$this->CI->db->where('admin_user',$user)
->where('admin_password',md5($pass))
->get('admin')
->row();
$row=count($cek);
if ($row==1) {
return $cek;
} else {
return false;
}
}
you can redirect the page from the controller, something like this.
after validating the user, it will redirect to your desired page.
function getlogin() {
$user = $this->input->post('username');
$pass = $this->input->post('password');
$user = $this->auth->log_admin($user,$pass);
if($user==true){
$this->session->set_userdata($user);
redirect('go to the next page');
}else{
$data['hasil'] = 0;
echo json_encode($data);
}
}

How to stop redirecting logged-in user to login page when pressing back button in php codeigniter

I have a login for with username and password , after the user logged in , the user redirect to dashboard , and if the user press the back button of browser it will redirect the user to login page , while i want to redirect the user to dashboard as is already logged-in.i would appreciate if anyone can help me to implement that.
Here is my login. php controller
<?php
class Login extends CI_controller {
public function __construct()
{
parent::__construct();
$this->load->library('form_validation');
$this->load->library('encrypt');
$this->load->model('login_model');
}
function index()
{
//echo CI_VERSION; die;
//echo $this->encrypt->encode('123456');
//echo "<br>".$this->encrypt->decode('ADxTYFI1ATFSYwFn');
//die;
$this->load->view('login');
}
function validation()
{
// print_r($_REQUEST);
// die;
$this->form_validation->set_rules('username', 'Username', 'required|trim' );
$this->form_validation->set_rules('password' , 'Password' , 'required');
if ($this->form_validation->run())
{
$res = $this->login_model->can_login($this->input->post('username'), $this->input->post('password'));
if(is_array($res)){
$stored_password = $res['stored_password'];
$row = $res['row'];
if(password_verify($this->input->post('password'),$stored_password)){
$userID = $row->id;//die;
$this->session->set_userdata('admin',$userID);
redirect('admin/dashboard');
}else{
$this->session->set_flashdata ('message','Invalid Credentils');
redirect('admin/login');
}
}else{
$this->session->set_flashdata ('message','Invalid Credentils');
redirect('admin/login');
}
}
else
{
$this->index();
}
}
}
And here is my login_model.php
<?php
class Login_model extends CI_Model
{
function can_login($username, $password)
{
$this->db->where('username', $username);
$query = $this->db->get('user_login');
if($query->num_rows() > 0)
{
$result = $query->row();
//print_r($result);die;
$stored_password = $result->password;
$return = array('stored_password'=> $stored_password , 'row' => $result);
return $return;
}
else
{
return FALSE;
}
}
And here is my dashboard.php controller
<?php
class Dashboard extends CI_Controller
{
function __construct()
{
parent::__construct();
if(!$this->session->userdata('admin'))
redirect('admin');
// else{
// redirect('admin/dashboard');
// }
}
function index()
{
$this->load->view('admin/dashboard');
}
function logout()
{
$this->session->sess_destroy();
redirect('admin');
}
}
Solved,
I solved the problem by adding session in my login.php controller
public function __construct()
{
parent::__construct();
if($this->session->userdata('admin'))
redirect('dashboard');
$this->load->library('form_validation');
$this->load->library('encrypt');
$this->load->model('login_model');
}

CodeIgniter Log Out Could still access the page after logging out when back button is clicked or typed a shortcut link

Hi Everyone i asking if how i can resolved this kind of problem. the problem is when i clicked the back button after logging out the user can still access the page or by typing the link of the page. i thought if i can destroy the session it will automatically disabled those pages..
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Auth extends MY_Controller {
public function index(){
$this->data['page_title'] = "User Login";
$this->load->view('templates/master', $this->data);
}
public function login(){
$username = $_POST['username'];
$password = $_POST['password'];
$data = $this->User_model->login ($username, $password);
if($data){
$this->session->set_userdata('users', $data);
$session_data = array(
'username' => $username);
$this->session->set_userdata($session_data);
redirect('users');
}
else{
$this->session->set_flashdata
('loginfail','<div class="alert alert-danger">×
<strong>Danger !</strong> Invalid Email or Password .</div>');
return redirect("auth");
}
}
public function logout()
{
$this->session->unset_userdata(array('username','id'));
$this->session->sess_destroy();
redirect('auth');
}
}
<a href="<?php echo ('auth/logout')?>" data-toggle="modal" data-target="#logoutModal">
<i class="fas fa-sign-out-alt fa-sm fa-fw mr-2 text-gray-400"></i>
Logout
</a>
My Homepage controller Code
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Users extends MY_Controller {
function __construct() {
if(empty($this->session->userdata('id'))){
redirect('auth/logout');
}
}
public function index()
{
$this->data['page_title'] = "Users List";
$this->data['users'] = $this->User_model->get();
$this->load->view('templates/master', $this->data);
}
public function add()
{
$this->data['page_title'] = "Add User";
$input_data = $this->input->post();
if(!empty($input_data))
{
$this->User_model->insert($input_data);
redirect('/users');
} else {
$this->load->view('templates/master', $this->data);
}
}
public function edit($id)
{
$this->data['page_title'] = "Edit User";
$input_data = $this->input->post();
if(!empty($input_data)){
$this->User_model->update($input_data);
redirect('/users');
} else {
$this->data['users'] = $this->User_model->get($id);
$this->load->view('templates/master', $this->data);
}
}
public function delete($id)
{
$this->User_model->delete($id);
redirect('/users');
}
}
My Core Controller Code
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class MY_Controller extends CI_Controller {
protected $data;
public function __construct()
{
parent::__construct();
define('CONTROLLER', $this->router->fetch_class());
define('METHOD', $this->router->fetch_method());
}
}
Yes, you must log out of the user session. And you have to check the user session in the constructor of a controller.
Example:
class Users extends MY_Controller {
function __construct() {
if(empty($this->session->userdata())){
redirect('LOGIN_CONTROLLER');
}
}
}
logout and login works fine...
but you have to restrict or privilege your functions
example
public function isLoggedIn() {
if ($this->session->userdata('uId') == TRUE) {
return true;
} else {
return false;
}
}
public function index() {
$status = $this->session->userdata('uStatus');
if ($this->isLoggedIn() == TRUE && $status == "1") {
//your code here
} else {
$this->session->set_flashdata('error', 'You have to login first');
redirect('login');
}
}
You should redirect
if(empty($this->session->userdata('id'))){
redirect('LOGIN_CONTROLLER/METHOD_NAME_HERE');
}

CodeIgniter - How do I get session to detect whether user is logged in?

I have very simple page that requires login to view. I have a login controller and view that will redirect to the main page after successful login. However, i want to detect whether user is logged in if the user directly access the main page link, if not logged in, then the user should be redirect back to the login page.
My Login controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller {
public function index()
{
$this->load->view('login_view');
}
public function process()
{
$user = $this->input->post('user');
$pass = $this->input->post('pass');
if ($user=='admin' && $pass=='123')
{
$this->session->set_userdata(array('user'=>$user));
redirect("Report");
}
else{
$data['error'] = 'Your Account is Invalid';
$this->load->view('login_view', $data);
}
}
public function logout()
{
$this->session->unset_userdata('user');
redirect("Login");
}
}
?>
and my Login view:
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<?php echo isset($error) ? $error : ''; ?>
<form method="post" action="<?php echo base_url('Login/process'); ?>">
<table cellpadding="2" cellspacing="2">
<tr>
<td><th>Username:</th></td>
<td><input type="text" name="user"></td>
</tr>
<tr>
<td><th>Password:</th></td>
<td><input type="password" name="pass"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Login"></td>
</tr>
</table>
</form>
</body>
</html>
while the login process is working good, but i'm not sure how to get the session from my main page to detect whether user is logged in. I know i should add some validation in the main controller but i'm not sure how, please help thank you.
main controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class EstoreReport extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('ReportModel');
}
public function index()
{
$report=new ReportModel;
$data['data']=$report->get_report();
$this->load->view('includes/header');
$this->load->view('Report/list',$data);
$this->load->view('includes/footer');
}
You can create a function and call it to check whether the user is logged in or not
public function is_logged_in()
{
$user = $this->session->userdata('user_data');
return isset($user);
}
Assuming you have session helper autoloaded, just like validation on the Login controller, you could set the validation in the index method of the Main / Report controller :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class EstoreReport extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('ReportModel');
}
public function index()
{
if (!isset($this->session->userdata('user'))) {
redirect("Login");
} else {
$report=new ReportModel;
$data['data']=$report->get_report();
$this->load->view('includes/header');
$this->load->view('Report/list',$data);
$this->load->view('includes/footer');
}
}
You could use $this->session->has_userdata() as per CI docs
So
// Write a boolean returning method
/**
* Returns if there is a user session
*
* #return bool
*/
public function isLoggedIn()
{
return $this->session->has_userdata($some_defined_key_like_user_id);
}
...
// Then in your index controller method
/**
* Index controller method
*
* #return void
*/
public function index()
{
$this->isLoggedIn() ? $this->load()->view('login') : redirect("Report");
}
Just simple configure in your controller index():
Use $this->session->userdata('user') == NULL to check whether user is logged in
public function index()
{
if($this->session->userdata('user') == NULL)
{
redirect('Login');
}
else
{
$report=new ReportModel;
$data['data']=$orders->get_report();
$this->load->view('includes/header');
$this->load->view('Report/list',$data);
$this->load->view('includes/footer');
}
}
Try this
class Login extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('loginmodel', 'login');
$this->load->library('form_validation');
}
public function index() {
$this->load->view('admin/login');
}
// Check for user login process
public function user_aouth() {
$this->form_validation->set_rules('username', 'Username', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if ($this->form_validation->run() == FALSE) {
$this->session->set_flashdata('error', 'Invalid Username and Password');
redirect('login');
} else {
$username = $this->input->post('username');
$password = $this->input->post('password');
$data = array(
'username' => $username,
'password' => $password
);
if ($this->login->check_valid_user_details($data)) {
$session_data = array(
'username' => $username
);
$this->session->set_userdata($session_data);
//redirect to admin user dashboard
redirect('dashboard');
} else {
$this->session->set_flashdata('error', 'Invalid Username and Password');
redirect('login');
}
}
}
public function logout() {
$this->session->unset_userdata('username');
$this->session->sess_destroy();
redirect('login');
}
}
In your login model
public function check_valid_user_details($data) {
$condition = "username=" . "'" . $data['username'] . "'" . "AND password=" . "'" . $data['password'] . "'";
$c = $this->db->select('*')
->from('admin')
->where($condition)
->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->result();
} else {
return FALSE;
}
}
Use this at the top of every page under dashboard
if($this->session->userdata('username') == NULL){
redirect('login');
}
controller
public function index()
{
//redirect to dashboard
$this->dashboard();
}
public function dashboard()
{ //session wise operating isset session-> dashboard ,else login page
if ($this->session->userdata('userName')) {
//if user found
return $this->load->view('dashboard');
} else {
//if "no user found"
return $this->load->view('login');
}
}
public function login_check()
{ //functions retrives two values 1-user type 2-userId
$data['userdata'] = $this->Mdl_login->Login_check();
if ($data['userdata'] == false) {
$this->load->view('login', $data);
} else {
redirect(base_url('index.php/dashboard'), 'refresh');
}
}
function logout()
{ //session destroy function
$this->session->unset_userdata('userName');
redirect(base_url(), 'refresh');
}
Model
function Login_check()
{
$username = $this->input->post('UserName');
$password = $this->input->post("PassWord");
//check with your value
$this->db->where('userName', $username);
$this->db->where('password', $password);
$qry_getuserdata = $this->db->get('user_tbl');
if ($qry_getuserdata->num_rows() > 0) {
$result = $qry_getuserdata->result();
$userid = $result[0]->userId;
$usertype = $result[0]->userType;
$email = $result[0]->email;
$this->session->set_userdata('userName', $username);
$this->session->set_userdata('userId', $userid);
$this->session->set_userdata('userType', $usertype);
$this->session->set_userdata('email', $email);
return true;
} else {
return false;
}
}
Now you can access your session data anywhere
if(isset($_SESSION['userName'])){ $data['userName']= $_SESSION['userName']; }
You can have true or false from below function call, Call this function in your controller and then redirect as per the response.
$this->session->userdata( 'logged_in' );

How to check whether or not the user is n admin instead of a normal user for all my admin functions?

First off, heres my code:
<?php
class Admin extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('admin_model');
}
function logout()
{
$this->session->unset_userdata('logged_in');
session_destroy();
redirect('home', 'refresh');
}
public function index()
{
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
if ($session_data['id'] != 1){
$this->load->view('head');
echo "Sorry, you have to be an administrator to access this page";
$this->load->view('footer');
} else {
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
$this->load->view('head');
$this->load->model('admin_model');
$data['users'] = $this->admin_model->show_data();
$data['bikes'] = $this->admin_model->show_bikes();
$this->load->view('admin', $data);
$this->load->view('footer');
}
} else
{
redirect('login', 'refresh');
}
}
The dilemma I'm in is, yes this will stop all normal users accessing the admin/index page. However they still will be able to access admin/create, admin/update and so on unless i put an if statement on all the functions which will take some time. Is there a quicker way (possibly something i could put in the construct) that will apply the check to all the admin pages? Thanks
Simply move your admin-check code to the constructor:
<?php
class Admin extends CI_Controller {
public function __construct()
{
parent::__construct();
if(!$this->session->userdata('logged_in')) {
redirect('login', 'refresh');
}
if ($session_data['id'] != 1){
$this->load->view('head');
echo "Sorry, you have to be an administrator to access this page";
$this->load->view('footer');
exit; // or return? sorry, not too familiar w/ CodeIgniter
}
$this->load->model('admin_model');
}
...
public function index()
{
...
}

Categories