I have this code while registering the form:
function register()
{
$this->form_validation->set_rules('txt_username', 'Username', 'trim|required');
$this->form_validation->set_rules('cpassword', 'Confirm Password', 'trim|required|matches[txt_password]|md5');
$this->form_validation->set_rules('txt_password', 'Password', 'trim|required|md5');
//other codes
$data = array('username' => $this->input->post('txt_username'),
'password' => $this->input->post('txt_password')
);
// insert form data into database
if ($this->account_model->insertUser($data));
{
$this->session->set_flashdata('msg','successfully registered!');
redirect('account/register');
}
}
the password matches here.
but when i use same data to username and password to login: it displays invalid username or password:
the login function is as follows:
function login()
{
//set validations
$this->form_validation->set_rules("txt_username", "Username", "trim|required");
$this->form_validation->set_rules("txt_password", "Password", "trim|required");
$username = $this->input->post("txt_username");
$password = $this->input->post("txt_password");
$usr_result = $this->account_model->get_user($username, $password);
if ($usr_result > 0) //active user record is present
{
$this->account_model->login();
$data['message'] ="You are logged in!";
}
else
{
$this->session->set_flashdata('msg', 'Invalid username and password!');
}
}
}
I have this model for inserting registration form data to database:
function insertUser($data)
{
return $this->db->insert('user', $data);
}
and i have this model to retreive data to login:
function get_user($usr, $pwd)
{
$sql = "select * from user where username = '" . $usr . "' and password = '".md5($pwd). "'";
$query = $this->db->query($sql);
return $query->num_rows();
}
The best method instead of MD5 is use base64 in Codeigniter. That means decode() and encode().
Encoding
$password = 'mYp#ssw0rd'; // or $password
$encriptKey = 'super-secret-key';
$encrypted_string = $this->encrypt->encode($password, $encriptKey);
Decoding
$password = 'mYp#ssw0rd'; // or $password
$encriptKey = 'super-secret-key';
$decrypted_string = $this->encrypt->decode($password, $encriptKey);
In Addition
Load library as well $this->load->library('encrypt');
You could do this in your model:
public function login()
{
$user = $this->get_by(array(
'email' => $this->input->post('email'),
'password' => $this->hash($this->input->post('password')),
), TRUE);
if (count($user))
{
// Log in user
$data = array(
'name' => $user->name,
'email' => $user->email,
'id' => $user->id,
'user_type'=>$user->user_type,
'emp_id'=>$user->emp_id,
'loggedin' => TRUE,
);
$this->session->set_userdata($data);
return TRUE;
}
return FALSE;
}
public function logout ()
{
$this->session->sess_destroy();
$this->session->unset_userdata('logged_in','id','name','email');
}
public function loggedin ()
{
return (bool) $this->session->userdata('loggedin');
}
public function hash ($string)
{
return hash('sha512', $string . config_item('encryption_key'));
}
And can let a user login. Use CI Session for login which would be a better option.
Read More here
For Controller Do this:
public function login()
{
$dashboard ='admin/dashboard';
$rules = $this->secure_m->rules;
$this->form_validation->set_rules($rules);
if ($this->form_validation->run() == TRUE)
{
if ($this->secure_m->login() == TRUE)
{
$this->secure_m->loggedin() == FALSE || redirect($dashboard);
redirect($dashboard);
}
else
{
$this->session->set_flashdata('error', 'That email/password combination does not exist');
redirect('secure/login', 'refresh');
}
}
$this->load->view("Your View");
}
Please store encrypted password at insert time.
for example:
$data['password'] = md5($data['password']);
I think it will resolve your problem.
Other code is working fine for me.
Related
I am trying to create a login/register function by using password_hash() and password_verify.
Here is the simple code that I wrote. The result that I get is "invalid Password" when I try to log in.
What am I missing?
Register Controller
public function register() {
$email = $this->input->post('email');
$password = password_hash($this->input->post('password'), PASSWORD_BCRYPT);
$insert_db = $this->db->insert('users',[
'email' => $email,
'password' => $password
}
I can see that password_hash function seems to be fine, it storing random characters in the database. However, when I try to login with those details it doesn't work.
Database: field: varchar(255)
Login controller:
public function verifyLogin() {
$email = $this->input->post('email');
$password = ($this->input->post('pswd'));
// load model
$this->load->model('Login_model');
$account = $this->Login_model->verifyLogin($email, $password);
if ($account) {
//if user found, show success msg
echo "successful login";
} else {
echo "invalid password";
}
}
Login Model
public function verifyLogin($email, $password) {
$query = $this->db->where([ 'email'=> $email])
->get('users');
if ($query->num_rows() == 1) {
// hash fetched from db
$record = $query->row();
$dbPassword = $record->password;
// Hash length showing 60
echo strlen($dbPassword);
if (password_verify($password, $dbPassword)) {
return true;
} else {
return false;
}
}
}
Login Form
<?= form_open('Login/verifyLogin'); ?>
<label>Email</label>
?php echo form_error('login-email);'?>
<?php echo form_input(['name'=>'login-email', 'value' => set_value('login-email')]); ?>
<label>Password</label>
<?php echo form_error('login-password'); ?>
<?php echo form_password(['name'=>'login-password', 'value' => set_value('login-password')]);?>
<?php echo form_submit(['type' => 'submit', 'value' => 'Login']); ?>
<?= form_close(); ?>
you have two mistakes
your password field name is login-password but you trying to get pswd also if user not found you should return false
Also for email it is the same your form name is login-email but your are trying to access email
public function verifyLogin() {
$email = $this->input->post('login-email');
$password = ($this->input->post('login-password'));
// load model
$this->load->model('Login_model');
$account = $this->Login_model->verifyLogin($email, $password);
if ($account) {
//if user found, show success msg
echo "successful login";
} else {
echo "invalid password";
}
}
and
public function verifyLogin($email, $password) {
$query = $this->db->where([ 'email'=> $email])
->get('users');
if ($query->num_rows() == 1) {
// hash fetched from db
$record = $query->row();
$dbPassword = $record->password;
// Hash length showing 60
echo strlen($dbPassword);
if (password_verify($password, $dbPassword)) {
return true;
} else {
return false;
}
}
return false;
}
Your code seem's working I tested ..
Hi all I have this issue when I validate log in in codeigniter that seems it does not check the required password in my database.The required password in my database is hash using this
$password_hash = password_hash($password, PASSWORD_BCRYPT);
How can i used password_verify function in my model code?
Here is my model code:
public function login($data) {
$condition = "username =" . "'" . $data['username'] . "' AND " . "password =" . "'" . $data['password'] . "'";
$this->db->select('*');
$this->db->from('users');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1)
{
return true;
} else
{
return false;
}
}
Here is my controller:
public function login_user()
{
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean','required');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean','required');
if ($this->form_validation->run() == FALSE) {
$this->load->view('login_view');
} else {
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password'),
'firstname' => $this->input->post('firstname'),
'lastname' => $this->input->post('lastname')
);
$result = $this->login_database->login($data);
if ($result == TRUE) {
// Add user data in session
$this->session->set_userdata('username', $data['username']);
$this->session->set_userdata('firstname', $data['firstname']);
$this->session->set_userdata('lastname', $data['lastname']);
//redirect to dashboard
$this->load->view('include/sidenavbar');
$this->load->view('include/topnavbar');
$this->load->view('dashboard');
} else {
$this->session->set_flashdata('message', 'Login is invalid. Please try again!');
$this->load->view('login_view', $data);
}
}
}
can anyone help me how to do this..
Thanks in advance.
You should use password_verify() to know if you're password is valid.
Try this model function:
public function login($data) {
$this->db->select('password');
$this->db->from('users');
$this->db->where('username', $data['username']);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
$record = $query->row_array();
return password_verify($data['password'], $record['password']);
} else {
return false;
}
}
Hope this will help you :
after returning data from model you can check for correct password using password_verify()
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password'),
'firstname' => $this->input->post('firstname'),
'lastname' => $this->input->post('lastname')
);
$result = $this->login_database->login($data);
/*$result should return a single user data (in array form here)*/
if (! empty($result))
{
if (password_verify($data['password'], $result['password']))
{
$this->session->set_userdata('username', $data['username']);
$this->session->set_userdata('firstname', $data['firstname']);
$this->session->set_userdata('lastname', $data['lastname']);
//redirect to dashboard
redirect('dashboard'); /*use redirect()*/
//$this->load->view('include/sidenavbar');
//$this->load->view('include/topnavbar');
//$this->load->view('dashboard');
}
else
{
$this->session->set_flashdata('message', 'Password is invalid. Please try again!');
$this->load->view('login_view', $data);
}
}
else
{
$this->session->set_flashdata('message', 'Login is invalid. Please try again!');
$this->load->view('login_view', $data);
}
Your model should be like this :
public function login($data)
{
$this->db->where('username', $data['username']);
$query = $this->db->get('users');
if ($query->num_rows() == 1) {
$user = $query->row_array();
return $user;
} else {
return false;
}
}
Update : dashboard method
public function dashboard()
{
/*$data['title'] = 'my title';
you can pass data to the view like this
$this->load->view('dashboard',$data);
*/
$this->load->view('templates/header');
$this->load->view('dashboard');
$this->load->view('templates/footer');
}
I am new to codeigniter, I am trying to login after registration... I enter correct user name and password, but error is "No such account exists in database" which set message in else part if its false.
For checking I used echo num_rows() it's showing 0 (which is wrong), total 5 records are there but echo num_fields is showing 8 fields (which is correct).
controller login code:
public function login() {
$this->form_validation->set_rules('username', 'User Name', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() === FALSE) {
$this->load->view('login');
} else {
//get user name
$username = $this->input->post('username');
//get encrypt password
$password = md5($this->input->post('password'));
//login user
$user_id = $this->auth_model->login($username, $password);
if ($user_id) {
//create session
$user_data = array(
'user_id' => $user_id,
'username' => $username,
'logged_in' => true
);
$this->session->set_userdata($user_data);
//set message
$this->session->set_flashdata("success", "your are logged in");
redirect('index.php/users/profile');
} else {
$this->session->set_flashdata("error", "No such account exists in database");
redirect('index.php/auth/login');
}
}
}
model login code:
public function login($username, $password) {
$this->db->where('username', $username);
$this->db->where('password', $password);
$result = $this->db->get('tblLogin');
if ($result->num_rows() == 1) {
return $result->row(0)->id;
} else {
return false;
}
}
public function login($username, $password) {
$this->db->where('username', $username);
$this->db->where('password', $password);
$result = $this->db->get('tblLogin');
$ret = $result->row();
if ($ret) {
return $ret;
} else {
return false;
}
}
row() function get is single and check in if condition.
print your query using $this->db->last_query();
and check your mysql database.
You can try this solution for your problem :
Changes your modal function:
Modal.php
public function login($username, $password) {
$this->db->where('username', $username);
$this->db->where('md5(password)', $password);
$result = $this->db->get('tblLogin');
$ret = $result->row();
if (!empty($ret)) {
return $ret;
} else {
return false;
}
}
Please changes your controller file.
LoginController.php
public function login() {
$this->form_validation->set_rules('username', 'User Name', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() === FALSE) {
$this->load->view('login');
} else {
//get user name
$username = $this->input->post('username');
//get encrypt password
$password = $this->input->post('password');
//login user
$user_id = $this->auth_model->login($username, $password);
if ($user_id) {
//create session
$user_data = array(
'user_id' => $user_id,
'username' => $username,
'logged_in' => true
);
$this->session->set_userdata($user_data);
//set message
$this->session->set_flashdata("success", "your are logged in");
redirect('index.php/users/profile');
} else {
$this->session->set_flashdata("error", "No such account exists in database");
redirect('index.php/auth/login');
}
}
}
Controller:
// log in user
public function login() {
$this->form_validation->set_rules('username', 'User Name', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() === FALSE) {
$this->load->view('users/login');
} else {
//get user name
$username = $this->input->post('username');
//get encrypt password
$password = $this->input->post('password');
//login user
$user_id = $this->auth_model->login($username, $password);
if ($user_id) {
//create session
$user_data = array(
'user_id' => $user_id,
'username' => $username,
'logged_in' => true
);
$this->session->set_userdata($user_data);
//set message
$this->session->set_flashdata("loggedin", "your are logged in");
redirect('dashboard');
} else {
$this->session->set_flashdata("log_failed", "Login invalid");
redirect('login');
}
}
}
Model:
public function login($username, $password) {
$this->db->where('username', $username);
$result = $this->db->get('tbllogin');
$db_password = $result->row(0)->password;
if (password_verify($password,$db_password)) {
return $result->row(0)->id;
} else {
return false;
}
}
I'm not quite sure why the username didn't appear on view page if i change the session data into array (i'm new in CodeIgniter). I have auth controller to make login process:
function index() {
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'username', 'required|trim|xss_clean');
$this->form_validation->set_rules('password', 'password', 'required|trim|xss_clean');
if ($this->form_validation->run() == FALSE) {
$this->load->view('Login');
# code...
}
else {
$username = $this->input->post('username');
$password = $this->input->post('password');
$check = $this->M_login->check($username, $password);
// session data
if ($check->num_rows() == TRUE) {
foreach ($check->result() as $value) {
$sess_data['id'] = $value->id;
$sess_data['name'] = $value->name;
$sess_data['username'] = $value->username;
$sess_data['password'] = $value->password;
$sess_data['description'] = $value->description;
$this->session->set_userdata($sess_data);
}
redirect('Dashboard');
}
else {
$this->session->set_flashdata('result_login', '<br>Invalid username or password, try again.');
redirect('Login');
}
And here is my dashboard controller:
public function __construct() {
parent::__construct();
if(!$this->session->userdata('id')){
redirect('login');
}
}
public function index() {
// Dashboard view
$username = $this->session->userdata('username');
$data['username']=$username;
$this->load->view('Dashboard', $data);
}
function logout() {
$this->session->sess_destroy('id');
redirect('login');
}
With above code, i can get the username on my dashboard view by echo $username. But when i change the session data like this:
if ($check->num_rows() == TRUE) {
foreach ($check->result() as $value) {
// session data
$sess_data = array(
'id' => $value->id,
'username' => $value->username,
'password' => $value->password,
'name' => $value->name,
'description' => $value->description
);
$this->session->set_userdata('log',$sess_data);
}
}
And Dashboard controller changed like this:
if(!$this->session->userdata('id')) {
$getdata= $this->session->userdata('log');
$data['username'] = $getdata['username'];
}
$this->load->view('Dashboard', $data);
Then the username disappeared from view page. How can i store username in session array and call it in view page. Please share your better suggestions or your experience guys.
Thanks.
Adding data in session :-
$newdata = array(
'username' => 'johndoe',
'email' => 'johndoe#some-site.com',
'logged_in' => TRUE
);
$this->session->set_userdata($newdata);
Retrieving Data from session :-
$this->session->all_userdata()
Retrieving single data :-
$session_id = $this->session->userdata('username');
Youcan refer this code
public function loginaction()
{
$this->load->library('session');
$a = $this->input->post('email');
$b = trim($this->input->post('password'));
$b1 = md5($b);
$c = 1;
$data = $this->userdata->userlogin($a,$b1,$c);
if($data)
{
echo true;
foreach ($data as $login)
{
$uid=$this->session->set_userdata('logId',$login->usr_id);
}
}
else
{
echo "Invalid username or password..!!!!";
$a=$this->input->post('email');
}
}
You can do it like
$username = $this->input->post('username');
$password = $this->input->post('password');
$check = $this->M_login->check($username, $password);
if ($check->num_rows() > 0)
{
$value = $check->row();
$sess_data['id'] = $value->id;
$sess_data['name'] = $value->name;
$sess_data['username'] = $value->username;
$sess_data['password'] = $value->password;
$sess_data['description'] = $value->description;
$this->session->set_userdata($sess_data);
redirect('Dashboard');
}
else
{
$this->session->set_flashdata('result_login', '<br>Invalid username or password, try again.');
redirect('Login');
}
And in your view
$username = $this->session->userdata('username');
Here's my login controller index function:
public function index() {
$data['title'] = 'Login';
$this->load->view('login_form', $data);
}
then here's my validate_credentials function:
public function validate_credentials() {
$this->load->library('form_validation');
$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->index();
} else {
$this->load->model('user_model');
if ($this->user_model->checkUserAccess($this->input->post('username'))) { // checks if user has access to the site
if ($this->ldapAuth()) { // checks if successful authentication with LDAP server
$email = $this->user_model->getEmail($this->input->post('username'));
$gpcid = $this->user_model->getUserGPC($this->input->post('username'));
$this->user_model->updateTimestamp('users', 'DateLastLogin', 'UserID', $this->input->post('username'));
$data = array (
'username' => $this->input->post('username'),
'gpcid' => $gpcid,
'email' => $email,
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('profile');
} else { // unsuccessful login
$error = "Username and/or Password is incorrect";
$data['title'] = 'Login';
$data['message'] = $error;
$this->load->view('login_form', $data);
}
} else {
$error = "You do not have access to the site";
$data['title'] = 'Login';
$data['message'] = $error;
$this->load->view('login_form', $data);
}
}
}
Is there a way to just call the index function and pass the error message rather than loading the view multiple times?
$data['title'] = 'Login';
$data['message'] = $error;
$this->load->view('login_form', $data);
Instead of loading view file you have to redirect it to index function. And use Session flash data to achieve this.
Like,
Controller
$this->session->set_flashdata( 'error', 'Username and/or Password is incorrect' );
redirect('index');
To print the message on login_form.php view file,
View (login_form.php)
<?php if($this->session->flashdata('error')){
echo $this->session->flashdata('message');
}?>
Your Controller
public function validate_credentials() {
$this->load->library('form_validation');
$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->index();
} else {
$this->load->model('user_model');
if ($this->user_model->checkUserAccess($this->input->post('username'))) { // checks if user has access to the site
if ($this->ldapAuth()) { // checks if successful authentication with LDAP server
$email = $this->user_model->getEmail($this->input->post('username'));
$gpcid = $this->user_model->getUserGPC($this->input->post('username'));
$this->user_model->updateTimestamp('users', 'DateLastLogin', 'UserID', $this->input->post('username'));
$data = array (
'username' => $this->input->post('username'),
'gpcid' => $gpcid,
'email' => $email,
'is_logged_in' => true
);
$this->session->set_flashdata($data);
redirect('profile');
} else {
$userdata = array (
'error' =>'Username and/or Password is incorrect',
);
$this->session->set_flashdata($userdata);
redirect('redirect url here'); // here is your url for index
}
} else {
$userdata = array (
'error' =>'You do not have access to the site',
);
$this->session->set_flashdata($userdata);
redirect('redirect url here'); // here is your url for index
}
}
}
Controller
public function loginaction() {
$this->load->library('session');
$a = $this->input->post('email');
$b = trim($this->input->post('password'));
$b1 = md5($b);
$c = 1;
$data = $this->userdata->userlogin($a, $b1, $c);
if($data) {
echo true;
foreach ($data as $login) {
$uid = $this->session->set_userdata('logId', $login->usr_id);
}
} else {
echo "Invalid username or password..!!!!";
$a = $this->input->post('email');
}
}