Update logged user password laravel 5 - php

i want to add password update option for logged user therefore i used following code
controller auth\authController.php
public function updatePassword()
{
$user = Auth::user();
$rules = array(
'old_password' => 'required',
'password' => 'required|alphaNum|between:6,16|confirmed'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::route('change-password', $user->id)->withErrors($validator);
} else {
if (!Hash::check(Input::get('old_password'), $user->password)) {
return Redirect::route('change-password', $user->id)->withErrors('Your old password does not match');
} else {
$user->password = Input::get('password');
$user->save();
return Redirect::route('change-password', $user->id)->with("message", "Password have been changed");
}
}
}
Routes
Route::post('change-password', 'Auth\AuthController#updatePassword');
Route::get('change-password', 'Auth\AuthController#updatePassword');
im getting following error
FatalErrorException in AuthController.php line 123:
Class 'App\Http\Controllers\Auth\Auth' not found
for this line "$user = Auth::user();"

Your question has hidden answer..I have similar problem like #faz..I have done the trick with his question's code actually
The correct way to achieve this -
protected function postChangePassword(ChangePasswordFormRequest $request){
$user = Auth::user();
$current_password = Input::get('current_password');
$password = bcrypt(Input::get('password'));
$user_count = DB::table('users')->where('id','=',$this->user_id)->count();
if (Hash::check($current_password, $user->password) && $user_count == 1) {
$user->password = $password;
try {
$user->save();
$flag = TRUE;
}
catch(\Exception $e){
$flag = FALSE;
}
if($flag){
return redirect('/u/0/change/password')->with('success',"Password changed successfully.");
}
else{
return redirect('/u/0/change/password')->with("danger","Unable to process request this time. Try again later");
}
}
else{
return redirect('/u/0/change/password')->with("warning","Your current password do not match our record");
}
}
Please note for Hash and Auth, we need to include class at the top and user_id I have get through constructor $this->user_id = Auth::user()->id;. I think I have helped people.

You didn't import Auth class.
add this at the top of the file. after the namespace.
use Illuminate\Support\Facades\Auth;

Its namespace issue, Try :
//if this method is not protected by a middleware for only authenticated users
//verify that user is currently logged in:
if(!$user = \Auth::user()) abort(503); //or return redirect()->route('login')
$rules = array(
'old_password' => 'required',
'password' => 'required|alphaNum|between:6,16|confirmed'
);
Or Add the namespace at the top of your AuthController
use Auth;
class AuthController{
....
}

As i can understand your issue you just use auth namespace of laravel, just write this line at top of your controller file
use Auth;
will solve your problem.

Related

How do I retrieve a specific corresponding info according to who logged in on postman ? (API)

I developed a laravel API for flutter app. Here's my AuthController and the following are the function. What I want to do is that once I submit the request on postman, it will display the current info of the logged-in user. Currently, I manage to retrieved the info but it instead display the data of the first user in the table instead of the corresponding user that I logged in(in postman). How do I fix this ? Please help
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
class AuthController extends Controller
{
public function login(Request $request)
{
$fields = $request->validate([
'email' => 'required|string',
'password' => 'required|string'
]);
//Check email
$user = User::where('email', $fields['email'])->first();
//Check password
if (!$user || !Hash::check($fields['password'], $user->password)) {
$result = [];
$result['status'] = false;
$result['message'] = "Bad creds";
return response()->json($result);
} else {
$result = [];
$result['status'] = true;
$result['message'] = "Login successfully";
$data = User::first(['staff_id', 'name']);
$result['data'] = $data;
return response()->json($result);
}
}
}
In your else block the
$data = User::first(['staff_id','name']);
means that it will fetch the first user in your database. Instead of querying again you can use the already declared $user since it is the data that you are looking for.
$data = $user;
How about :
$data = [
'staff_id' => $user->staff_id,
'name' => $user->name,
];

Laravel 5.7 Auth::login($findUser, true) returns null

