Session on codeigniter not working perfectly - php

I have an issue regarding session (userdata/flashdata) on my code.
Modal
public function loginCheck(){
$email = $this->input->post('email');
//encrypt password
$this->load->library("hashing");
$password = $this->hashing->incrypt($this->input->post('password'));
$this->params = array('email' => $email, 'password' => $password);
$user = $this->findById();
if(count($user)>0){
$data = array(
'email' => $user->email,
'isLoggedIn' => 1,
'user_id' => $user->id,
'user_type' => $user->user_type
);
$this->session->set_userdata($data);
return true;
}
return false;
}
And my Controller
public function login(){
$this->load->model('model_users');
//if posted login
$submit = $this->input->post('submit');
if($submit){
$this->load->model('model_users');
$rules = $this->model_users->rules;
$this->form_validation->set_rules($rules);
if($this->form_validation->run() == true){
// user credential from model
if($this->model_users->loginCheck()== true){
redirect("admin/site/index");
} else{
$this->session->set_flashdata('message', 'Oops! Invalid email and/ or password.');
redirect("admin/site/login");
}
}else{
$this->session->set_flashdata('message', 'Oops! Invalid email and/ or password.');
redirect("admin/site/login");
}
}
$this->loadPartialView("admin/login");
}
The session is not being set on CI 3.0. The function set_userdata() is not functioning well.
The manual session initializing is also having trouble.

Please try load Session Library into Controller and Modal before using it.
$this->load->library('session');

i dont think if this is a good answer, but have you call your session in view?
as i know ,
CodeIgniter supports "flashdata", or session data that will only be available for the next server request, and are then automatically cleared.
it can be found in sesseion documentation
so in your view in div tag or other, its like
<?php echo $this->session->flashdata('message');?>

First you can add library of session.
There are two way of add library.
1) You can add in controller method.
2) autoload in autoload.php file.

Related

Codeigniter how to get userid after login

I have successfully created a registration and login system.
I have used useremail and password in the login form and I want to display the username and other properties related to that logged in user.
What are the simplest and best practices to get the userid after a login in codeigniter?
As good coder create session at login time and use session at website wide.
public function login($username, $password) {
$user = $this->db
->select("username, name, phone")
->where(
[
'username' => $username,
'password' => md5($password)
]
)
->get("table_name")
->row();
if ($user) {
$logindata = [
'userid' => $user->username,
'name' => $user->name,
'phone' => $user->phone
];
$this->session
->set_userdata($logindata);
return true;
}
else {
return false;
}
}
Then after you can use anywhere in website
echo $this->session->userid;
I hope it will help you in general way.
Best practice would be that when you check the login details in your model after success you should create a session saving userid of that user and use that anywhere in your application for fetching respective data against that user. Take a look at following psuedo code for login user.
public function userAuthentication($username,$pass)
{
$this->db->select('id');
$this->db->where('username',$username);
$this->db->where('password',md5($pass));
$result = $this->db->get('users')->result();
if(!empty($result)){
$this->session->set_userdata('userlogged_in', $result[0]->id);
return true;
}else{
return false;
}
}
You can place this function in your model and apply it in your controller. I hope this helps.
You may create a session and set user id after successful login.

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
}
}

How do I pull a variable from a model to use on my controller in CodeIgniter?

I am trying to use a variable in my controller that has been created in my model.
Here is the model:
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 on my controller I'm trying to use $token that was created in the model:
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 = $this->um->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';
}
}
thanks in advance
You're trying to access an array as an object.
$reset_token = $this->um->validate_retrieve($whatever_id);
$token = $reset_token['token'];
That's how you access the token portion of the returned results from this function.
And according to your latest update, you would actually access it like this:
$token = $user['token'];
Because in the following line you assign the results of the validate_retrieve method to the variable $user:
$user = $this->um->validate_retrieve(array('email' => $this->input->post('email')));

hashing/salting post data codeigniter

I am at the tail end of signing in a created user to an account. I've commented out my flow and everything seems to make since, however I am missing a step or two because now the post data password is not being hashed.
CONTROLLER:
function validate_credentials()
{
// WHEN THE VIEW IS LOADED THIS FUNCTION IS CALLED AND LOADS MODEL AS WELL AS DEFINES THE SALT VARIABLE AND LOADS THE ENCRYPTING HELPER LIBRARY
$this->load->model('user_model', 'um');
$login = $this->input->post('submit');
$salt = $this->_salt();
$this->load->library('encrypt');
//IF THE SUBMIT BUTTON IS TRIGGERED THE POST DATA IS SENT TO THE VALIDATE FUNCTION IN THE MODEL VIA VARIABLES CREATED
if($login)
{
$data = array(
'email' => $this->input->post('email'),
'password' => $this->encrypt->sha1($user->salt. $this->encrypt->sha1($this->input->post('password')))
);
$user = $this->um->validate($data);
}
// IF ITS A REAL USER OPEN THE GATE AND LET THEM IN
if($user)
{
$this->session->set_userdata($data);
redirect('account/dashboard');
}
else
{
$this->index();
}
}
MODEL:
function validate($data)
{
$this->output->enable_profiler(TRUE);
// TAKING THE DATA FROM THE MODEL AND CHECKING IT AGAINST THE STORED INFO IN THE DB
$query = $this->db->where($data)->get('users', 1);
if($query->row())
{
return $query->row();
}
}
thanks in advance
$user->salt should just be $salt.

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