Auth with laravel - laravel

I do not know why the auth of laravel not work to me.. I have tried all but it still does not work, I use this code to login:
$user = User::where('rut', $request->rut)
->where('password', md5($request->password))
->first();
$employee = Employee::where('id_user', $user->id_user)
->first();
$permissions = User_Type_Permission::where('id_user_type', $user->id_user_type)->pluck('id_permission')->toArray();
$request->session()->put('id_user_type', $user->id_user_type);
$request->session()->put('id_branch_office', $employee->branch_office);
$request->session()->put($permissions);
if(Auth::login($user))
{
echo 1;
die();
return redirect('/account');
}
else
{
echo 2;
die();
return redirect('/login');
}
It returns "2" every time, and the user is not empty, it comes with values from database
I have used Attempt too:
$user = User::where('rut', $request->rut)
->where('password', md5($request->password))
->first();
$employee = Employee::where('id_user', $user->id_user)
->first();
$permissions = User_Type_Permission::where('id_user_type', $user->id_user_type)->pluck('id_permission')->toArray();
$request->session()->put('id_user_type', $user->id_user_type);
$request->session()->put('id_branch_office', $employee->branch_office);
$request->session()->put($permissions);
$credentials = [
'rut' => $user->rut,
'password' => md5($request->password),
];
if(Auth::attempt($credentials))
{
echo 1;
die();
return redirect('/account');
}
else
{
echo 2;
die();
return redirect('/login');
}
and it returns false too, the login information is correct, but Auth does not work at all, what can it be?
Thanks!

You should remove md5.. if you store the hashed password by bcrypt..
Auth::attempt() automatically check the plain text password in the request with the hashed in the database.
So the code should be
$credentials = [
'rut' => $user->rut,
'password' =>$request->password,
];
if(Auth::attempt($credentials))
{
echo 1;
die();
return redirect('/account');
}else{return redirect('/login')}
And put all the code you have written in the top to the true condition..
what you write is not correct ..
if authenticated make what i want..
Not put the code then check if authenticated!
I Hope this work with you!
Good luck!

Related

Laravel change password issue

For Laravel change password I did like this but why it is not working.. Its not updating password. I have done login page, registration everything working. But this giving me lot of trouble. Below is my code.
$returnValue = DB::table('users')->where('users_id', $users_id)->where('password', bcrypt($request->opassword))->update(['password'=>bcrypt($request->npassword)]);
if($returnValue >= 1)
{
$success['message'] = "Password updated successfully..";
return $this->sendResponse($success);
}
else
{
$error = "Entered Old password is not valid..";
return $this->sendResponse($error);
}
At first import Hash at the top of the controller. like this below
use Illuminate\Support\Facades\Hash;
After this , validate old password match with your database like this below
$user = User::findOrFail($users_id);
if (Hash::check($request->password, $user->password)) {
$user->password = Hash::make($request->opassword);
$user->update(); // $user->save();
$success['message'] = "Password updated successfully..";
return $this->sendResponse($success);
} else {
$error = "Entered Old password is not valid..";
return $this->sendResponse($error);
}
Try this.
You have issues with your keys:
$returnValue = DB::table('users')
->where('id', $users_id)
->where('password', bcrypt($request->opassword))
->update(['password'=>bcrypt($request->npassword)]);

How to write Laravel eloquent query inside model function?

