Codeigniter user form errors not showing - php

On my codeigniter login. If user types in incorrect user name it should display error saying Username or Password Incorrect as flash-data. And if user puts in username that does not exist then would throw error Username Not Match Any Records.
Cannot get the form database check errors to display correct way. I can login OK but just not throwing login flash-data errors correct.
How can I get my form database errors to work correct. The main codeigniter form validation are OK just not throwing my database errors.
public function index() {
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required|trim');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == FALSE) {
$this->login();
} else {
if ($this->input->post('username') && $this->input->post('password')) {
// Gets the user information from the database.
$user = $this->user_login_model->get('username', $this->input->post('username'));
if ($user) {
// If User Login Success
if ($this->user_login_model->check_password($this->input->post('password'), $user['password']) == TRUE) {
$this->user->login($user['user_id']);
redirect('admin/dashboard');
} else {
$this->session->set_flashdata('error', 'Username or Password Is Does Not Match Any Records!');
$this->login();
}
}
}
}
}
public function login() {
$this->document->setTitle($this->lang->line('heading_title'));
$data['text_login'] = $this->lang->line('text_login');
$data['text_register'] = $this->lang->line('text_register');
$data['entry_username'] = $this->lang->line('entry_username');
$data['entry_password'] = $this->lang->line('entry_password');
$data['action'] = site_url('admin');
$data['button_login'] = $this->lang->line('button_login');
return $this->load->view('common/login', $data);
}
Get User model
/**
* Retrieve a user
*
* #param string where
* #param int value
* #param string user_identification field
*/
public function get($where, $value = FALSE) {
if (!$value) {
$value = $where;
$where = 'user_id';
}
$user = $this->db->where($where, $value)->get($this->table)->row_array();
return $user;
}

Flashdata will only be shown if the user is redirected to another page.
On the failed login action you only load a view to the user's screen. Try altering
$this->login();
to
redirect('controller/login'); //ofc change the controller name first

Related

Login in CodeIgniter with password_verify

