Model always executing else clause when using WHERE clause - php

I have a problem with the function of the mode. When I put the right admin name and admin password, it doesn't work. Instead, it gives me the last error message ("You don't have..."), but if I comment out the second WHERE clause in my model, then it works as intended.
Model:
function validate_admin()
{
$this->db->where('adminname',$this->input->post('adminname'));
//$this->db->where('adminpassword',md5($this->input->post('adminpassword')));
$query = $this->db->get('admin');
if($query->num_rows() == 1)
{
return TRUE;
}
}
Controller:
function validate_admin_credentials()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('adminname','Username','trim|required');
$this->form_validation->set_rules('adminpassword','Password','trim|required');
if($this->form_validation->run() == FALSE)
{
$data['main_content']='login_failed';
$this->load->view('includes/template',$data);
}
else
{
$this->load->model('admin_model');
if($this->admin_model->validate_admin())
{
$data = array(
'adminname' => $this->input->post('adminname'),
'adminpassword' => $this->input->post('adminpassword'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('/site/admin_panel');
}
else
{
echo "You don't have administration privileges";
}
}
}
How can I resolve this issue?

If you completely sure about password you can try this code:
$this->db->where('adminpassword', md5($this->input->post('adminpassword', TRUE)));
Edit: edited, sorry for my poor english

You can try it.
Model
$adminpassword = md5($this->input->post('adminpassword'));
$data = array('adminname' => $this->input->post('adminname'),
'adminpassword' => $adminpassword);
$query = $this->db->get_where('admin', $data);
return $query->num_rows();
Controller
if($this->admin_model->validate_admin() > 0)

Related

password_verify() logging in all the time

Using codeigniter hashed my password with BCRYPT, seems that everytime I login I redirect to the success page. So I am figuring password verify is not working, even if I enter the incorrect login it still redirects, does not throw the form_validation errors either.
I used the documentation to set it up along with the guides on SO. Will eventually go to Ion Auth but want to know how to fix this. As I am still learning code igniter mvc.
Model
class user_model extends CI_Model{
public function register($encrypt_pass){
$data = array(
'name'=> $this->input->post('name'),
'email'=> $this->input->post('email'),
'username'=> $this->input->post('username'),
'password'=>password_hash($encrypt_pass,PASSWORD_BCRYPT)
);
return $this->db->insert('customers',$data);
}
public function login($username,$password){
//validate the inputs from form
$this->db->where('username',$username);
$query = $this->db->get('customers'); //customers is the table
$result = $query->row_array();
if(!empty($result) && password_verify($password, $result['password'])){
return $result;
}
else{
return "false";
}
}
}
Controller
public function 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('templates/header');
$this->load->view('users/login',$data);
$this->load->view('templates/footer');
}
else {
//Getting username
$username = $this->input->post('Username');
//Getting and ecrypting password
$password = $this->input->post('Password');//password hashed
$user_id = $this->user_model->login($result);
//checking for user/pass correct will set session if so
if($user_id){
$this->session->set_flashdata('user_loggedin','You are now logged in');
redirect('posts');
}
// If combo is incorrect will redirect
else{
$this->session->set_flashdata('user_loggedin','Login Failed, Please Try
Again');
redirect('users/login');
}
}
}
}
Here is a simple working login code, there are many ways how to do it, it's just an example.
ON YOUR MODEL
Create a function that will check/get the username's password.
public function _getUserPassword($user_name){
$data = array();
$this->db->select('PASSWORD');
$this->db->from('tbl_user');
$this->db->where('USER_NAME', $user_name);
$query = $this->db->get();
if($query->num_rows() > 0){
foreach($query->result_array() as $field_name => $field_value){
$data = $field_value;
}
return $data;
}
else{
return false;
}
}
I've seen your's just selecting it.
We need to use that _getUserPassword function on we call it verify function
function verify($username, $password){
$data = array();
$userNameExists = $this->_getUserPassword($username);
if(password_verify($password, $userNameExists['PASSWORD'])){
$this->db->select('*');
$this->db->from('tbl_user AS user');
$this->db->where('USER_NAME', $username);
$query = $this->db->get();
if($query->num_rows() > 0){
foreach($query->result_array() as $field_name => $field_value){
$data = $field_value;
}
return $data;
}
else{
return false;
}
}
else{
return false;
}
}
So if the verification is success it will return the data to your controller, Let's use your controller.
Let's assume that you changed the models
ON YOUR CONTROLLER
public function 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('templates/header');
$this->load->view('users/login',$data);
$this->load->view('templates/footer');
}else {
//Getting username
$username = $this->input->post('Username');
//Getting and ecrypting password
$password = $this->input->post('Password');
$user_id = $this->user_model->verify($username,$password);
//checking for user/pass correct will set session if so
if($user_id){
$this->session->set_userdata('user_loggedin','You are now logged in');
redirect('posts');
}else{
//DO NOT SET USER DATA SESSION HERE UNLESS IT WILL AUTOMATICALLY LOGGED IN.
redirect('users/login');
}
}
}
Hope this helps!
where you are checking that password is matching or not.
try this in your controller.after user check.
if($user>0){
if (password_verify($this->input->post('Password'), $user_id['password'])) {
//success message
}
else{
//error message.password is invalid
}

change password in codeigniter with logged in users throws error

I want to change the password for logged in users,but it always give me an error:[Message: Trying to get property 'password' of non-object] in the controller. How to solve this error???
Please help,Thanks much!
This is my controller:
if($this->form_validation->run()){
$cur_password = md5($this->input->post('cpassword')); // md5-encrypt the password
$new_password = md5($this->input->post('npassword'));
$conf_password = md5($this->input->post('copassword'));
//$this->load->model('queries');
$this->load->library('session');
$user_id = $this->session->userdata('user_id');//multiple users id login
$passwd = $this->queries->getCurPassword($user_id);
!ERROR FOUND HERE!->if($passwd->password == $cur_password){
if($new_password == $conf_password){
if($this->queries->updatePassword($new_password,$user_id)){
echo 'Password Updated Successfully!';
echo '<br/><label>Back to homepage</label><br/>';
}else{
echo 'Failed To Update Password!!';
}
}else{
echo 'New Password and Confirm Password is not matching!!';
}
}else{
echo 'Sorry! Current Password is not matching!!';
}
}else{
echo validation_errors();
}
This is my model:
<?php
class Queries extends CI_Model{
function login() {
$query = $this->db->select('*')
->from('users')
->where('id');
return $query->row();
}
function index() {
$userid = $this->login()->id; //id of the user which is currently logged IN
$this->session->set_userdata('user_id', $user_id);
}
public function getCurPassword($user_id){
$query = $this->db->where(['id'=>$user_id])
->get('users');
if($query->num_rows() > 0 ){
return $query->row();
}
}
public function updatePassword($new_password,$user_id){
$data = array(
//'password' => md5($this->input->post("$new_password"))
'password' => ($new_password)
//'password'=> password_hash(["$new_password"],PASSWORD_BCRYPT)
);
return $this->db->where('id',$user_id)
->update('users',$data);
}
}
Thanks!
You have error in your syntax error says that you are trying to get property of non-object means $passwd may be an array
if($passwd['password'] == $cur_password)
And in case you have null user_id
Place these two lines in your controller function above if($this->form_validation->run()){ line
$userid = $this->queries->login()->id; //id of the user which is currently logged IN
$this->session->set_userdata('user_id', $userid);
and in your login function in model
function login() {
$query = $this->db->select('*')
->from('users')
->where('username',$this->session->userdata('username'));
return $query->row();
}
Hope it helps!
This happens when the user_id not found.
Notice that the getCurPassword function will return the user if found (when checking if num_rows > 0) but if didn't found it returns NULL.
When this happens the $passwd var is null so you cann't access $passwd->password.
You can solve it by changing the if statement to:
if($passwd && $passwd->password == $cur_password){
Edited Try to retrieve your user name as and then call with it the getCurPassword function:
$user_name = $this->session->userdata('username');
$passwd = $this->queries->getCurPassword($user_name );
And in the controller change getCurPassword function as:
public function getCurPassword($user_name){
$query = $this->db->select('*')
->from('users')
->where('username', $user_name);
if($query->num_rows() > 0 ){
return $query->row();
}
}
Notice that I assume you have "username" column in your DB

Simple CRUD Operation in Codeigniter?

I'm doing simple CRUD operation in Codeigniter.
This is My Controller:
public function areaEdit($area_id)
{
$this->global['pageTitle'] = 'Area Edit';
$data['areaEdit'] = $this->um->areaEdit($area_id);
$this->loadViews("utilities/area/areaEdit", $this->global, $data , NULL);
}
public function updateArea($area_id='area_id')
{
$area_name = $this->input->post('area_name');
$area_abbr = $this->input->post('area_abbr');
$this->form_validation->set_rules('area_name', 'Area Name', 'trim|required');
$this->form_validation->set_rules('area_abbr', 'Area Abbrevation', 'trim');
if ($this->form_validation->run() == FALSE) {
$this->areaEdit($area_id);
} else {
$area_name = ucwords(ucfirst($this->security->xss_clean($area_name)));
$area_abbr = ucwords(ucfirst($this->security->xss_clean($area_abbr)));
$data = array('area_name' => $area_name, 'area_abbr' => $area_abbr);
$result = $this->um->updateArea($data, $area_id);
if ($result) {
$this->session->set_flashdata('success', '<b>'.$area_name.'</b> updated successfully on '.date('d/m/Y H:i:s'));
} else {
$this->session->set_flashdata('error', 'Something wrong! Please try again.');
}
redirect(base_url('utilities/areaList'));
}
}
public function deleteArea($area_id='area_id')
{
$result = $this->um->deleteArea($data, $area_id);
if ($result) {
$this->session->set_flashdata('success', '<b>'.$area_name.'</b> deleted successfully on '.date('d/m/Y H:i:s'));
} else {
$this->session->set_flashdata('error', 'Something wrong! Please try again.');
}
redirect(base_url('utilities/areaList'));
}
And this is My Model is:
public function areaEdit($area_id)
{
$this->db->select("*");
$this->db->from("tbl_area");
$this->db->where("area_id", $area_id);
$query = $this->db->get();
return $query->row();
}
public function updateArea($data, $area_id)
{
$this->db->where("$area_id", $area_id);
$this->db->update("tbl_area", $data);
if ($this->db->affected_rows() > 0) {
return true;
} else {
return false;
}
}
public function deleteArea($area_id='area_id')
{
$this->db->where("area_id", $area_id);
$this->db->delete("tbl_area");
if ($this->db->affected_rows() > 0) {
return true;
} else {
return false;
}
}
When I'm running this script, it gives me an error, it goes in else condition in controller for update function and delete function.
I'm not getting that where I'm making mistake ?
Any kind of help is welcome, thanks in advance.
Hope this will help you :
Mismatch arguments : you are passing two parameters from controller but there is only one argument in model's deleteArea();
Should be like this :
public function deleteArea($area_id='area_id')
{
$result = $this->um->deleteArea($area_id);
if ($result) {
$this->session->set_flashdata('success', '<b>'.$area_name.'</b> deleted successfully on '.date('d/m/Y H:i:s'));
} else {
$this->session->set_flashdata('error', 'Something wrong! Please try again.');
}
redirect(base_url('utilities/areaList'));
}

Login form not validating

I am creating a login form but it does not do the validation rightly against the value in the database. when I put in the wrong password it still redirects me to the page that needs login access
CONTROLLER
public function login() {
$this->form_validation->set_rules('username', 'Username', 'trim|required|alpha_numeric|min_length[6]|max_length[12]|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|alpha_numeric|min_length[6]|max_length[6]|xss_clean');
if ($this->form_validation->run() == FALSE) {
// return main page if submitted form is invalid.
$this->load->view('abt_login');
} else {
$this->load->model('abt_db');
$q = $this->abt_db->check_login();
if($q)
{
$data = array(
'email' => $this->input->post('email'),
'password' => $this->input->post('password'),
);
$this->session->set_userdata($data);
redirect('index.php/abovetheblues/abt-abovetheblues');
}
else
{
redirect('index.php/abovetheblues/abt_selfhelp');
}
}
}
MODEL
function check_login() {
$this->load->database();
$this->db->where('email', $this->input->post('email'));
$this->db->where('password', $this->input->post('password'));
$q = $this->db->get('user');
if ($q->num_rows == 1) {
return true;
}
}
num_rows is a function and you not call the function
Try to change this:
if ($q->num_rows == 1) {
return true;
}
to this:
if ($q->num_rows() == 1) {
return true;
}
Consider passing the two variables to the function instead of trying to grab them from the input class:
Controller:
$this->load->model('abt_db');
$q = $this->abt_db->check_login($this->input->post('email'), $this->input->post('password'));
Model:
function check_login($email, $password) {
$this->load->database();
$this->db->where('email', $email);
$this->db->where('password', $password); ## VERY UNSECURE - SEE BELOW
$q = $this->db->get('user');
if ($q->num_rows() == 1) { ## as seen in the previous answer
return true;
}
return false; ## You NEED to have this.
}
PLEASE NOTE:
You are checking the password directly with the database in plaintext. This is a terrible idea and will lead to your application getting compromised.
I strongly recommend you read this excellent primer on password security:
Salting Password Hashing

How to take specific data from table and store it in a cookie codeigniter php?

I'm new to codeigniter and php, few days only, so I need a little help.
I'm trying to put some data in my cookie from table so I can check where to redirect user after login. In table users there are two columns named Admin and Company with one or zero if user is or not, and then i wish to insert that information to cookie.
function conformation in user_controler is:
function conformation(){
$this->load->model('user');
$q = $this->user->confr();
if($q){
$data = array(
'username' => $this->input->post('username'),
'Admin' => $this->input->post($a = $this->user->getAdmin), // get 1/0 from users column Admin
'Company' => $this->input->post($c = $this->user->getComp),
'login' => true
);
if( $a == 1 ){ //is admin redirect to admin view
$this->session->set_userdata($data);
redirect('user_controler/useradm');
}
if($c == 1){ //if company redirect to company view
$this->session->set_userdata($data);
redirect('user_controler/usercomp');
}
$this->session->set_userdata($data);// if common user redirect to user view
redirect('user_controler/userpro');
}
else{ // if nothing above redirect to login page
redirect('user_controler/log');
}
}
And in user model:
function getAdmin{
$this->db->where('Admin', 1);
$a = $this->db->get('users');
}
function getComp{
$this->db->where('Company', 1);
$a = $this->db->get('users');
}
function conf(){
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', $this->input->post('password'));
$q = $this->db->get('users');
if($q->num_rows == 1 ){
return TRUE;
}
}
Also have site controller for checking login
class Site extends CI_Controller{
function __construct() {
parent::__construct();
$this->login();
}
function login(){
$login = $this->session->userdata('login');
if(!isset($login) || login != TRUE){
$this->log;
die();
}
}
}
Of course it's not working because i should probably check these column some other way but I don't know how. I Also have enabled table ci_session and it's work perfectly without Admin and Company.
Hello and welcome to Stackoverflow.
Here are my updates to the code (I have annotated my changes):
function conformation(){
$this->load->model('user');
if($this->user->confr()){ //$q wasn't needed, as you are only using this twice
$user = $this->input->post('username'); //I have added this as I will be referring to it a couple of times.
$data = array(
'username' => $user,
'Admin' => $this->user->getAdmin($user), // Your method was questioning the original form looking for data that it would never find - This will question your model.
'Company' => $this->user->getComp($user), //Same as above
'login' => true
);
$this->session->set_userdata($data); //It doesn't matter who the user is, we shall set the data to start with.
if($this->user->getAdmin($user)){ //is admin redirect to admin view
redirect('user_controler/useradm');
}
elseif($this->user->getComp($user)){ //if company redirect to company view
redirect('user_controler/usercomp');
}
else { //Redirect non-privileged users.
redirect('user_controler/userpro');
}
}
else{ // if nothing above redirect to login page
redirect('user_controler/log');
}
}
Users Model:
function getAdmin($user){
$this->db->where('username', $user); //Before you was just returning everyone who is an admin This instead finds the user
$a = $this->db->get('users');
foreach($a as $u) {
if($u["Admin"]==1) { return true; } //This finds if the user is a admin or not, and the function will now return a value (true)
}
}
function getComp($user) {
$this->db->where('username', $user);
$a = $this->db->get('users');
foreach($a as $u) {
if($u["Company"]==1) { return true; }
}
} //Edited similar to the function above
function conf(){
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', $this->input->post('password'));
$q = $this->db->get('users');
if($q->num_rows == 1 ){
return TRUE;
}
}
Lastly your login function:
function login(){
$login = $this->session->userdata('login');
if(!isset($login) || $login != TRUE){ //You weren't referring to your $login variable
$this->log;
die();
}
}
Hopefully this helps with your problems, let me know if you need any amendments.

Categories