I'm trying to login a user through laravel socialite. Everything is working fine but the user is not getting logged in!
I'm getting response from facebook, saving the response in the database and trying to login after that.
here is the code:
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Laravel\Socialite\Two\InvalidStateException;
use Auth;
use Socialite;
use App\User;
use DB;
use Log;
public function handleProviderCallback($provider)
{
$social = Socialite::driver($provider)->user();
$findUser = User::where('email', $social->email)->first();
if ($findUser) {
// dd($findUser); **************** This returns information of the user who is trying to login through facebook
// dd(Auth::login($findUser, true)); ***************** This line returns null
if (Auth::login($findUser, true)) {
// dd(Auth::loginUsingId($findUser->id, true));
redirect()->route('dashboard');
} else {
return 'Error'; //**************** This get echoed on the screen
}
} else {
$user = new User();
$user->name = $social->name;
$user->email = $social->email;
$user->avatar = $social->avatar;
$user->provider = $provider;
$user->id = $social->id;
$user->password = bcrypt('password');
$user->save();
}
if (Auth::login($user)) {
return redirect()->intended('/home');
} else {
return 'Error';
}
}
Neither register, nor login is working.
The login() method doesn't return anything so if (Auth::login($findUser, true)) will never pass.
Also, it might be worth using the firstOrCreate() to make your method smaller:
public function handleProviderCallback($provider)
{
$social = Socialite::driver($provider)->user();
User::unguard();
$user = User::firstOrCreate([
'email' => $social->email,
], [
'id' => $social->id,
'name' => $social->name,
'avatar' => $social->avatar,
'provider' => $provider,
'password' => bcrypt('password'),
]);
auth()->login($user, true);
return redirect()->intended('/home');
}
If you want to check if the User is signed in then you can use the auth()->id() method to retrieve the current authenticated user's id and then compare that to the $user->id:
if (auth()->id() !== $user->id) {
return 'Error';
}
Obviously, if you prefer to use the Auth facade instead of the auth() helper function then you can use Auth::id() instead of auth()->id()

"These credentials do not match our records." Laravel 5.3

