Retrieve password stored in db - laravel-5

I created user profile for my application. In this user profile, user can update their information just like email address, password, position, company name .. etc. If user want to change one of their information, user need to provide current password. And I will verify current password user provided is correct or not. Error is I can't verify the current password user provided. Below is the part of my user controller codes.
if($request['current_pwd'])
{
if($request['new_pwd'])
{
if($user->password == bcrypt($request['current_pwd']))
{
$user->password = bcrypt($request['new_pwd']);
}else{
return redirect()->back()->with(['message' => 'Wrong current password !']);
}
}elseif($user->password == bcrypt($request['current_pwd']))
{
$user->save();
}else{
return redirect()->back()->with(['message' => 'Wrong Current Password ! Check Again!']);
}
}else{
return redirect()->back()->with(['message' => 'Please enter your current password !']);
}
if the user want to change their current password, user must enter current password, new password, . If current password is equal the password stored in db, the new password will be update. If not, return with messages.

try this
first include Hash namespace in your controller,
use Illuminate\Support\Facades\Hash;
and use the following condition to make sure the current password is entered is valid
if($request->has('current_password')){
$current_password = $request->input('current_password');
if(!Hash::check($current_password,Auth::user()->password)){
return redirect()->back()->withInput()->withErrors([
'current_password' => 'You current password doesnot match with the logined user\'s !'
]);
}
}

You should match the encrypted "current password" entry with the password the user already has. You can get the user's password by using the function Auth::user()
So your condition would be:
if(bcrypt($request['current_pwd']) == Auth::user()) {
// Do password change
} else {
// Invalid password error
}
There is another function: getAuthPassword() which you can use by specifying the user ID, like so:
$user = User::find('1');
$user->getAuthPassword();
This will get the password for user ID 1

