how to verify the hashed password? - php

I am using CodeIgniter framework.
Below is the function contained in the Signup.php controller.
public function _hash_string($str){
$hashed_string = password_hash($str, PASSWORD_BCRYPT);
return $hashed_string;
}
public function _verify_hash($text, $hashed_string){
$result = password_verify($text, $hashed_string);
return result; //TRUE OR FALSE
}
public function index()
{
if($this->input->post('newuser') == 1)
{
$user = new Users_model();
$user->username = $this->input->post('username');
$user->email = $this->input->post('email');
$pass= $this->input->post('password');
$hashed_pass = $this ->_hash_string($pass);
$user->password = $hashed_pass;
$user->account_status = 1;
$user->user_role = $this->input->post('user_role');
$id = $this->usermodel->insert($user);
}else{
$this->load->view('signup-page');
}
I've successfully hashed the user's password. How can I verify them?
Below is the function contained in the Login.php controller.
public function index()
{
if($this->input->post('login') == 1)
{
$user = new Users_model();
$user->email = $this->input->post('email');
$user->password = $this->input->post('password');
$user->user_role = $this->input->post('user_role');
$results = $this->usermodel->login($user);
if(count($results) > 0)
{
foreach($results as $row)
{
$session_array = array(
"id" => $row['id'],
"username" => $row['username'],
"email" => $row['email'],
"password" => $row['password'],
"account_status" => $row['account_status'],
"user_role" => $row['user_role']
);
$this->session->set_userdata($session_array);
$url = base_url() . "home?login=success";
redirect($url, "refresh");
}
}else{
$url = base_url() . "login?login=failed";
redirect($url, "refresh");
}
}else{
$this->load->view('login-page');
}
}
And here is the Users_model.php model.
function login($user){
$conditions = array(
"email" => $user->email,
"password" => $user->password,
"user_role" => $user->user_role,
"account_status" => 1,
);
$this->db->select('*');
$this->db->from('users');
$this->db->where($conditions);
$rs= $this->db->get();
return $rs->result_array();
}
What should I do to properly log the user in?

You can't compare password in mysql. because hashed using php, you have to use php function to compare password.
function login($user){
$conditions = array(
"email" => $user->email,
//"password" => $user->password,
"user_role" => $user->user_role,
"account_status" => 1,
);
$this->db->select('*');
$this->db->from('users');
$this->db->where($conditions);
$rs= $this->db->get();
if(!empty($rs)) {
$result_array = $rs->row_array();
$controllerInstance = & get_instance();
if($controllerInstance->_verify_hash($user->password,$result_array['password']) == TRUE) {
return $result_array;
}
}
return false;
}
use get instance to access controller.
$controllerInstance = & get_instance();
$controllerData = $controllerInstance->_verify_hash();
Hope this helps. updated after zaph comment

Related

login api with email, password or mobile number,password in codeigniter

I am trying to create an api which enables login for email id and password or mobile number and password in codeigniter but i was unable to do both i don't know the error. Here is my code of controller
Controller code
public function signin()
{
$this->default_file();
$responseData = array();
if(!empty($_POST['username']))
{
$userData = array();
$get_number = $this->validate_mobile($_POST['username']);
if(!empty($get_number))
{
$userData['usermob'] = $_POST['username'];
}
else
{
$userData['useremail'] = $_POST['username'];
}
$userData['userpass'] = $_POST['userpass'];
$userSignIn = $this->apm->signin($userData);
if((((!empty($userSignIn['id'])) && (!empty($userSignIn['useremail']))) ||((!empty($userSignIn['id'])) && (!empty($userSignIn['usermob'])))))
{
$session_data = array('id'=> $userSignIn['id'], 'logged_in'=> true);
$this->session->set_userdata('userLoggedIn', $session_data);
$userDetails = array();
$userDetails['id'] = $userSignIn['id'];
$getUserDetails = $this->apm->getUserDetails($userDetails);
$responseData['id'] = $getUserDetails['result']['u_id'];
$responseData['username'] = $getUserDetails['result']['username'];
$responseData['useremail'] = $getUserDetails['result']['useremail'];
$responseData['usermob'] = $getUserDetails['result']['usermob'];
$responseData['userlocation'] = $getUserDetails['result']['userlocation'];
$responseData['device_token'] = $getUserDetails['result']['device_token'];
$responseData['device_name'] = $getUserDetails['result']['device_name'];
$responseArray = array(
'apiName' => 'signin',
'version' => '1.0.0',
'responseCode' => 200,
'responseMessage' => 'logged in successfully',
'responseData' => $responseData
);
}
else
{
$responseArray = array(
'apiName' => 'signin',
'version' => '1.0.0',
'responseCode' => 204,
'responseMessage' => "Email or Passwor is incorrect.",
'responseData' => null//$responseData
);
}
}
else
{
$responseArray = array(
'apiName' => 'signin',
'version' => '1.0.0',
'responseCode' => 204,
'responseMessage' => "Sorry, please provide your input details.",
'responseData' => null//$responseData
);
}
echo json_encode($responseArray);
die();
}
My modal Code is here
public function signin($userData)
{
$arrData = array();
if(!empty($userData['useremail']) || !empty($userData['usermob']))
{
if(!empty($userData['useremail']))
{
$where = "useremail='".$userData['useremail']."'";
}
if(!empty($userData['usermob']))
{
$where = "usermob='".$userData['usermob']."'";
}
$this->db->select('*');
$this->db->from('users');
$this->db->where($where);
$result = $this->db->get()->result_array();
if(!empty($result))
{
if(!empty($userData['useremail']))
{
if(($userData['useremail']) && ($userData['userpass']))
{
$where = "useremail='".$userData['useremail']."' AND userpass='".$userData['userpass']."'";
$this->db->select('*');
$this->db->from('users');
$this->db->where($where);
$res = $this->db->get()->result_array();
if(!empty($res))
{
$arrData['id'] = $res[0]['u_id'];
$arrData['useremail'] = $res[0]['useremail'];
}
else
{
$arrData['errorLogin'] = 'Incorrect email or password';
}
}
}
if(!empty($userData['usermob']))
{
if(($userData['usermob']) && ($userData['userpass']))
{
$where = "usermob='".$userData['usermob']."' AND userpass='".$userData['userpass']."'";
$this->db->select('*');
$this->db->from('users');
$this->db->where($where);
$res = $this->db->get()->result_array();
if(!empty($res))
{
$arrData['id'] = $res[0]['u_id'];
$arrData['usermob'] = $res[0]['usermob'];
}
else
{
$arrData['errorLogin'] = 'Incorrect email or password';
}
}
}
}
else
{
$arrData['error'] = 'Please Enter username and password';
}
}
return $arrData;
}
I was trying to login with email and mobile number but my code gives only one access either with email or with mobile. i want help so that i can login with email and mobile number both.
I have tested this code using Postman, hope it can help:
public function signin($userData)
{
//get the data using useremail and userpass
$this->db->where('useremail', $userData['useremail']);
$this->db->where('userpass', $userData['userpass']);
$result = $this->db->get('users')->result_array();
//if there's no result, get the data using usermob and userpass
if (!$result) {
$this->db->where('usermob', $userData['usermob']);
$this->db->where('userpass', $userData['userpass']);
$result = $this->db->get('users')->result_array();
}
//if there's still no result, the username or password was incorect
if (!$result) {
$result = 'Wrong Username or Password';
}
return $result;
}

I have registration form to sign in but from admin panel admin can also add new user with that same form. how can check if form submitted by admin?

i have registration form to register new users, but the same time from admin panel, admin can also register new user with the same form. now the prob is how can i check if form is submitted by admin or not ?
its my user table
public function up()
{
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('username')->unique();
$table->string('email')->unique();
$table->string('password');
$table->boolean('active')->default(0);
$table->boolean('admin')->default(0);
$table->boolean('banned')->default(0);
$table->string('avatar')->nullable();
$table->string('activation_token')->nullable();
$table->string('remember_token')->nullable();
$table->timestamps();
});
}
and this is my Usercontroller
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class UserController extends \BaseController implements RemindableInterface {
use RemindableTrait;
//Rules required to register the user
public static $rules = array(
'username' => 'required|unique:users|alpha_dash|between:5,15',
'email' => 'required|email|unique:users',
'password' => 'required|alpha_dash|between:6,12|confirmed',
'g-recaptcha-response' => 'required',
);
/**
* Show the form for creating a new resource.
* GET /user/create
*
* #param string $username
* #param string $email
* #param string $password
* #param boolean $active
* #param string $activation_token
* #param string $filename
* #param int $points
* #return Response
*/
public function create($username, $email, $password, $active = 0, $activation_token = null, $filename = null)
{
$user = new User();
$user->username = $username;
$user->email = $email;
$user->password = $password;
$user->active = $active;
$user->activation_token = $activation_token;
if ($filename) {
$user->avatar = $filename;
}
$user->save();
return $user;
}
/**
* Show the form for editing the specified resource.
* GET /user/settings
*
* #return Response
*/
public function settings()
{
$user = User::where('id', Auth::user()->id)->first();
$data = array('user' => $user);
return View::make('user.settings', $data);
}
/**
* Update the specified resource in storage.
* PUT /user/{id}
*
* #param int $id
* #return Response
*/
public function update($id = null)
{
$input = Input::all();
$validator = Validator::make(
$input,
array(
'email' => 'required|email:unique:users',
'password' => 'alpha_dash|between:6,12|confirmed',
'username' => 'alpha_dash|between:5,15',
)
);
if ($validator->passes()) {
if($id == null) {
$id = $input['user'];
}
$user = User::find($id);
$inputPassword = isset($input['password']) ? $input['password'] : null;
if (!empty($inputPassword)) {
$user->password = Hash::make($inputPassword);
}
$inputUsername = isset($input['username']) ? $input['username'] : null;
if (!empty($inputUsername)) {
$user->username = $inputUsername;
}
$inputEmail = isset($input['email']) ? $input['email'] : null;
if (!empty($inputEmail) && $user->email != $inputEmail) {
$user->email = $inputEmail;
if(!$user->admin) {
$email = $inputEmail;
$user->active = 0;
$activation_token = str_random(64);
$user->activation_token = $activation_token;
$data = array('username' => $user->username, 'activation_token' => $activation_token);
Mail::send(
'emails.welcome',
$data,
function ($message) use ($email) {
$message->to($email)->subject(Lang::get('words.activation-subject'));
}
);
}
}
$user->save();
$redirectURL = $user->admin ? 'admin/user' : 'settings';
return json_encode(array('status' => 'success', 'message' => 'Updated', 'url' => $redirectURL));
}
return json_encode(array('status' => 'error', 'message' => $validator->messages()->all()[0]));
}
public function sendActivation()
{
$user = Auth::user();
if (!$user->active) {
$email = $user->email;
$activation_token = str_random(64);
$user->activation_token = $activation_token;
$data = array('username' => $user->username, 'activation_token' => $activation_token);
Mail::send(
'emails.welcome',
$data,
function ($message) use ($email) {
$message->to($email)->subject(Lang::get('words.activation-subject'));
}
);
$user->save();
return Redirect::to('/')->with(array('status' => 'showSuccessToast', 'message' => Lang::get('words.activation-resend')));
} else {
return Redirect::to('/')->with(array('status' => 'showErrorToast', 'message' => Lang::get('words.activation-resend')));
}
}
public function upload($id, $type)
{
if (!Auth::guest()) {
$input = Input::all();
$validator = Validator::make(
$input,
array(
'image' => 'mimes:jpeg,png'
)
);
if ($validator->passes()) {
$user = User::find($id);
$mediaDir = 'uploads/' . $type . 's/';
$oldImgPath = $mediaDir . $user->$type . '.jpg';
$name = Custom::slugify('');
$newImg = Custom::imgUpload($input['image'], $name, $type.'s', false, false);
$newImg .= '/' . $name;
$user->$type = $newImg;
$user->save();
if (file_exists($oldImgPath)) {
unlink($oldImgPath);
}
return json_encode(array('status' => 'success', 'message' => Lang::get('words.profile-updated'), 'img' => $newImg));
}
return json_encode(array('status' => 'error', 'message' => $validator->messages()->all()[0]));
} else {
return json_encode(array('status' => 'error', 'message' => Lang::get('words.auth-failed')));
}
}
/**
* Remove the specified resource from storage.
* DELETE /user/{id}
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
//
}
/**
* Login the user.
* POST /login
*
* #return Response
*/
public function login()
{
// get login POST data
$email_login = array(
'email' => Input::get('email'),
'password' => Input::get('password'),
);
$username_login = array(
'username' => Input::get('email'),
'password' => Input::get('password'),
);
$remember = Input::get('remember') == 'on' ? true : false;
if (Auth::attempt($email_login, $remember) || Auth::attempt($username_login, $remember)) {
if (Auth::user()->banned) {
Auth::logout();
return json_encode(array('status' => 'error', 'message' => Lang::get('words.you-banned')));
}
return json_encode(array('status' => 'success', 'message' => Lang::get('words.login-success')));
} else {
return json_encode(array('status' => 'error', 'message' => Lang::get('words.login-error')));
}
}
// *********** FACEBOOK OAUTH SIGNIN/SIGNUP ********** //
public function loginWithFacebook()
{
$settings = Setting::first();
$code = Input::get('code');
$fb = OAuth::consumer('Facebook');
if (!empty($code)) {
// This was a callback request from facebook, get the token
$token = $fb->requestAccessToken($code);
// Send a request with it
$result = json_decode($fb->request('/me'), true);
$oauth_userid = $result['id'];
$oauth_username = $result['name'];
$oauth_username = Custom::slugify($oauth_username);
$oauth_email = isset($result['email']) ? $result['email'] : $oauth_username.'#facebook.com';
//dd($oauth_username);
if (isset($oauth_userid) && isset($oauth_username)) {
$fb_auth = OauthUser::where('oauth_uid', $oauth_userid)->where('service', 'facebook')->first();
if (isset($fb_auth->id)) {
$user = User::find($fb_auth->user_id);
} else {
// Execute Add or Login Oauth User
$user = User::where('email', $oauth_email)->first();
if (!isset($user->id)) {
$username = $this->createUsernameIfExists($oauth_username);
$email = $oauth_email;
$password = Hash::make(Custom::slugify('', 12));
/*if ($email != $oauth_username.'#facebook.com') {
$active = 1;
} else {
$active = 0;
}*/
$user = $this->create($username, $email, $password, 1);
$new_oauth_user = new OauthUser();
$new_oauth_user->user_id = $user->id;
$new_oauth_user->service = 'facebook';
$new_oauth_user->oauth_uid = $oauth_userid;
$new_oauth_user->save();
} else {
// Redirect and send error message that email already exists. Let them know that they can request to reset password if they do not remember
return Redirect::to('/')->with(array('status' => 'error', 'message' => Lang::get('words.username-exists')));
}
}
// Redirect to new User Login;
Auth::login($user, true);
return Redirect::to('/')->with(array('status' => 'success', 'message' => Lang::get('words.login-success')));
}
} else {
$url = $fb->getAuthorizationUri();
// return to facebook login url
return Redirect::to((string)$url);
}
}
// *********** TWITTER OAUTH SIGNIN/SIGNUP ********** //
public function loginWithTwitter()
{
$settings = Setting::first();
// get data from input
$token = Input::get('oauth_token');
$verify = Input::get('oauth_verifier');
// get twitter service
$tw = OAuth::consumer('Twitter');
// if code is provided get user data and sign in
if (!empty($token) && !empty($verify)) {
// This was a callback request from twitter, get the token
$token = $tw->requestAccessToken($token, $verify);
// Send a request with it
$result = json_decode($tw->request('account/verify_credentials.json'), true);
$oauth_userid = $result['id'];
$oauth_username = Custom::slugify($result['screen_name']);
$oauth_email = $oauth_username.'#twitter.com';
if (isset($oauth_userid) && isset($oauth_username)) {
$twitter_auth = OauthUser::where('oauth_uid', $oauth_userid)->where('service', 'twitter')->first();
if (isset($twitter_auth->id)) {
$user = User::find($twitter_auth->user_id);
} else {
// Execute Add or Login Oauth User
$user = User::where('email', $oauth_email)->first();
if (!isset($user->id)) {
$username = $this->createUsernameIfExists($oauth_username);
$email = $oauth_email;
$password = Hash::make(Custom::slugify('', 12));
$user = $this->create($username, $email, $password, 1);
$new_oauth_user = new OauthUser();
$new_oauth_user->user_id = $user->id;
$new_oauth_user->service = 'twitter';
$new_oauth_user->oauth_uid = $oauth_userid;
$new_oauth_user->save();
} else {
// Redirect and send error message that email already exists. Let them know that they can request to reset password if they do not remember
return Redirect::to('/')->with(array('status' => 'error', 'message' => Lang::get('words.username-exists')));
}
}
// Redirect to new User Login;
Auth::login($user, true);
return Redirect::to('/')->with(array('status' => 'success', 'message' => Lang::get('words.login-success')));
}
} else {
// get request token
$reqToken = $tw->requestRequestToken();
// get Authorization Uri sending the request token
$url = $tw->getAuthorizationUri(array('oauth_token' => $reqToken->getRequestToken()));
//dd($url);
return Redirect::to((string)$url);
}
}
// *********** GOOGLE OAUTH SIGNIN/SIGNUP ********** //
public function loginWithGoogle()
{
$settings = Setting::first();
// get data from input
$code = Input::get('code');
// get google service
$googleService = OAuth::consumer('Google');
// if code is provided get user data and sign in
if (!empty($code)) {
// This was a callback request from google, get the token
$token = $googleService->requestAccessToken($code);
// Send a request with it
$result = json_decode($googleService->request('https://www.googleapis.com/oauth2/v1/userinfo'), true);
$oauth_userid = $result['id'];
$oauth_username = Custom::slugify($result['name']);
$oauth_email = isset($result['email']) ? $result['email'] : $oauth_username.'#gmail.com';
if (isset($oauth_userid) && isset($oauth_username) && isset($oauth_email)) {
$google_auth = OauthUser::where('oauth_uid', $oauth_userid)->where('service', 'google')->first();
if (isset($google_auth->id)) {
$user = User::find($google_auth->user_id);
} else {
// Execute Add or Login Oauth User
$user = User::where('email', $oauth_email)->first();
if (!isset($user->id)) {
$username = $this->createUsernameIfExists($oauth_username);
$email = $oauth_email;
$password = Hash::make(Custom::slugify('', 12));
/*if ($email != $oauth_username.'#gmail.com') {
$active = 1;
} else {
$active = 0;
}*/
$user = $this->create($username, $email, $password, 1);
$new_oauth_user = new OauthUser();
$new_oauth_user->user_id = $user->id;
$new_oauth_user->service = 'google';
$new_oauth_user->oauth_uid = $oauth_userid;
$new_oauth_user->save();
} else {
// Redirect and send error message that email already exists. Let them know that they can request to reset password if they do not remember
return Redirect::to('/')->with(array('status' => 'error', 'message' => Lang::get('words.username-exists')));
}
}
// Redirect to new User Login;
Auth::login($user, true);
return Redirect::to('/')->with(array('status' => 'success', 'message' => Lang::get('words.login-success')));
}
} else {
// get googleService authorization
$url = $googleService->getAuthorizationUri();
return Redirect::to((string)$url);
}
}
/**
* Signup Signup.
* POST /signup
*
* #return Response
*/
public function signup()
{
$validator = Validator::make(Input::all(), static::$rules);
if ($validator->fails()) {
$message = $validator->messages()->all()[0];
return json_encode(array('status' => 'error', 'message' => $message));
}
$username = htmlspecialchars(stripslashes(Input::get('username')));
$user = User::where('username', '=', $username)->first();
if (!$user) {
$email = Input::get('email');
$activation_token = str_random(64);
$user = $this->create($username, $email, Hash::make(Input::get('password')), 0, $activation_token);
$data = array('username' => $username, 'activation_token' => $activation_token);
Mail::send(
'emails.welcome',
$data,
function ($message) use ($email) {
$message->to($email)->subject(Lang::get('words.activation-subject'));
}
);
return json_encode(array('status' => 'success', 'message' => Lang::get('words.register-success')));
} else {
return json_encode(array('status' => 'error', 'message' => Lang::get('words.username-exists')));
}
}
private function createUsernameIfExists($username)
{
$user = User::where('username', $username)->first();
while (isset($user->id)) {
$username = $username.Custom::slugify('', 4);
$user = User::where('username', $username)->first();
}
return $username;
}
public function activation()
{
$token = Input::get('token');
if ($token) {
$user = User::where('activation_token', $token)->where('active', 0)->first();
if ($user) {
$user->activation_token = null;
$user->active = 1;
$user->save();
return Redirect::to('/')->with(array('status' => 'showSuccessToast', 'message' => Lang::get('words.email-verified')));
} else {
return Redirect::to('/')->with(array('status' => 'showErrorToast', 'message' => Lang::get('words.email-already-verified')));
}
}
}
In the controller:
If (Auth::check()) && Auth::user()->admin) { 'is admin' ) else { 'is sign in' }
Not sure what difference it will make in saving this user but that will be the way to differentiate in your public function store() {} UserController.
There are so many ways to do this. The first one is, there is a column in users schema:
$table->boolean('admin')->default(0);
You can use this column as, put the value 1 in case the form is submit by admin, otherwise its default value is 0.
The another method is, create a column like created_by with a default value of 0 for users. Put its value to the logged in userId, by this you can identify, by which user the registration is done.

