Codeigniter 3 redirect issue - php

I'm trying to redirect a not logged in user to a login page, using this code inside Codeigniter 3:
if ( !$this->aauth->is_loggedin() OR !$this->aauth->is_allowed("dashboard"))
{
redirect('auth/login', 'refresh');
}
else
{ //show stuff }
The codeigniter is installed on a subfolder called "admin".
I have the controller Auth.php and the method login exists, but still it doesn't work, the only thing I receive is a 404 Not found error
The routs.php file contains:
$route['default_controller'] = 'home';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
$route['admin'] = 'admin/dashboard';
$route['admin/prefs/interfaces/(:any)'] = 'admin/prefs/interfaces/$1';
And the auth controller :
class Auth extends MY_Controller {
function __construct()
{
parent::__construct();
$this->load->library("Aauth");
$this->form_validation->set_error_delimiters($this->config->item('error_start_delimiter', 'ion_auth'), $this->config->item('error_end_delimiter', 'ion_auth'));
$this->lang->load('auth', 'romanian');
}
function index()
{
if ( ! $this->aauth->is_loggedin() )
{
redirect('auth/login', 'refresh');
}
else
{
redirect('/', 'refresh');
}
}
function login()
{
$this->data['success'] = false;
if ($this->input->is_ajax_request()) {
if ($this->aauth->login($this->input->post('identity'), $this->input->post('password'))) {
$this->data['success'] = true;
} else {
$this->data['message'] = 'Utilizator sau parola gresite!';
}
echo json_encode($this->data);
die();
}
if ( ! $this->aauth->is_loggedin())
{
/* Load */
$this->load->config('admin/dp_config');
$this->load->config('common/dp_config');
/* Valid form */
$this->form_validation->set_rules('identity', 'Identity', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_rules('remember_me', 'Remember Me', 'optional');
/* Data */
$this->data['admin_assets'] = $this->config->item('admin_assets');
$this->data['title'] = $this->config->item('title');
$this->data['title_lg'] = $this->config->item('title_lg');
$this->data['auth_social_network'] = $this->config->item('auth_social_network');
$this->data['forgot_password'] = $this->config->item('forgot_password');
$this->data['new_membership'] = $this->config->item('new_membership');
if ($this->form_validation->run() == TRUE)
{
$remember = (bool) $this->input->post('remember');
//if ($this->ion_auth->login($this->input->post('identity'), $this->input->post('password'), $remember))
if ($this->aauth->login($this->input->post('identity'), $this->input->post('password'), $remember))
{
//if ( ! $this->ion_auth->is_admin())
if ( $this->aauth->is_allowed("dashboard"))
{
$this->session->set_flashdata('message', $this->ion_auth->messages());
redirect('/', 'refresh');
}
else
{
/* Data */
$this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
/* Load Template */
$this->template->auth_render('auth/choice', $this->data);
}
}
else
{
$this->session->set_flashdata('message', $this->ion_auth->errors());
redirect('auth/login', 'refresh');
}
}
else
{
$this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
$this->data['identity'] = array(
'name' => 'identity',
'id' => 'identity',
'type' => 'email',
'value' => $this->form_validation->set_value('identity'),
'class' => 'form-control',
'placeholder' => lang('auth_your_email')
);
$this->data['password'] = array(
'name' => 'password',
'id' => 'password',
'type' => 'password',
'class' => 'form-control',
'placeholder' => lang('auth_your_password')
);
/* Load Template */
$this->template->auth_render('auth/login', $this->data);
}
}
else
{
redirect('/', 'refresh');
}
}
function logout($src = NULL)
{
//$logout = $this->ion_auth->logout();
$logout = $this->aauth->logout();
//$this->session->set_flashdata('message', $this->ion_auth->messages());
if ($src == 'admin')
{
redirect('auth/login', 'refresh');
}
else
{
redirect('/', 'refresh');
}
}
}
Could someone point me to the correct way of redirecting to a specific page?

Try
$link = base_url()."auth/login";
header('Location: '.$link);
Instead of redirect. And don't forget to specify base url in codeigniter config
$config['base_url'] = "http://YOU-DOMAIN.com/YOUR-SUBDOMAIN/";

Related

Use form_validation correctly in CodeIgniter

I have a registration system with CodeIgniter but currently I have no control on email and password. A user can register without putting email or a password.
I have an index() and a register_user function() in my Signup controller but the redirection is not working on success
At the moment I have the following code:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Signup extends CI_Controller {
public function index()
{
if(!isset($this->session->userdata['sessiondata']['user_id']))
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required',
array('required' => 'You must provide a %s.')
);
if ($this->form_validation->run() == FALSE)
{
$this->load->view('signup-view');
}
else
{
$this->load->view('home-view');
}
}else{
if (intval($this->session->userdata['sessiondata']['user_type']) == 1) {
redirect(base_url().'admin');
} else {
redirect(base_url().'home');
}
}
}
function register_user(){
$this->load->library('custom_u_id');
$data = array('user_id' => $this->custom_u_id->construct_id('USR'),
'name' => $_POST['name'],
'email' => $_POST['email'],
'password' => $_POST['password'],
);
$this->load->model('signup_model');
$user_details = $this->signup_model->register_user($data);
if (!empty($user_details)){
$user_data = array
(
'user_id' => $user_details['user_id'],
'email' => $user_details['email'],
'name' => $user_details['name'],
'user_type' => $user_details['user_type'],
);
$this->session->set_userdata('sessiondata',$user_data);
if (intval($user_details['user_type']) == 1) {
redirect(base_url().'admin');
} else {
redirect(base_url().'home');
}
} else{
redirect('login');
}
}// end of function login
}
Do I need to put the form_validation in my register_user function ? I've tried but the check doesn't work anymore...
I also have in my view the <?php validation_errors();?> function and the <?php form_open(base_url().'signup');?>
looking by your code, i think you want to put register_user() inside validation TRUE since the query is in that method.
so try to change your code to this :
public function index()
{
if(!isset($this->session->userdata['sessiondata']['user_id']))
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required',
array('required' => 'You must provide a %s.')
);
if ($this->form_validation->run() == FALSE)
{
$this->load->view('signup-view');
}
else
{
$this->register_user();
}
}else{
if (intval($this->session->userdata['sessiondata']['user_type']) == 1) {
redirect(base_url().'admin');
} else {
redirect(base_url().'home');
}
}
}
and be sure your form action to like this :
<form action="<?=site_url('/signup/index');?>">