Due to salting! this kind of $user->password == bcrypt($request['current_pwd'] checking will not work!
Try making hash of same password you will get different hash!
So Check like this in laravel 5.2
$crypt = new Hashing\BcryptHasher();
$match = $crypt->check($user->password, $request['current_pwd']);

Related

How to call the password reset function in Strapi?

By default, Strapi has a welcome email template and password reset template. For the custom function we are writing, we want to create users without a password (or random password the user doesn't know). Then, when our function is finished, we want to send the user a welcome email (overwriting/disabling the default), with a password reset link. Therefore, we need to call the function/service to reset the password for the user, and receive the URL to send this in the welcome email.
However, currently I cannot find any information regarding the function/service to reset the user password. The only method I now see is to call http://localhost/auth/reset-password with the username or email, but would like to use a service such as strapi.services.user.resetPassword(userID) to get the URL back.
Does this function exists and/or is this possible?
Using Strapi 3.1.2
I have move my original answer here since it was more relevant to the question.
To reset a user password, we have to provide an identifier which is in this case the username. The possible steps are:
Query the user based on the identifier
Generate new hash password based on provided randomly generated value
Update the user password with the newly generated hash-password.
The implementation at a controller can be like this:
module.exports = {
resetPassword: async ctx => {
....
// Provide identifier and newPassword
const params = ctx.request.body;
const identifier = params.identifier
const newPassword = params.newPassword
// Get User based on identifier
const user = await strapi.query('user', 'users permissions').findOne({username: identifier});
// Generate new hash password
const password = await strapi.plugins['users-permissions'].services.user.hashPassword({password: newPassword});
// Update user password
await strapi
.query('user', 'users-permissions')
.update({ id: user.id }, { resetPasswordToken: null, password });
...
}
}
Don't forget to implement isOwner policy, or if the old password can be provided, we can validate the process using isValidPassword
// Validate given old password against user query result password
const isValidPassword = await strapi.plugins['users-permissions'].services.user.validatePassword(old.password, user.password);

How can disable the password filed ? ( laravel )

I've system don't required the password input just one input
when I login , so I created this:
public function do_login()
{
if (auth()->attempt(['user_id' => request('user_id')])) {
return redirect('home');
} else {
session()->flash('erorr', trans('Your Id Incorrect'));
return redirect('/')->withInput();
}
} //ends of do_login
and this is the error appears to me >
image
You can't use Auth's attempt without a password.
Since you're letting anyone in with just the ID, all you need is:
auth()->loginUsingId(request('user_id'))
You may want to look up the ID in your database first, or loginUsingId should throw an exception you can try/catch for.
If user_id doesn't correspond to the id column of your users table, you may need a slightly different approach:
$user = User::where('user_id', request('user_id'))->first();
auth()->login($user);

How to send original users password to his mail (before bcryption)

In my system users can't register. Admin adding all users in the admin panel and telling them your password is "xxx". Right now i need to send mail to users. Which contains users email and users password. System is working great. But there is one exception. In the mail, passwords is bcrypted. How can i solve? I don't any clue. I am using observers. In the model:
public static function boot()
{
parent::boot();
self::created(function () {
$customer = Customer::latest()->get()->first();
Mail::send('emails.user_login_informations', ['customer' => $customer], function($message) use($customer) {
$message->to($customer->email, $customer->name, $customer->password)
->subject('Login Information');
});
});
}
ps: this is working. In my mail:
Your email: xxx#example.com
Your Password: $2y$10$/GW5XNH9KGU.Nz05PZHFJuKb2ldhwYhS8oMX9e7HJIuFNJ
But this looks like:
Your email: xxx#example.com
Your Password: 123
You can create a temporary password field and delete it upon user activation. I needed this for a real world example. For instance:
Event::listen('rainlab.user.activate', function($user) {
$user->temp_password = null;
$user->save();
});
User::saving(function ($user) {
$password = post('User.password');
if ($password && ! $user->attributes['is_activated']) {
$user->temp_password = $password;
}
});
As mentioned above though, this includes a big security risk.
You hash user passwords to increase the security. The Hashing functionality is a one way hashing, so it can't be reversed.
A better way would be to create a password reset token und send it to the user. So the user can set a new password with the email address / token combination. To increase this method you could let the token expire after 30 minutes or so.

Password verify always returns fail in Laravel (Hash::check)

I've got an issue when I try to validate the post password via Hash::check in Laravel 5.5
I made a posts table (in this case sales table) with password column. When I try to create the post, it's working perfectly and the password is hashed and also belongs to logged in User. Then on the current post page is a button with an input (password) to delete that specific post, but the condition is always false.
My Controller public function destroy(Request $request, $id)
$input_pass = request('input_password');
$sale = Sale::find($id);
$hashed = $sale->password;
// Check if sale password is correct
if (Hash::check($input_pass, $sale->password)) {
$sale->delete();
} else {
// something else to do
}
For the post store, I used bcrypt method to hash the password. I've been also trying to dd('sale->password') which refers to column in sales table (correct) and dd('$input_pass') which refers to typed in password in DELETE form (also correct) - so I'm a little bit confused, why the pass don't match.
From your comment I find that you have a logical error where you initially hash your password and persist it in DB.
You are passing the string password to bcrypt where it should actually be something like request('password')
Change
'password' => bcrypt('password'),
to
'password' => bcrypt(request('password')),

Laravel - How to check value with another encrypted in DB

I am developing a sales system where every user has an account. To authenticate users I store passwords with bcrypt and use the Laravel Auth library as follows:
$data = $request->only('user', 'password');
if (\Auth::attempt($data)){
#redirect dashboard
}
In the Point Of Sale screen, user can add special products that require a PIN (The PIN is the password of some users with privileges).
When i call a button click to save the sale, in my Request class i add this validation (i only need to check if there are some special products, and if, check the PIN that have to match in the DB), i use this code:
$allowed_pin = true;
foreach (Request::get('products') as $product) {
if($product["special_perm"] === "1"){
$pin = $product["pin"];
$user = User::where('password', '=', bcrypt($pin))->first();
if ($user) {
$allowed_pin = true;
} else {
$allowed_pin = false;
}
}
}
The problem is when i compare password in Request class, if i use dd() it show me "$2y$10$AasS5/FTWv28PmYuABfqve4Ao6m1U9zxdUE6ZoHJWcfpn19sd4wcG" and real password hashed in database is "$2y$10$DmefHppecIjuanjRbcj82OPyjhi.L0/4YGd62LYCvkDTGjXxL25fG"
and they not matching.
Does Auth class use some internal encryption different to bcrypt?
To compare the plain text password with the encrypted one, use Hash::check('plain-text', $hashedPassword)
Check out the Laravel docs: https://laravel.com/docs/5.4/hashing

Resources