Cant create a admin session in CI

I want to create a login system in CodeIgniter.
I have this in my controller:
public function user_login_process()
{
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password')
);
$result = $this->login_database->login($data);
if ($result == TRUE) {
$username = $this->input->post('username');
$result = $this->login_database->read_user_information($username);
if ($result != false) {
$session_data = array(
'username' => $result[0]->username,
'email' => $result[0]->email,
);
$this->session->set_userdata('logged_in', $session_data);
if (isset($this->session->userdata['logged_in'])) {
if( $username="admin"){
$result1 = $this->login_database->read_admin_information($username);
if ($result1 != false) {
$session_data = array(
'username' => $result1[0]->username,
);
$this->session->set_userdata('admin', $session_data);
$this->load->view('admin_page');
}}}
else {
$this->load->view('home_page');
}}
} else {
$data = array(
'error_message' => 'Invalid Username or Password'
);
$this->load->view('login_form', $data);
}
//}
I have this in my model:
public function login($data) {
$condition = "username =" . "'" . $data['username'] . "' AND " . "password =" . "'" . $data['password'] . "'";
$this->db->select('*');
$this->db->from('user');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return true;
} else {
return false;
}
}
// Read data from database to show data in admin page
public function read_user_information($username) {//Will read the data for loginn
$condition = "username =" . "'" . $username . "'";
$this->db->select('*');
$this->db->from('user');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->result();
} else {
return false;
}
}
public function read_admin_information($username) {//Will read the data for loginn
$condition = "username =" . "'" . $username . "'";
$this->db->select('*');
$this->db->from('user');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->result();
} else {
return false;
}
}
So I'm trying to create a session which differentiates a user if it is a normal or is admin(username=admin). The problem is that after I login like admin or not this always takes me to the admin page. What it should do: it should take me to the home_page if user is not admin but is logged in.
Have I done something wrong? I have read the session class of CI before I did this. Can someone help me to do this in right way? Thanks!
you are not comparing, you are assigning here:
if( $username="admin"){ // will assign 'admin' to $username
Should be:
if( $username=="admin"){ // will compare $username == 'admin'
try this sir: (if you have a usertype on your table)
for example:
User_Account:(The table)
User_type(1 is admin)(0 is client)
ID | First_name | Last_name | Username | Password | User_type
1 Michael Jordan MJ23 6rings 1
2 Kobe Bryant KB24 5rings 0
MODEL:
public function login($user,$pass){
$data = array(
'Username' => $user,
'Password' => $pass);
$query = $this->db->get_where('user_account',$data);
return $query->result_array();
}
VIEW:
<form action="<?php echo base_url(); ?>index.php/My_Controller/login_user" method="post">
Username: <input type="text" name="username"/><br/>
Password: <input type="password" name="password"/><br/>
<button type="submit">LOGIN</button>
</form>
CONTROLLER:
public function login_user(){
$user = $this->input->post('username');//this is from the name on input
$pass = $this->input->post('password');//this is from the name on input
$result=$this->My_Model->login($user,$pass);
$usertype = $result["0"]["User_type"];//this is from the database, whenever you login a user which is valid this is what you will use to see what is his User_type
if($usertype == 1){
redirect('My_Controller/show_admin');
}
else if($usertype == 0){
redirect('My_Controller/show_client');
}
}
Try this out: if you have questions just comment!

Session Doesn't work in codeigniter

In my project, session is work fine before few days.But now it doesn't work. i can't find the error. plsease help me. it displays error called Severity: Notice
Message: Undefined index: firstname
Filename: user_include/header.php
Line Number: 5
A PHP Error was encountered
Severity: Notice
Message: Undefined
index: id
Filename: user_include/header.php
Line Number: 7
controller
/ Check for user login process
public function user_login_process() {
$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
if(isset($this->session->userdata['logged_in'])){
//$this->load->view('admin_page');
$this->home();
}else{
$this->load->view('user_site/login_form');
}
} else {
$data = array(
'email' => $this->input->post('email'),
'password' => $this->input->post('password')
);
$result = $this->login_database->login($data);
if ($result == TRUE) {
$email = $this->input->post('email');
$result = $this->login_database->read_user_information($email);
if ($result != false) {
$session_data = array(
'firstname' => $result[0]->firstname,
'email' => $result[0]->email,
'id' => $result[0]->id,
);
// Add user data in session
$this->session->set_userdata('logged_in', $session_data);
$this->load->view("user_include/header");
$this->load->view('user_site/index');
}
} else {
$data = array(
'error_message' => 'Invalid Username or Password'
);
$this->load->view('user_site/login_form', $data);
}
}
}
// Logout
public function logout() {
// Removing session data
$sess_array = array(
'email' => ''
);
$this->session->unset_userdata('logged_in', $sess_array);
$data['message_display'] = 'Successfully Logout';
$this->load->view('user_site/login_form', $data);
}
}
?>
model
// Read data using username and password
public function login($data) {
$condition = "email =" . "'" . $data['email'] . "' AND " . "password =" . "'" . $data['password'] . "'";
$this->db->select('*');
$this->db->from('user');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return true;
} else {
return false;
}
}
// Read data from database to show data in admin page
public function read_user_information($email) {
$condition = "email =" . "'" . $email . "'";
$this->db->select('*');
$this->db->from('user');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->result();
} else {
return false;
}
}
}
?>
view
<?php
if (isset($this->session->userdata['logged_in'])) {
$firstname = ($this->session->userdata['logged_in']['firstname']);
$email = ($this->session->userdata['logged_in']['email']);
$id = ($this->session->userdata['logged_in']['id']);
} else {
header("location: login");
}
the error is in you user_include/header.php , check the id and firstname are set before you echo them out.
In your model replace following code by given code:
public function read_user_information($email) {
$condition = "email =" . "'" . $email . "'";
$this->db->select('*');
$this->db->from('user');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->result();
} else {
return false;
}
}
To
public function read_user_information($email) {
$this->db->select('firstname, email, id');
$this->db->from('user');
$this->db->where('email',$email);
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->row_array();
} else {
return false;
}
}
In your controller replace following code by given
$email = $this->input->post('email');
$result = $this->login_database->read_user_information($email);
if ($result != false) {
$session_data = array(
'firstname' => $result[0]->firstname,
'email' => $result[0]->email,
'id' => $result[0]->id,
);
// Add user data in session
$this->session->set_userdata('logged_in', $session_data);
$this->load->view("user_include/header");
$this->load->view('user_site/index');
}
To
$email = $this->input->post('email');
$user_details = $this->login_database->read_user_information($email);
if ($user_details != false) {
// Add user data in session
$this->session->set_userdata('logged_in', $user_details);
$this->load->view("user_include/header");
$this->load->view('user_site/index');
}
In view, replace your code by following:
<?php
$user_details = $this->session->userdata['logged_in']);
if ($user_details != "") {
$firstname = $user_details['firstname'];
$email = $user_details['email'];
$id = $user_details['id'];
} else {
header("location: login");
}