Actually I don't know how to retrieve data from db using function and query inside model .Please help me what should i add inside model function.
Here is controller
public function checkAdmin(Request $request){
$data = array();
$data['email'] = $request->email;
$data['password'] = $request->password;
$found = AdminModel::checkAdmin($data);
if($found == TRUE){
echo "found";
}
else{
echo "sorry";
}
}
Here is the Model Function
public static function checkAdmin($data){
$found = $this->where('email',$data['email'])->where('password',$data['password'])->first();
return $found;
}
What is the purpose of the checkAdmin function? Are you trying to validate a login? If yes, Laravel does this for you out of the box with the Auth::attempt method:
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
// Authentication passed...
return redirect()->intended('dashboard');
}
https://laravel.com/docs/5.7/authentication#authenticating-users
However to answer your question, you could do so like this:
$userFound = AdminModel::where(['email' => $request->email, 'password] => $request->password)->count();
if($userFound){
echo "found";
}
else{
echo "sorry";
}

How to get the value of a variable from the collection

public function returnsTrueIfEmailIsVerified(Request $request)
{
// Gets the email
$email = request("email"); //johndoe#example.com for example
// Determine if zero or one ;
$user = User::where('email','=',$email)->get(); // 0 or 1 ;
$userCount = User::where('email','=',$email)->count(); // 0 or 1 ;
$confirmedValue = $user->get('confirmed');
$response ;
if ( $user === 1 && $confirmedValue === true ) {
$response = 'OK';
}
elseif ($user === 1 && $confirmedValue === false) {
$response = 'Not Confirmed yet';
}
else {
$response = 'Not Registered yet';
}
return response()->json(200,$response);
}
with that code I would return a response that if a user isn't registered or is registered and that if he's registered but that he's not confirmed yet..
I want to return something out from that I'm not just familiar with laravel's way
There are so many error in your code, I've fixed it and this code will work. I think you need to learn more Laravel and PHP.
public function returnsTrueIfEmailIsVerified(Request $request)
{
$email = request("email");
$user = User::where('email', '=', $email);
$response = [
'message' => ''
];
if ($user->count() === 1) {
$confirmedValue = $user->first()->confirmed;
if ($confirmedValue) {
$response['message'] = 'OK';
} else {
$response['message'] = 'Not Confirmed yet';
}
} else {
$response['message'] = 'Not Registered yet';
}
return response()->json($response, 200);
}
you can't response string as a json, json is key value pair.
User::where('email', '=', $email) return Query Builder not 0 or 1, use count() method;
you can't retrieve value from multiple items you have to specific item like this $user->get()[0]['confirmed] or use Laravel special method $user->first()->confirmed

Change password for logged in user (codeigniter)

Is there any solution how to make change password for logged in user? i want to make a change password for logged in user, the code i made only change user password with user id number 1. it doesn't change for logged in user. so any idea?
this is my controller:
public function update(){
$this->form_validation->set_rules('password', 'Current Password', 'required|alpha_numeric|min_length[6]|max_length[20]');
$this->form_validation->set_rules('newpass', 'New Password', 'required|alpha_numeric|min_length[6]|max_length[20]');
$this->form_validation->set_rules('confpassword', 'Confirm Password', 'required|alpha_numeric|min_length[6]|max_length[20]');
if($this->form_validation->run()){
$cur_password = $this->input->post('password');
$new_password = $this->input->post('newpass');
$conf_password = $this->input->post('confpassword');
$this->load->model('queries');
$userid = '1';
$passwd = $this->queries->getCurrPassword($userid);
if($passwd->password == $cur_password){
if($new_password == $conf_password){
if($this->queries->updatePassword($new_password, $userid)){
echo 'Password updated successfully';
}
else{
echo 'Failed to update password';
}
}
else{
echo 'New password & Confirm password is not matching';
}
}
else{
echo'Sorry! Current password is not matching';
}
}
else{
echo validation_errors();
}
This is my model:
public function getCurrPassword($userid){
$query = $this->db->where(['id'=>$userid])
->get('users');
if($query->num_rows() > 0){
return $query->row();
} }
public function updatePassword($new_password, $userid){
$data = array(
'password'=> $new_password
);
return $this->db->where('id', $userid)
->update('users', $data); }
You can initialize a session when the user logs in to the system at the beginning, and store the information of the user in that session, like this:
function login() {
$query = $this->db->select(*)
->from('table_name')
->where('your parameters....');
return $query->row();
}
function index() {
$userid = $this->login()->id; //id of the user which is currently logged IN
$this->session->set_userdata('current_userId', $userid);
}
You have now stored the id of currently logged IN user in the session. You can access the id by $this->session->userdata('current_userId');. Replace your $userid = '1' by the session data. Also, you will have to load the session library in order to do so.

Codeigniter password_verify method

I have this method in my Codeigniter (version 3.0) login module. It works fine but is this safe? Is any better solution to check login and password using PHP password_verify?
(PHP 5.6,
MySQL 5.0).
$user = $this->input->post('username');
$password = $this->input->post('password');
$myquery = $this->db->query("SELECT * FROM users WHERE user = '$user'");
$row = $myquery->row();
if (isset($row))
{
//Using hashed password - PASSWORD_BCRYPT method - from database
$hash = $row->password;
if (password_verify($password, $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
} else{
echo 'Wrong user!';
}
your code looks fine but you can do it a bit more in a CI Way and a bit more cleaner, in this case you are protected by sql injections and you have a bit more encapsulation
Try something like this:
public function checkLogin()
{
$this->load->library("form_validation");
$arrLoginRules = array
(
array(
"field" => "username",
"label" => "Benutzername",
"rules" => "trim|required"
),
array(
"field" => "password",
"label" => "Passwort",
"rules" => "trim|required"
)
);
$this->form_validation->set_rules($arrLoginRules);
try
{
if (!$this->form_validation->run()) throw new UnexpectedValueException(validation_errors());
$user = $this->input->post('username');
$password = $this->input->post('password');
$query = $this->db
->select("*")
->from("users")
->where("user", $user)
->get();
if ($query->num_rows() != 1) throw new UnexpectedValueException("Wrong user!");
$row = $query->row();
if (!password_verify($password, $row->hash)) throw new UnexpectedValueException("Invalid password!");
echo "valid user";
}
catch(Excecption $e)
{
echo $e->getMessage();
}
}
Fore more information, take a look at the Form validation
and the Query Builder documentation.

Resources