I'm trying to achieve to login implementation in CodeIgniter, I'm hashing password while registration like password_hash($this->input->post('password'),PASSWORD_DEFAULT) in my Controller and in the same Controller I'm trying to write a login method which is as followed :
public function loginValidation() {
$this->form_validation->set_rules('email', 'Email', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if ($this->form_validation->run()) {
// true
$email = $this->input->post('email');
$password = $this->input->post('password');
// User Model Loaded in constructor
if ($this->user->canLogin($email, $password)) {
$session_data = array('email' => $email );
$this->session->set_userdata($session_data);
redirect('profile/personal','Refresh');
} else {
$this->session->set_flashdata('error', 'Invalid Username or Password');
//redirect('login','Refresh');
}
} else {
// try again to login
//redirect('login','Refresh');
}
}
My user Model function is
public function canLogin($email, $password) {
$this->db->where('email',$email);
$this->db->where('password',$password);
$query = $this->db->get($this->tableName);
if ($query->num_rows() > 0) {
return true;
} else {
return false;
}
}
I know I have to password_verify($string,$hash) at some point but I'm unable to figure out.
How do I validate the password against email and redirect to the desired view i.e. personal/profile and I'm making request via AJAX call.
What you need to do is fetch the record from the DB where only the email matches (assuming it is the Unique key). Then you compare the returned value using password_verify().
This is very rough and untested, but should give you an idea:
public function canLogin($email, $password) {
$this->db->where('email',$email);
// $this->db->where('password',$password);
$query = $this->db->get($this->tableName);
$row = $query->row();
return $row ? password_verify($password, $row->password) : false;
}

I get error when i login to my project and then go back to the base url

I'm getting error when login to my project and then goto the base url. The below is the error which i get
My Login page [ see the url ]
After logging in , if i remove the highlighted segments[pls see below image] after which i get the above error
I know these error are due to headers so can somebody help me in saying what error am i making in header. An also say how to make good use of session so that the form is to resubmitted when i refresh after logging in. Below are the header codes.
login header
<?php if(isset($this->session->userdata['logged'])){
header("location: http://localhost/capacity_planner/login/login_check");
}
?>
admin dashboard[after logging in header]
<?php if(isset($this->session->userdata['logged'])){
$email = ($this->session->userdata['logged']['email']);
}else{
header("location: http://localhost/capacity_planner/login");
}
?>
controller side
public function login_check(){
$data['base_url'] = base_url();
$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
if ($this->form_validation->run($this) == false) {
$this->index();
} else {
if(isset($this->session->userdata['logged'])) {
$data['login_bg'] = $this->input->post('login_bg');
$this->load->view("admin_db", $data);
}
}
function check_database($password){
$email= $this->input->post('email');
$user = $this->user->loginCheck($email, $password);
if($user[1] == 1){
$result = $this->user->user_details($email);
if($result != false) {
$session_data = array(
'id' => $result[0]->id,
'email' => $result[0]->cp_email,
);
$this->session->set_userdata('logged', $session_data);
return true;
}
} else{
$this->form_validation->set_message('check_database', $user[0]);
return false;
}
}
ERR_TOO_MANY_REDIRECTS is caused when strucked up in a conditional loop
I assume you want to redirect to admin dashboard if you go to index after logged in..
Try adding these lines in your public function index()
public function index(){
if(isset($this->session->userdata['logged'])) {
//admin_db display function eg.redirect('admindashboard');
}
else{
//load your index view
this->load->view('your_index_view');
}
}
or you can check reverse way in admin dashboard function like this
public function dashboard(){
if($this->session->userdata('logged') == ''){
redirect('index');
}
else{
$this->load->view('dashboard view');
}
}
This is my assumption.Kindly check it.

Form Validation Call Back Function Not Working

Here Is My COde I m checking username is already exist or not in datbase
when i validate and submit the form duplicate entry entered in database i want that if already exist it show validation error
My Controller
public function index()
{
if($this->input->post('submit')) {
$this->form_validation->set_rules('name', 'User Name', 'callback_checkuser');
$this->form_validation->set_rules('role', 'Role', 'trim|required');
$this->form_validation->set_rules('pass', 'Password', 'trim|required');
if($this->form_validation->run()==TRUE)
{
$user['u_name'] = $this->input->post('name');
$user['role'] = $this->input->post('role');
$user['password']= md5($this->input->post('pass'));
$u_id = $this->custom_model->add_user($user);
if($u_id){
$data['msg'] = 'Successfully Created!!!!';
}
}
}
$this->load->template('add_user', $data);
}
function checkuser($name) {
if($this->custom_model->check_name($name) == false) {
false;
}else {
$this->form_validation->set_message('checkuser', 'This user already exist');
return true;
}
}
Here is My Model
public function check_name($name) {
$sql = "SELECT * FROM users WHERE u_name='".$name."' ";
$query = $this->db->query($sql);
$res = $query->row_array();
if (is_array($res) && count($res) > 0){
return $res;
}
return false;
}
There is a return statement missing in the function checkuser, but more importantly, you should invert the value you return. According to the example in the docs, when you set a validation message because of a validation error, you should return false, and return true when the validation passes.
So add a return, and change the boolean values. BTW, you don't really need an else clause and the word "exist" needs an additional "s":
function checkuser($name) {
if ($this->custom_model->check_name($name) == false) {
return true; // the user does not yet exist, so all is OK
}
$this->form_validation->set_message('checkuser', 'This user already exists');
return false; // this is a duplicate user name: not OK
}
Use this:
$this->form_validation->set_rules('name', 'User Name', 'trim|required|is_unique[users.u_name]');// trim and required added too
Docs.

Managing two roles in codeigniter

I have two roles, the admin and the teacher. The admin and teacher accounts can login however when I logged in the teacher account it will redirect to admin page. I don't know if my code is right as well. I'm a newbie at using codeigniter so please bear with me.
So here's my controller:
public function login_validation(){
$this->load->library('form_validation');
$this->form_validation->set_rules('idnum', 'ID Number', 'required|trim|xss_clean|callback_validate_credentials');
$this->form_validation->set_rules('password', 'Password', 'required|md5|trim');
if ($this->form_validation->run()){
//$this->load->model('model_users');
$this->load->model('model_role');
$data = array(
'login_id' => $this->input->post('idnum'),
'is_logged_in' => 1,
'role' => $this->model_role->scalar('user_account','role')
);
$this->session->set_userdata($data);
redirect('site/members');
} else {
$data['title'] = "Outcome-based Education";
$this->load->view("index/header", $data);
$this->load->view("index/view_home");
$this->load->view("index/footer");
}
}
public function members(){
if($this->session->userdata('is_logged_in') && $this->session->userdata('role', 'admin')){
$this->load->view('login/admin');
} elseif($this->session->userdata('is_logged_in') && $this->session->userdata('role', 'teacher')){
$this->load->view('login/members');
}
else{
redirect('site/restricted');
}
}
And this is my model:
public function can_log_in(){
$this->db->where('login_id', $this->input->post('idnum'));
$this->db->where('password', md5($this->input->post('password')));
$query = $this->db->get('user_account');
if($query->num_rows() == 1){
return true;
} else{
return false;
}
}
In your members function you are not actually checking the value of the role session data, you are just checking that it exists. You need to change :
if($this->session->userdata('is_logged_in') && $this->session->userdata('role', 'admin')){
to:
if($this->session->userdata('is_logged_in') && $this->session->userdata('role') == 'admin'){
As you will see, there is only 1 parameter that can be passed into the $this->session->userdata() function:
/**
* Fetch a specific item from the session array
*
* #access public
* #param string
* #return string
*/
function userdata($item)
{
return ( ! isset($this->userdata[$item])) ? FALSE : $this->userdata[$item];
}
when you perform login action , From where you are calling can_log_in() method of model , Even you load the model but you are calling only $this->model_role->scalar('user_account','role') method which you give only "admin" parameter results in response .

Should I compare $get value to stored relavent db value?

I am trying to implement resetting a users password in codeigniter.
I've created a form that the users sends their email and it creates a row in a 'reset' table that stores their token that is created as well as attaches the token the link sent to the email.
The final step is actually resetting the password. I am not understanding how to make the correct comparison when checking the token attached to the email against the one stored in the db associated with that email, or if that is even the right way to go about it.
In the current code I have, I am unable to get it to pass validation and actually reset the password. Here is my code:
This is the model for creating the token and sending the email:
public function validate_retrieve($data) {
$query = $this->db->where($data)->get('users', '1');
foreach ($query->result() as $user)
{
$user->email;
$user->salt;
$user->id;
}
$token = sha1($user->email.$user->salt).dechex($user->id);
$reset_token = array(
'token' => $token,
'email' => $user->email
);
$insert = $this->db->insert('reset', $reset_token, '1');
return $reset_token;
}
and the controller:
public function retrieve()
// REQUEST PASSWORD RESET
// LOADED WHEN THE FORM IS SUBMITTED OFF THE PASSWORD PAGE AND SENDS THE EMAIL WITH TOKEN AND INSTRUCTIONS
{
$this->load->library('form_validation');
$this->load->library('session');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->load->model('user_model', 'um');
$this->load->library('encrypt');
$this->load->helper('url');
$submit = $this->input->post('submit');
$salt = $this->_salt();
if($submit)
// IF THE SUBMIT BUTTON IS SET
{
// START PROCESS TO CREATE $USER VARIABLE THAT HOLDS WHAT THE USER ENTERED IN THE FORM AND THAT CAN GET CHECKED AGAINST THE DB IN THE MODEL
$user = $this->um->validate_retrieve(array('email' => $this->input->post('email')));
// IF THE USER IS CREATED AND CHECKS OUT AND ALL OF THE ERRORS ARE CLEARED ON THE FORM
if( $user && $this->form_validation->run() == TRUE ) {
$domain = "clci.dev/index.php";
// CREATE A TOKEN LINK TO SEND TO THE USERS EMAIL THAT EXIST IN THE DB AND WAS ENTERED
$token = $user['token'];
$link = "http://www.".$domain."/auth/reset/?token=$token";
$this->load->library('email');
$this->email->from('noreply#cysticlife.org', 'CysticLife');
$this->email->to($this->input->post('email'));
$this->email->subject('Reset Password');
$this->email->message("Please go to the following web address to reset your password:\n\n$link\n\n-Your friends at CysticLife\n\nPlease remember to add the cysticlife.org domain to your address book to ensure that you receive your CysticLife e-Notifications as requested.");
$this->email->send();
redirect('auth/success');
exit;
}
$this->form_validation->run() == FALSE;
$data['main_content'] = 'auth/password';
$this->load->view('includes/templates/main_page_template', $data);
$data['email_error'] = 'This email is invalid';
}
}
now here is what I'm having trouble with, the model for resetting:
public function verify_token($token)
{
$this->db->where('token', $token);
$query = $this->db->get('reset');
if ($query->num_rows() == 1) {
return TRUE;
} else {
return FALSE;
}
}
public function reset_password()
{
$salt = $this->_salt();
$query = $this->db->get('reset', 1);
$row = $query->row();
$data = array(
'password' => $this->encrypt->sha1($salt . $this->encrypt->sha1($this->input->post('password'))),
'salt' => $salt
);
$this->db->where('email', $row->email);
$this->db->update('users', $data);
}
and the controller:
public function reset_password()
{
$this->load->library('form_validation');
$this->load->library('session');
$this->load->model('user_model', 'um');
$this->load->library('encrypt');
$this->load->helper('url');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
$this->form_validation->set_rules('password2', 'Confirm Password', 'trim|required|matches[password]');
$salt = $this->_salt();
$submit = $this->input->post('submit');
if($submit)
{
$validToken = $this->um->verify_token($token);
if($this->form_validation->run() == TRUE && $validToken == TRUE)
{
$this->um->reset_password(array('password' => $this->input->post('password', $salt)));
$data['main_content'] = 'auth/success';
$this->load->view('includes/templates/home_page_template', $data);
}
$this->form_validation->run() == FALSE;
$data['main_content'] = 'auth/reset';
$this->load->view('includes/templates/main_page_template', $data);
}
}
I seem to be very close but I am definitely stuck. Any help is greatly appreciated.
http://yoursitename.com/reset/[hashcode]
send the link to the member email, went password have reset by user.
on web site you will retrieve the hashcode to compare with your database
public function reset($hashcode)
{
if($hashcode!=null)
{
// compare with db
// if success
// redirect to create new password page
// or show create new password form
}
}

Categories