Laravel hash password in controller - php

I want to make a password hash inside the Controller so that the information is stored to the database.
My storing function is;
public function store(Request $request)
{
$validator = \Validator::make($request->all(), ['fullname' => 'required',
'email' => 'required|email|max:255|unique:users',
'username' => 'required|max:255|unique:users',
'password' => 'required',]);
if ($validator->fails()) {
return response()->json([
'1' => 'Your information not stored!',
]);
}
else {
$newuser = new User;
$newuser -> fullname = request('fullname');
$newuser -> email = request('email');
$newuser -> password = request('password');
$newuser -> username = request('username');
$newuser -> status = 1;
$newuser -> role_id = 1;
$newuser -> save();
return response()->json([
'2' => 'Your information stored successfuly!',
]);
}
This works correctly. But, I want to hash the password.
https://laravel.com/docs/5.0/hashing
https://laracasts.com/discuss/channels/requests/how-to-hash-user-input-password-when-using-form-validation-in-form-request-laravel-5
public function setPasswordAttribute($value)
{
$this->attributes['password'] = bcrypt($value);
}
This does not work. Does any of you have any suggestions?

just change
$newuser -> password = bcrypt(request('password'));

Change:
$newuser->password = request('password');
To:
$newuser->password = bcrypt(request('password'));
See the docs

Related

credentials do not match our records

I am currently working on POS in laravel 8. I am having an error when I login in that "credentials do not match our records" When I login in through the default Register page than it works fine but when I register through internal panel than the data goes to the database but I face error when I log in.
Code for registration through panel:
public function store(Request $request)
{
$users = new User;
$users->name = $request->name;
$users->email = $request->email;
$users->password = Hash::make($request->name);
// $users->password = bcrypt($request->name);
$users->is_admin = $request->is_admin;
$users->save();
if($users){
return redirect()->back()->with('User Created Successfully');
}
return redirect()->back()->with('User Failed Created');
}
Default register code:
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
Your panel registration form is hashing the name input and not the password input.
$users->password = Hash::make($request->name);
Should probably be
$users->password = Hash::make($request->password);
#Code for registration through panel code should be like this#
public function store(Request $request){
$users = new User;
$users->name = $request->name;
$users->email = $request->email;
$users->password = Hash::make($request->password);
$users->is_admin = $request->is_admin;
$users->save();
if($users){
return redirect()->back()->with('User Created Successfully');
}
return redirect()->back()->with('User Failed Created');
}

How can I decrypt password to login in laravel?

While changing the password I am using this function
public function passwordChange(Request $request, $userId)
{
$user = User::find($userId);
$user->password = Crypt::encrypt(Input::get('password'));
$user->save();
return redirect('my-profile');
}
So in my mongoDb database password insert in encrypted form, So whenever I have to login in system at that time how can I compare my password with password of database
public function authenticate(Request $request)
{
$rules = array(
'company_email' => 'required|email|exists:users,company_email',
'password' => 'required|string|max:20|min:4',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
return view('pages.login')->with('v_errors', $validator->errors()->messages());
}
else
{
//get email and query
$authenticateMe = $request->only('company_email', 'password');
$user = User::where($authenticateMe)->first();
if (empty($user))
{
return view('pages.login')->with('not_exists', 'true');
}
//session set
// Session::put('key', $user->username, $user->file);
Session::put('key', ['username' => $user->username, 'email' => $user->company_email, 'userId' => $user->id, 'profilePicture' => $user->file]);
return redirect('my-profile');
}
}
I am not using php artisan make:auth
will anyone please help??
Instead of encrypting the password, use hashing. Laravel has its own documentation about how to use that: https://laravel.com/docs/5.8/hashing
Simply you can not decrypt an encrypted password but you can check user credentials by adding an array of user email & password to Auth::attempt() function Here is a link to the description: https://laravel.com/docs/5.8/authentication#authenticating-users?
Here is your function using Auth::attempt():
public function authenticate(Request $request)
{
$rules = array(
'company_email' => 'required|email|exists:users,company_email',
'password' => 'required|string|max:20|min:4',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
return view('pages.login')->with('v_errors', $validator->errors()->messages());
}
else
{
//get email and query
$authenticateMe = $request->only('company_email', 'password');
if (Auth::attempt($authenticateMe)) {
$user = User::find(Auth::user()->id);
//session set
// Session::put('key', $user->username, $user->file);
Session::put('key', ['username' => $user->username, 'email' => $user->company_email, 'userId' => $user->id, 'profilePicture' => $user->file]);
return redirect('my-profile');
}else{
return view('pages.login')->with('not_exists', 'true');
}
}
}
And do not forget to add use Auth; to the function controller

Logout user from all browser when password is reset in laravel 5.6

When the user changes their password, they get Logged Out from the browser. However, if they are logged into another browser at the same time they stay logged in on the other browser.
I want to log out the user from all browsers they are logged into when they reset their password.
Here login controller.
function checklogin(Request $request)
{
$this->validate($request, ['email' => 'required|email', 'password' => 'required|string|min:3']);
$user_data = array(
'email' => $request->get('email') ,
'password' => $request->get('password')
);
$remember_me = $request->has('remember') ? true : false;
if (Auth::attempt($user_data, $remember_me))
{
return redirect()->intended('dashboard');
}
else
{
return back()->with('error', 'Wrong Login Details');
}
}
send mail function as below
function sendEmail(Request $request)
{
$this->validate($request, ['email' => 'required|exists:users']);
$email = $request->email;
$name = User::where('email', $email)->first();
$name = $name->name;
$token = Password::getRepository()->createNewToken();
$link = url("password/reset?email=$email&token=$token");
$value = Password_resets::where('email', $email)->first();
if (isset($value))
{
Password_resets::where('email', $email)->update(['email' => $email, 'token' => $token]);
}
else
{
Password_resets::insert(['email' => $email, 'token' => $token]);
}
Mail::to($email)->send(new \App\Mail\ResetPassword($link, $name));
return redirect()->back()->with('success', 'Please check your Email for Password Reset');
}
password reset function as below
function resetpasswordchange(Request $request)
{
$passwordtoken = $request->input('passwordtoken');
$email = $request->input('email');
$user_password = $request->input('user_password');
$users['user'] = Password_resets::where('token', $passwordtoken)->where('email', $email)->get();
if (empty($users['user'][0]))
{
$settoken = '0';
}
else
{
$settoken = $users['user'][0]->token;
}
if (($settoken) == $passwordtoken)
{
$update = array(
'password' => bcrypt($user_password) ,
);
User::where('email', $email)->update($update);
/* Auth::logout();
auth()->logoutOtherDevices(bcrypt($user_password),'password');*/
return redirect()->route('login')->with('success', 'Password has been Updated.');
}
else
{
return redirect()->back()->with('error', 'Token & Email Not Match!.');
}
}
How I can logout the user from all browsers who they are logged already ?
Open App\Http\Kernel and inside the protected $middlewareGroups property uncomment the \Illuminate\Session\Middleware\AuthenticateSession::class middleware. This compares the password hash of the user to see if the session is valid or not.

how to make custom login in laravel 5.6?

I have used my own custom login without using auth. Here is my code
public function userLogin(Request $request){
if($request->isMethod('post')){
$data = $request->input();
$this->validate($request, [
'uemail'=> 'required|email',
'user_type'=> 'required',
'user_id' => 'required',
'upassword' => 'required|min:6',
],
[
'uemail.email' => 'Email must be valid',
'uemail.required' => 'Email is required',
'user_type.required' => 'Type is required',
'user_id.required' => 'Name is required',
'upassword.required' => 'Password is required',
'upassword.min' => 'Password must be at least 6 characters',
]);
$user_type = $data['user_type'];
$user_id = $data['user_id'];
$uemail = $data['uemail'];
$upassword = $data['upassword'];
$hashPass = bcrypt($upassword);
DB::enableQueryLog();
$user1 = User::where('type',$user_type)->where('user_id',$user_id)->where('email',$uemail)
->where('status',1)->where('deleted_at',null)->firstOrFail();
$user = DB::table('users')->where('type',$user_type)->where('user_id',$user_id)->where('email',$uemail)
->where('status',1)->where('deleted_at',null);
// $query = DB::getQueryLog();
// $query = end($query);
$isPasswordCorrect = Hash::check($upassword, $user1->password);
if($user == null){
echo "Failed"; die;
}
if($user->exists() && $isPasswordCorrect){
echo "Success"; die;
Session::put('userSession',$user1->email);
Session::put('loginSession',$user_type);
Session::put('idSession',$user1->user_id);
return redirect('/user/dashboard');
} else {
return redirect('/user')->>with('flash_message_error','Invalid Login Credentials..');
}
}
return view('death_notice.user_login');
}
This is my login function. But its not working. When the credentials is right it redirects to dashboard i.e that's correct, but when the email or password or other credentials is wrong it showing error message. But when if the user enter such data which is not in the database then it must show message that user doesn't exists. but its going to page not found error...
I want to have the solution of this problem.
Okay, first confirm that, you have a route like '/user' defined in your web.php
You haven't used get() in $user eloquent
$user = DB::table('users')->where('type',$user_type)->where('user_id',$user_id)->where('email',$uemail)
->where('status',1)->where('deleted_at',null)->get();
And it shows 404 not found error because you have used firstorFail() it will fail on no record matching and will show 404 not found error so
$user1 = User::where('type',$user_type)->where('user_id',$user_id)->where('email',$uemail)
->where('status',1)->where('deleted_at',null)->first();
if(empty($user1))
{
echo "user doesn't exists";exit;
}
As per my understanding the query $user and $user1 is same so my suggestion would be to use only one
I made the following corrections:
$data = $request; is sufficient, you don't need to do $data = $request->input();
Check the count on the Eloquent query like this count($users->get()), to check if user was found.
public function userLogin(Request $request){
if($request->isMethod('post')){
$data = $request->input();
$this->validate($request, [
'uemail'=> 'required|email',
'user_type'=> 'required',
'user_id' => 'required',
'upassword' => 'required|min:6',
],
[
'uemail.email' => 'Email must be valid',
'uemail.required' => 'Email is required',
'user_type.required' => 'Type is required',
'user_id.required' => 'Name is required',
'upassword.required' => 'Password is required',
'upassword.min' => 'Password must be at least 6 characters',
]);
$user_type = $data['user_type'];
$user_id = $data['user_id'];
$uemail = $data['uemail'];
$upassword = $data['upassword'];
$hashPass = bcrypt($upassword);
DB::enableQueryLog();
$user1 = User::where('type',$user_type)->where('user_id',$user_id)->where('email',$uemail)
->where('status',1)->where('deleted_at',null)->firstOrFail();
$users = DB::table('users')->where('type',$user_type)->where('user_id',$user_id)->where('email',$uemail)
->where('status',1)->where('deleted_at',null);
// $query = DB::getQueryLog();
// $query = end($query);
$isPasswordCorrect = Hash::check($upassword, $user1->password);
if(count($users->get()) == 1){
$user1 = $users->first();
$isPasswordCorrect = Hash::check($upassword, $user1->password);
echo "Success"; die;
Session::put('userSession',$user1->email);
Session::put('loginSession',$user_type);
Session::put('idSession',$user1->user_id);
return redirect('/user/dashboard');
} else {
return redirect('/user')->>with('flash_message_error','Invalid Login Credentials..');
}
}
return view('death_notice.user_login');
}
I have not tested the code, but the idea should be clear.
Use following code to custom login. it's for, Ajax login, you can modify according to your requirements.
function userLogin(Request $request)
{
$auth = false;
$credentials = $request->only('email', 'password');
// if user login credentials are correct then users logged in
if (Auth::attempt($credentials, $request->has('remember')))
{
$auth = true; // Success
}
// returns json response if login credentials are correct.
if ($auth == true)
{
return response()->json([
'auth' => $auth,
'intended' => URL::previous(),
'msg'=>1,
'name' => Auth::user()->name
]);
} else { // returns json response if login credentials are incorrect
return response()->json(['msg' => 2]);
}
}

Why Laravel 5 hashes password twice?

I set hash mutator for User model:
public function setPasswordAttribute($value)
{
\Log::info('Hash');
$this->attributes['password'] = \Hash::make($value);
}
Then I have a register function. The password hashes twice (checked in logs)
public function register(RegisterNewUser $request)
{
$user = new User();
$user->first_name = $request->first_name;
$user->last_name = $request->last_name;
$user->email = $request->email;
$user->password = $request->password;
$user->admin = true;
$user->save();
$this->auth->login($user);
return redirect()->route('dashboard');
}
Actually the function was originally written like this:
$user = new User($request->all());
$user->admin = true;
$user->save();
With the same result. Password gets hashed twice and I can't figure why.
I even tried:
get('test', function() {
$user = \CRM\EloquentModels\User::create([
'email' => 'zzz#zzz.zzz',
'last_name' => 'zzz',
'password' => 123
]);
});
And it gets hashed twice. No idea...

Categories