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.
This is my controller
class login extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->helper('url','html');
$this->load->model('login_model');
}
public function index(){
$this->load->view('login');
}
public function verify_login()
{
$data = $this->login_model->verify_login();
if ($data) {
$userdata = array('id' => $data[0]['user_id'] , 'name' => $data[0]['full_name'], 'type' => $data[0]['user_type'] );
$this->session->set_userdata('login_info',$userdata);
if($userdata['type'] == 0) {
header("Location: ".base_url()."home");
}
else {
header("Location: ".base_url()."reports_controller");
}
}
else{
header("Location: ".base_url()."login");
}
}
public function logout(){
$this->session->sess_destroy('login_info');
header("Location: ".base_url()."login");
}
}
First you have to check what your session value will return,then you can restrict url.Use this to check your session
$session = $this->session->userdata('login_info');
$type = $session['type'];
Related
I am working on one role based login system. Actually, What should I do to the controller, model and the views in this role based login system to allocate different access criteria.
I am little confused about how to set and access for the user according to the role.
Mainly I am not sure about how to allocate different view as a role.
ex. I apply if condition to check role and then view according to the role the menu show the different links. like main admin can only watch account tab. the user can not see the account tab.
I also set the same if condition with the session in the controller for preventing direct access to that page.
Here is my code which I applied to menu and controller.
<?php
$login_role= $this->session->userdata('user_data');
if($login_role['user_role'] === 'super_admin'){
?><li><a href="<?php echo base_url('account/view_account'); ?>">
<div>Account</div></a></li><?php
}
?>
and the same condition in the controller
public function index()
{
$login_role= $this->session->userdata('user_data');
if($login_role['user_role'] === 'super_admin')
{
$this->load->model('location_model');
$city_list = $this->location_model->get_city_list();
$state_list = $this->location_model->get_state_list();
//log_message('info', 'City and State list will sucessfully loded.');
$this->load->view('admin/account_insert',['city_list'=>$city_list,'state_list'=>$state_list]);
} else {
redirect('admin/dashboard','refresh');
}
}
I am not sure about is this safe to use like this way. or I have to do something else as a good practice.
I am using a single Controller Login system for all user roles. I have a table of user roles and I have role id in users table. Then I have controller names matching those roles. When user login, I check for role and redirect the user to that controller after verification. Following is the index function of my Login Controller.
public function index()
{
if(!$this->isLoggedIn())
{
$data['title']='Title You want to set on Page';
if($_POST)
{
$config=array(
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'trim|required|valid_email',
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required',
),
);
$this->form_validation->set_rules($config);
if($this->form_validation->run()==false)
{
$data['errors']=validation_errors();
$this->load->view('static/head', $data);
$this->load->view('admin/login');
}
else
{
$user=$this->admin_model->checkUser($_POST);
if(!empty($user))
{
if($user['role']==1)
{
$user['type']='admin';
}
elseif($user['role']==2)
{
$user['type']='team';
}
elseif($user['role']==3)
{
$user['type']='client';
}
elseif($user['role']==4)
{
$user['type']='manager';
}
$this->session->set_userdata($user);
redirect(base_url().$user['type']);
}
else
{
$data['errors']='The credentials you have provided are incorrect or your account has not been approved yet.';
$this->load->view('static/head', $data);
$this->load->view('admin/login');
}
}
}
else
{
$this->load->view('static/head', $data);
$this->load->view('admin/login');
}
}
else
{
redirect(base_url().$this->session->userdata['type']);
}
}
Its working perfectly for me. Furthermore in each Controller I have functions to check if the user is logged in for this role like this
public function isLoggedIn()
{
if(!empty($this->session->userdata['id'])&& $this->session->userdata['type']=='team')
{
return true;
}
else
{
return false;
}
}
And I render my index function of that controller. E.g Following is the team controller index function
public function index()
{
if($this->isLoggedIn())
{
$data['menu']=$this->team_model->getMenuItems();
$data['task_logs']=$this->admin_model->getAllLogs();
$data['title']='Title';
$this->load->view('static/head',$data);
$this->load->view('static/header');
$this->load->view('static/sidebar');
$this->load->view('team/dashboard');
$this->load->view('static/footer');
}
else
{
redirect(base_url());
}
}
I have two controllers
1.Login
2.Dashboard
In Login controller I have two methods
1.logged_in()
2.logged_out()
This is my Login Controller
public function logged_in()
{
$user_email =$this->input->post('user_email');
$user_password =$this->input->post('user_password');
$result=$this->Login_model->login_data($user_email,$user_password);
if(!$result)
{
$this->session->set_flashdata('failure', 'Login failed');
redirect(BASE_URL.'admin/Login');
}
else
{
$data=array(
'user_email'=>$result[0]['user_email'],
'user_password'=>$result[0]['user_password'],
);
$this->session->set_userdata('session_data',$data);
$this->session->set_flashdata('success', 'Login sucessfully');
redirect(BASE_URL.'admin/Dashboard');
}
}
public function logged_out()
{
$this->session->unset_userdata('session_data');
$this->session->sess_destroy();
$this->session->set_flashdata('success', 'Logout sucessfully');
redirect(BASE_URL.'admin/Login');
}
And this is Dashboard controller :
class Dashboard extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
if($this->session->userdata('session_data')!='')
{
$this->load->view('admin/dashboard');
}
else
{
$this->session->set_flashdata('admin_flash', 'Try again');
redirect(BASE_URL."admin/Login");
}
}
}
I have a problem while after login it enters in my view which I have to load but the problem is that if I go back it goes to login page which i don't want.
so suggest me solution?
My idea is to make something like a boolean called logged by default false and set it true when the user log into the page and false if you log out. Then check if the user is login in the login page and if he's login redirect the user to the homepage
simply check whether user logged in or not in your login page. If user is already logged in, redirect him/her to dashboard.
In your code:
public function logged_in()
{
// check whether user is logged in or not,
// if yes redirect them to dashboard
if($this->session->userdata('session_data')!='')
{
redirect(BASE_URL."admin/dashboard");
}
$user_email =$this->input->post('user_email');
$user_password =$this->input->post('user_password');
$result=$this->Login_model->login_data($user_email,$user_password);
if(!$result)
{
$this->session->set_flashdata('failure', 'Login failed');
redirect(BASE_URL.'admin/Login');
}
else
{
$data=array(
'user_email'=>$result[0]['user_email'],
'user_password'=>$result[0]['user_password'],
);
$this->session->set_userdata('session_data',$data);
$this->session->set_flashdata('success', 'Login sucessfully');
redirect(BASE_URL.'admin/Dashboard');
}
}
view controller
<?php
class Site extends CI_Controller {
function homePage() {
$this->load->view('homePage');
}
function getValues($username) {
$this->load->model('customer_model');
$data['results']=$this->customer_model->getOne($username);
$this->load->view('view_db',$data);
}
}
I wanna display the logged in user details from database to a page. where the user logs in and it directs to home page and in that , there is link which directs to view the users details according to my design..
view Controller of login
<?php
class Login extends CI_Controller {
function index() {
//loads the main page to be displaye din the page
$this->load->view('login_form');
}
function validate_credentials() {
$this->load->model('customer_model');
$query = $this->customer_model->validate();
if ($query) {//if the user credidential is validated
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true
);
//retrieving the session data
$this->session->set_userdata($data);
redirect('site/homePage');
} else {
$this->index();
}
}
the model view--- i have mentioned only getting a specific user
function getOne($username){
$query=$this->db->query('SELECT * FROM customer WHERE username = $username');
//$this->db->select('*');
//$query= $this->db->get('customer');
return $query->result();
}
and the view.. where now i just wanna retrieve the value and check later i can improve the interface ;)
<?php
//print_r($results);
foreach($results as $row) {
echo $row->id;
echo $row->last_name;
echo "<br/>";
}
?>
i know it should be done through a session .. but how to do it?
Ok so when this person who is now logged in clicks on the link that brings them to the getValues() method. You can just do a check to see if they are logged in, then if they are retrieve their information based on the sessions username key.
function getValues(){
if ($this->session->userdata('is_logged_in')) {
$username = $this->session->userdata('username');
//Get your db results
$this->load->model('customer_model');
$data['results']=$this->customer_model->getOne($username);
$this->load->view('view_db',$data);
} else{
//What you want to happen when they are not logged in.
}
Does that make sense?
I don't want my users to be able to go to the login page if they are logged in. They have to log out first to be able to login. It seems simple enough, am i not understanding something correctly
class UsersController extends AppController {
public function isAuthorized($user) {
if( $this->Auth->login() ){
return false;
} else {
return true;
}
}
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl());
} else {
$this->Session->setFlash(__('Username or password is incorrect'), 'default', array(), 'auth');
}
}
}
There are also actions like register or lost password etc.
Basically you just check on blacklisted controller/actions and redirect to your home screen or login redirect accordingly
// Do not allow access to these public actions when already logged in
$allowed = array('Account' => array('login', 'lost_password', 'register'));
foreach ($allowed as $controller => $actions) {
if ($this->name === $controller && in_array($this->request->action, $actions)) {
$this->Common->flashMessage('The page you tried to access is not relevant if you are already logged in. Redirected to main page.', 'info');
return $this->redirect($this->Auth->loginRedirect);
}
}
See
https://github.com/dereuromark/cakefest/blob/master/Controller/AppController.php#L66
I use laravel, and in situations like that, my login route is filtered like this.
Route::get('login', array('before' => 'guest', "uses" => "SessionController#create"));
guest is the name of a filter, defined as return !Auth::check();
For CakePHP, I'd imagine it'd be pretty similar. Look for a way that you can filter your routes, based on if your current user is authenticated.
I have login controller in my CI app:
function index()
{
if($this->session->userdata('logged_in')==TRUE)
redirect('/success');
$data['error']=$this->session->flashdata('errormessage');
$this->load->view('auth',$data);
}
function process_login()
{
$username=$this->input->post('username');
$password=$this->input->post('password');
if($password == "good_pwd")
{
$data=array('username'=>$username,'logged_in'=>TRUE);
$this->session->set_userdata($data);
redirect('/success');
}
else
{
$this->session->set_flashdata('errormessage','Login failed');
redirect('/failed');
}
}
Thats my securing constructor in main controller:
function __construct()
{
parent::__construct();
if($this->session->userdata('logged_in')!=TRUE) redirect('/login');
}
When I'm trying to get into www.mysite.com/main/function1/ and I'm not logged in, then constructor redirects me into login page - when I log in correct I'm being redirected into main home page instead of page which redirected me into login page (in this example case: www.mysite.com/main/function1/ ) - how to do it?
you'd need to store your request URI in a session for this, so you can return to the previous page, something along the lines of:
function __construct()
{
parent::__construct();
if($this->session->userdata('logged_in')!=TRUE) {
$this->load->helper('url');
$this->session->set_userdata('last_page', current_url());
redirect('/login');
}
}
... you can then use session data to redirect back
Set the redirection url in the controller of the
$redirect_to = "where you want to redirect after login";
$this->session->set_userdata('redirect_to',$redirect_to);
Use Some thing like this in the User controller
$redirect_to = $this->input->post('redirect_to') ? $this->input->post('redirect_to') : $this->session->userdata('redirect_to');
$this->template->build('login', array(
'_user' => $user,
'redirect_to' => $redirect_to,
));