php / codeigniter redirect user based on group membership

I have this login php file from a CodeIgniter based PHP app. Basically I want to edit this so that if the user is member of "salesman" group then redirect them to another page. This will just be for this group others will redirect as normal and wont be effected.
Presume I need to add in an If at some part.
class Auth extends MX_Controller {
function __construct()
{
parent::__construct();
$this->load->library('ion_auth');
$this->load->library('session');
$this->load->library('form_validation');
$this->load->helper('url');
// Load MongoDB library instead of native db driver if required
$this->config->item('use_mongodb', 'ion_auth') ?
$this->load->library('mongo_db') :
$this->load->database();
}
//redirect if needed, otherwise display the user list
function index()
{
if (!$this->ion_auth->logged_in())
{
redirect('module=auth&view=login');
} else {
redirect('module=home');
}
}
function users() {
$groups = array('admin', 'purchaser', 'salesman', 'viewer');
if ($this->ion_auth->in_group($groups))
{
$this->session->set_flashdata('message', $this->lang->line("access_denied"));
$data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));
redirect('module=home', 'refresh');
}
$this->user_check();
$data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
$data['success_message'] = $this->session->flashdata('success_message');
//list the users
$data['users'] = $this->ion_auth->users()->result();
foreach ($data['users'] as $k => $user)
{
$data['users'][$k]->groups = $this->ion_auth->get_users_groups($user->id)->result();
}
$meta['page_title'] = 'Users';
$this->load->view('commons/header', $meta);
$this->load->view('index', $data);
$this->load->view('commons/footer');
}
//log the user in
function login()
{
$data['title'] = "Login";
//validate form input
$this->form_validation->set_rules('identity', 'Identity', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == true)
{ //check to see if the user is logging in
//check for "remember me"
$remember = (bool) $this->input->post('remember');
if ($this->ion_auth->login($this->input->post('identity'), $this->input->post('password'), $remember))
{ //if the login is successful
//redirect them back to the home page
$this->session->set_flashdata('success_message', $this->ion_auth->messages());
redirect('module=home', 'refresh');
}
else
{ //if the login was un-successful
//redirect them back to the login page
$this->session->set_flashdata('message', $this->ion_auth->errors());
redirect('module=auth&view=login', 'refresh'); //use redirects instead of loading views for compatibility with MY_Controller libraries
}
}
else
{ //the user is not logging in so display the login page
//set the flash data error message if there is one
$data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
$data['success_message'] = $this->session->flashdata('success_message');
$data['identity'] = array('name' => 'identity',
'id' => 'identity',
'type' => 'text',
'value' => $this->form_validation->set_value('identity'),
);
$data['password'] = array('name' => 'password',
'id' => 'password',
'type' => 'password',
);
$this->load->view('auth/login', $data);
}
}
This condition will catch the logged in user's group and, if they are salesman, redirect them to to/whatever/page.
if ($this->ion_auth->in_group(array('salesman')))
redirect('to/whatever/page');
}