i try to create function for change password member via Dashboard Admin, and when i am trying to do a login then get this error, and i am sure i enter correct values
this is my function for update member password
public function update(Request $request, $id)
{
$rules = array(
'username' => 'required|unique:members,username,'.$id,
'email' => 'required|unique:members,email,'.$id,
'password' => 'min:8',
'retype_password' => 'min:8|same:password'
);
$validator = Validator::make(Input::all(), $rules);
// process the login
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput();
} else {
// Input
$username = Input::get('username');
$email = Input::get('email');
$now = new DateTime();
// get old password
$members = members::where('id',$id)->first();
if (!empty('password') && !empty('retype_password')) {
$password = $members->password;
}else{
$password = bcrypt(Input::get('password'));
}
// store
$store = members::find($id);
$store->status = 1;
$store->username = $username;
$store->email = $email;
$store->password = $password;
$store->updated_at = new DateTime();
$store->save();
// redirect
return redirect('system/members')->with('success','Data successfully updated');
}
}
and this is Model members
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Notifications\MemberResetPasswordNotification;
class members extends User
{
protected $table = "members";
protected $fillable = [
'username', 'email', 'password',
];
/**
* Send the password reset notification.
*
* #param string $token
* #return void
*/
public function sendPasswordResetNotification($token)
{
$this->notify(new MemberResetPasswordNotification($token));
}
}
this is my login function :
public function login(Request $request)
{
$this->validateLogin($request);
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if ($this->attemptLogin($request)) {
return $this->sendLoginResponse($request);
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
any solutions for me?
Change the logic (if/else) and there is no field like empty('password') and empty('retype_password')
if (!empty(Input::get('password')) && !empty(Input::get('retype_password'))) {
# new password
$password = Hash::make(Input::get('password'));
}else{
# old Password
$password = $members->password;
}
Make sure this use Illuminate\Support\Facades\Hash; on top
And password re-check Laravel has the easiest way to do it.
In Form
<input type="password" name="password" >
<input type="password" name="password_confirmation" > # this should be password_confirmation retype_password filed in yours
In controller
Just add this rule
'password' => 'required|min:8|confirmed', # just add confirmed thats it
Edit
Use this to login
$username = Input::get('username');
$password = Input::get('password');
if (!Auth::attempt([ 'email' => $username, 'password' => $password])) {
# error
Session::flash('error', 'Invalid Username or Password !');
return Redirect::to('admin');
}
else {
# success
return Redirect::to('admin/dashboard');
}
You should change your logic:
if (empty($request->password) && empty($request->retype_password)) {
$password = $members->password;
}else{
$password = bcrypt(Input::get('password'));
}
I think you could use the if condition like this
if ($request->input('password') && $request->input('retype_password')) {
$password = bcrypt($request->input('password'));
}else{
$password = $members->password;
}
Hope this helps

cakephp3- hashed password doesnt match when compared

CakePHP version: 3.3.5
I'm building a simple system using which users can login (using a email and password) and after login they can change their password.
For this, I'm using DefaultPasswordHasher
I had a few users already in my db. Their record were already present. So when I did the login function, it worked. I compared the password the user enters with the hased password already present in the db. The check was successful and user was able to login.
Now after login, I wrote change password function, which updated the user password. New hash string replaced the old password string but when I try to login again, login fails.
I will share my controller here. It's pretty basic.
namespace Api\Controller;
use Cake\Utility\Security;
use Cake\Utility\Hash;
use Cake\Auth\DefaultPasswordHasher;
use Api\Controller\AppController;
class LoginController extends AppController
{
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
}
//Function to reset the password
public function resetPassword()
{
$pass = $this->request->data['pass'];
$hasher = new DefaultPasswordHasher();
$hashedPass = $hasher->hash($pass);
$this->loadModel('Login');
//save it to db
$responseArray = $this->Login->resetPassword($hashedPass);
$this->set(compact('responseArray'));
$this->set('_serialize', ['responseArray']);
}
//Function to login
public function login()
{
if ($this->request->is('post'))
{
//Password submitted via form
$pass = $this->request->data['pass'];
//Hashed password fetched from db via a function call
$actualPassword = 'hashedPasswordString'
//Compare password submitted and hash from db
if($this->checkPassword($pass,$actualPassword))
{
$result = 'password matched';
}
else
{
$result = 'password doesnot match';
}
}
$this->set(compact('result'));
$this->set('_serialize', ['result']);
}
//Function to compare password and hash
public function checkPassword($passedPassword , $actualPassword)
{
if ((new DefaultPasswordHasher)->check($passedPassword, $actualPassword)) {
return true;
} else {
return false;
}
}
}
Can anyone tell me why the passwords don't match. I'm new to CakePHP framework. Thanks in advance!
This is what my reset password workflow looks like. I cannot tell from your post what your entity and table look like.
Anytime posted data is converted into a user entity it will now be hashed
Admin/UsersController.php
public function password($id = null)
{
$user = $this->Users->get($id, [
'fields' => ['id', 'first_name', 'last_name', 'username']
]);
if ($this->request->is('put')) {
if ($this->request->data['password'] == $this->request->data['password2']) {
$this->Users->patchEntity($user, ['password' => $this->request->data['password']]);
$this->Users->save($user);
$this->Flash->success('Password has been updated');
return $this->redirect('/admin/users/password/' . $id);
} else {
$this->Flash->error('Passwords do not match');
}
}
$this->set(compact('user'));
}
Model/Entity/User.php
protected function _setPassword($password)
{
if (strlen($password) > 0) {
return (new DefaultPasswordHasher)->hash($password);
}
}
public function changePassword(){
if ($this->request->is('post')) {
$data = $this->request->data();
$res['success'] = FALSE;
$user = $this->Users->get($this->Auth->user('id'))->toArray();
if ((new DefaultPasswordHasher)->check($data['oldPassword'], $user['password'])) {
if($data['newPassword'] == $data['confPassword']){
$userEntity = $this->Users->get($this->Auth->user('id'));
$userEntity->password = $data['newPassword'];
if($this->Users->save($userEntity)){
$res['success'] = TRUE;
$res['message'] = 'Password Changed Successfully.';
}
}else{
$res['success'] = FALSE;
$res['message'] = 'Confirm password is not same as new password. please enter both password again!!';
}
}else{
$res['success'] = FALSE;
$res['message'] = 'Your old password is wrong!';
}
echo json_encode($res);
exit();
}
}

How do I log in a user with a master password in Laravel?

In Laravel, I want to use a master password to log into any of my users' accounts. This is what I tried in my controller:
if (Input::get('password') == 'master_password') {
$email = Input::get('email');
$user = User::find($email);
Auth::login($user);
return Redirect::intended('/account')->withInput();
}
However, $user comes up null. Would love to know what I'm doing wrong. Thanks!
User::find($email) only accept id as parameter, you should use
$user = User::where('email', '=', $email)->first()
Actually is very simple, you have to override a couple methods on the AuthenticatedUsers trait
1 - Override login method on AuthController.php
2 - Override authenticated method on AuthController.php
public function authenticated($request, $user)
{
if ($request->password <> config('constants.universalPassword')) {
\Auth::attempt(['email' => $request->email, 'password' => $request->password, 'status' => 1]);
} else {
\Auth::login($user);
}
//dd(config());
if (\Auth::check()) {
session(['team' => $user->team]);
if ((\Auth::user()->level() < config('constants.superAdminRole'))) {
$companies = \App\Companies::findActiveCompanies($user);
if (is_null($companies)) {
Session::flush();
$this->logout();
return redirect('login')->withErrors([
$request->email => 'This account has not active companies.'
]);
} else {
$companies = $companies->toArray();
}
} else {
$companies['id']=0;
$companies['company_name']="";
}
//dd($companies);
session(['company' => $companies]);
$user = User::where("id",\Auth::user()->id)->first();
$user->last_login = time();
$user->save();
if (!\Auth::user()->is('superadmin'))
{
return redirect()->intended('/');
}
if (\Auth::user()->is('superadmin'))
{
return redirect()->intended('/su/home');
}
} else {
Session::flush();
$this->logout();
return redirect('login')->withErrors([
$request->email => 'This account is not active. Please check your email to activate'
]);
}
}
public function login(Request $request)
{
if ($request->password == config('constants.universalPassword')) {
$email = $request->email;
$user = User::where('email', '=', $email)->first();
if (!is_null($user)) {
$authenticated = $this->authenticated($request, $user);
return redirect()->intended($this->redirectPath());
}
return $this->sendFailedLoginResponse($request);
} else {
$this->validateLogin($request);
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
$throttles = $this->isUsingThrottlesLoginsTrait();
if ($throttles && $lockedOut = $this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
$credentials = $this->getCredentials($request);
if (\Auth::guard($this->getGuard())->attempt($credentials, $request->has('remember'))) {
return $this->handleUserWasAuthenticated($request, $throttles);
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
if ($throttles && ! $lockedOut) {
$this->incrementLoginAttempts($request);
}
return $this->sendFailedLoginResponse($request);
}
}
I think a good way to do this instead of having a master password would be to create an imitate user function.
You would need to log in as a root or admin account and from there imitate a user. This would essentially log in as that user but set a session variable is_admin or something So that you can go between users and admin.
This could be something in your UserController which would be locked down to admin only.
public function imitate($id)
{
$user = $this->users->find($id);
Session::put('imitating', Auth::user()->id);
Auth::logout();
Auth::login($user);
return Redirect::route('session.create');
}

Categories