password_hash not updating when submit form

When I submit my form if password fields are submitted it should update the password else if empty does not update password.
I cannot seem to get the password_hash to update very strange. I can create new users fine with it but not update there password.
All other post are working fine update fine.
Not sure why password not updating? How am I able to fix issue thanks in advance.
<?php
class Model_user extends CI_Model {
public function edit_user($user_id, $data) {
$data = array(
'username' => $data['username'],
'user_group_id' => $data['user_group_id'],
'firstname' => $data['firstname'],
'lastname' => $data['lastname'],
'email' => $data['email'],
'image' => $data['image'],
'status' => $data['status']
);
$this->db->set($data);
$this->db->where('user_id', $user_id);
$this->db->update($this->db->dbprefix . 'user');
if ($data['password']) {
$options = [
'cost' => 11,
'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM),
];
$data = array(
'password' => password_hash($_POST['password'], $options)
);
$this->db->set($data);
$this->db->where('user_id', $user_id);
$this->db->update($this->db->dbprefix . 'user');
}
}
}
Controller
<?php
class Users extends MY_Controller {
public function __construct() {
parent::__construct();
$this->load->model('admin/user/model_user');
}
public function index() {
$this->get_form();
}
public function update() {
$this->form_validation->set_rules('username', 'Username', 'required');
if ($this->form_validation->run($this) == FALSE) {
$this->get_form();
} else {
$this->model_user->edit_user($this->uri->segment(4), $_POST);
redirect('admin/user');
}
}
public function get_form() {
$data['title'] = "Users";
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'text' => 'Home',
'href' => site_url('admin/dashboard')
);
$data['breadcrumbs'][] = array(
'text' => "Users",
'href' => site_url('admin/user')
);
$user_info = $this->model_user->get_user($this->uri->segment(4));
if (isset($_POST['username'])) {
$data['username'] = $_POST['username'];
} elseif (!empty($user_info)) {
$data['username'] = $user_info['username'];
} else {
$data['username'] = '';
}
if (isset($_POST['user_group_id'])) {
$data['user_group_id'] = $_POST['user_group_id'];
} elseif (!empty($user_info)) {
$data['user_group_id'] = $user_info['user_group_id'];
} else {
$data['user_group_id'] = '';
}
$this->load->model('admin/user_group/user_group_model');
$data['user_groups'] = $this->user_group_model->get_user_groups();
if (isset($_POST['password'])) {
$data['password'] = $_POST['password'];
} else {
$data['password'] = '';
}
if (isset($_POST['confirm'])) {
$data['confirm'] = $_POST['confirm'];
} else {
$data['confirm'] = '';
}
if (isset($_POST['firstname'])) {
$data['firstname'] = $_POST['firstname'];
} elseif (!empty($user_info)) {
$data['firstname'] = $user_info['firstname'];
} else {
$data['firstname'] = '';
}
if (isset($_POST['lastname'])) {
$data['lastname'] = $_POST['lastname'];
} elseif (!empty($user_info)) {
$data['lastname'] = $user_info['lastname'];
} else {
$data['lastname'] = '';
}
if (isset($_POST['email'])) {
$data['email'] = $_POST['email'];
} elseif (!empty($user_info)) {
$data['email'] = $user_info['email'];
} else {
$data['email'] = '';
}
if (isset($_POST['image'])) {
$data['image'] = $_POST['image'];
} elseif (!empty($user_info)) {
$data['image'] = $user_info['image'];
} else {
$data['image'] = '';
}
$this->load->model('admin/tool/model_tool_image');
if (isset($_POST['image']) && is_file(FCPATH . 'image/catalog/' . $_POST['image'])) {
$data['thumb'] = $this->model_tool_image->resize($_POST['image'], 100, 100);
} elseif (!empty($user_info) && $user_info['image'] && is_file(FCPATH . 'image/catalog/' . $user_info['image'])) {
$data['thumb'] = $this->model_tool_image->resize($user_info['image'], 100, 100);
} else {
$data['thumb'] = $this->model_tool_image->resize('no_image.png', 100, 100);
}
$data['placeholder'] = $this->model_tool_image->resize('no_image.png', 100, 100);
if (isset($_POST['status'])) {
$data['status'] = $_POST['status'];
} elseif (!empty($user_info)) {
$data['status'] = $user_info['status'];
} else {
$data['status'] = 0;
}
$this->load->view('template/user/user_form_view', $data);
}
}
Take a closer look at the edit_user function. You receive $data but you immediately overwrite it. Please note that you don't set a password key to the newly created array. Then you check if ($data['password']) but that will never be true therefore the update will never be done.
There is a problem in your password_hash($_POST['password'], $options).
You passed $_POST['password'] instead of $data['password'].
It took me a while to figure it out I needed to create another variable out side of the if statement in my model like below and then was able to update if new password present.
All working now.
$input_password = $this->input->post('password');
if ($input_password) {
$password = password_hash($input_password, PASSWORD_BCRYPT);
$data_password = array(
'password' => $password
);
$this->db->where('user_id', $user_id);
$this->db->update($this->db->dbprefix . 'user', $data_password);
}

Categories