How to validate Session in codeigniter?

I am trying to create a session in Codeigniter. I have loaded session and encrypt library in autoload. By default the login.php page opens. I want to open the dashboard.php page, if the user is already logged in. I have written the following code, but it opens the login.php page, even after login.
Kindly tell me how to check if the session is already set or not.
public function index()
{
$data['products_data']= $this->products_model->all_products();
// $this->load->view('login');
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password','Password','required');
if ($this->form_validation->run()== false)
{
$this->load->view('login');
}
else
{
if ($this->session->userdata('login_status')) {
$this->load->view('header');
$this->load->view('dashboard');
$this->load->view('footer');
}
else
{
$username= $this->input->post('username');
$password= $this->input->post('password');
if( $this->products_model->login_model($username,$password))
{
$sess_data= array(
'username'=> $username,
'login_status'=>'1'
);
$session_data = $this->session->set_userdata($sess_data);
$this->load->view('header');
$this->load->view('dashboard');
$this->load->view('footer');
}
}
}
}
$sessdata = $this->session->set_userdata($session_data);
if (isset($sessdata))
{
//session exists
}
else{
// no session value
}
So Your controller should look like below to avoid redirecting to login page on page refresh,
function index() {
if ($this->session->userdata('login_status')) {
//write your code for redirect to dashboard
} else {
$data['products_data'] = $this->products_model->all_products();
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == false) {
$this->load->view('login');
} else {
$username = $this->input->post('username');
$password = $this->input->post('password');
if ($this->products_model->login_model($username, $password)) {
$sess_data = array(
'username' => $username,
'login_status' => '1'
);
$session_data = $this->session->set_userdata($sess_data);
//write your code for redirect to dashboard
}
}
}
}
Remove the single qoutes on
$this->session->set_userdata('$sess_data');
it is treating the variable $sess_data as a regular string.
must be:
$this->session->set_userdata($sess_data);
I rather like to create another controller for dashboard and redirect it to there after successful login. It is clean and you can do further changes easily
if( $this->products_model->login_model($username,$password))
{
$sess_data= array(
'username'=> $username
);
$session_data = $this->session->set_userdata($sess_data);
if(isset($session_data))
redirect(site_url('/dashboard/'));
}
FM: $sess_data should not be in single quotes
I will use session to record login status.
$session_data= array(
'username'=> $username,
'lgoin_status' => 1
);
$this->session->set_userdata('$session_data');
And I will check session's login_status
if ($this->session->userdata('login_status')) {
// do something
}
Edit
On your code, you should check session at first, so..
public function index()
{
if ($this->session->userdata('login_status'))
{
// do something
}
else
{
$data['products_data']= $this->products_model->all_products();
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password','Password','required');
if ($this->form_validation->run()== false)
{
$this->load->view('login');
}
...
}

Registration with CodeIgniter Ion Auth

I am trying to register a user with Ion Auth, but the register() function does not seem to report any error messages. How does one register with Ion Auth? I've already read various tutorials like this one and this one (and the documentation), but they do not seem to be working.
function register()
{
// do not allow registration if logged in
if ($this->ion_auth->logged_in())
{
redirect('/');
}
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|callback_email_check');
$this->form_validation->set_rules('email2', 'Email Confirmation', 'trim|required|valid_email|matches[email]');
$this->form_validation->set_rules('password', 'Password', 'trim|required|md5');
if ($this->form_validation->run() == FALSE)
{
$this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
$this->load->view('header');
$this->load->view('register', $this->data);
$this->load->view('footer');
}
else
{
$username = $this->input->post('email');
$password = $this->input->post('password');
$email = $username;
$additional_data = array(
'first_name' => $this->input->post('name'),
'last_name' => '',
);
if (!$this->ion_auth->email_check($email))
{
$group_name = 'users';
$uId = $this->ion_auth->register($username, $password, $email, $additional_data, $group_name);
if ($uId == FALSE)
{
$this->session->set_flashdata('message', $this->ion_auth->errors());
redirect("home/register", 'refresh');
}
else
{
redirect('/'); // registration success
}
}
}
}
function email_check($str)
{
if ($this->ion_auth->email_check($str))
{
$this->form_validation->set_message('email_check', 'This email is already registered.');
return FALSE;
}
return TRUE;
}

Unable to change Identity to 'username' in Codeigniter Ion Auth?

I have installed ion auth and everything is up and functional. The only problem I have is I want to change the login to use the visitors username instead of e-mail. I change the CONFIG option in the ion_auth.php config file and it still doesnt work. Is there an extra step Im missing??
ion_auth config
/**
* A database column which is used to
* login with.
**/
$config['identity'] = 'username';
login() in the controller
//log the user in
function login()
{
$this->data['title'] = "Login";
//validate form input
$this->form_validation->set_rules('email', 'E-mail Address', 'required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == true)
{ //check to see if the user is logging in
//check for "remember me"
$remember = (bool) $this->input->post('remember');
if ($this->ion_auth->login($this->input->post('email'), $this->input->post('password'), $remember))
{ //if the login is successful
//redirect them back to the home page
$this->session->set_flashdata('message', $this->ion_auth->messages());
redirect($this->config->item('base_url'), 'refresh');
}
else
{ //if the login was un-successful
//redirect them back to the login page
$this->session->set_flashdata('message', $this->ion_auth->errors());
redirect('auth/login', 'refresh'); //use redirects instead of loading views for compatibility with MY_Controller libraries
}
}
else
{ //the user is not logging in so display the login page
//set the flash data error message if there is one
$this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
$this->data['email'] = array('name' => 'email',
'id' => 'email',
'type' => 'text',
'value' => $this->form_validation->set_value('email'),
);
$this->data['password'] = array('name' => 'password',
'id' => 'password',
'type' => 'password',
);
$this->load->view('auth/login', $this->data);
}
}
login() model
public function login($identity, $password, $remember=FALSE)
{
if (empty($identity) || empty($password) || !$this->identity_check($identity))
{
return FALSE;
}
$query = $this->db->select($this->identity_column.', id, password, group_id')
->where($this->identity_column, $identity)
->where('active', 1)
->where($this->ion_auth->_extra_where)
->limit(1)
->get($this->tables['users']);
$result = $query->row();
if ($query->num_rows() == 1)
{
$password = $this->hash_password_db($identity, $password);
if ($result->password === $password)
{
$this->update_last_login($result->id);
$group_row = $this->db->select('name')->where('id', $result->group_id)->get($this->tables['groups'])->row();
$session_data = array(
$this->identity_column => $result->{$this->identity_column},
'id' => $result->id, //kept for backwards compatibility
'user_id' => $result->id, //everyone likes to overwrite id so we'll use user_id
'group_id' => $result->group_id,
'group' => $group_row->name
);
$this->session->set_userdata($session_data);
if ($remember && $this->config->item('remember_users', 'ion_auth'))
{
$this->remember_user($result->id);
}
return TRUE;
}
}
return FALSE;
}
Why are you still processing email in the controller (instead of username)?
You need to change your controller since it is still grabbing email from POST and using it to try to login.
You should add an index in the users table of username column

Categories