New to JWT and i want to simply change my password after that i try to log in it is not working.
My update password function code :
public function resetPassword(ResetPasswordRequest $request, JWTAuth $JWTAuth)
{
$password = Hash::make($request->password);
$user = User::where('email', '=', $request->email)->first();
if(!$user) {
return response()->json([
'message' => "Credential do not match",
'status_code' => 403,
]);
}
if($user) {
$user->password = $password;
$user->save();
}
return response()->json(['message' => 'Your password has been changed successfully','status_code' => 204]);
}
This function working fine after i try to log in it is return $token null.
My login controller code :
public function login(LoginRequest $request, JWTAuth $JWTAuth)
{
$credentials = $request->only(['email', 'password']);
try {
$token = Auth::guard()->attempt($credentials);
if(!$token) {
return response()->json([
'message' => "Email and password do not match",
'status_code' => 403,
]);
}
$user = Auth::user();
$user->last_login = Carbon::now();
$user->save();
$user = Auth::user();
$user->UserDeviceData()->firstOrCreate([
'device_id' => $request->device_id
]);
} catch (JWTException $e) {
return response()->json([
'message' => "Internal server error",
'status_code' => 500,
]);
}
return (new UserTransformer)->transform($user);
}
On user model :
public function setPasswordAttribute($value)
{
$this->attributes['password'] = Hash::make($value);
}
What is the problem ? It is a right way to do a change password ?
While resetting your password, you are hashing your password two times one in resetPassword function and second in setPasswordAttributeso you need to replace
this
$password = Hash::make($request->password);
with this
$password = $request->password;
in your resetPassword function
Related
I'm using laravel 9 auth to authenticate the user
my Controller code
login function
public function authLogin(Request $request)
{
$request->validate([
'email' => 'required|email',
'password' => 'required|min:5|max:12',
]);
$fnf = User::where('email','=',$request->email)->first();
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
$request->session()->put('LoggedUser', $fnf->uniqueId);
return redirect('dashboard');
}else{
return redirect("/")->with('fail','Please check mail id & password !');
}
}
registration function
public function customRegistration(Request $request)
{
$request->validate([
'firstName' => 'required',
'email' => 'required|email|unique:mania_adminauth',
'number' => 'required|min:10|max:10',
'password' => 'required|min:6',
]);
$data = $request->all();
$arrData['firstName'] = $data['firstName'];
$arrData['lastName'] = $data['lastName'];
$arrData['email'] = $data['email'];
$arrData['number'] = $data['number'];
$arrData['password'] = Hash::make($data['password']);
$arrData['createdOn'] = Carbon::now()->timestamp;
$table = 'mania_adminauth';
$user = new commonModal();
$Response = $user->insertData($table, $arrData);
if ($Response != 0) {
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
return redirect("dashboard");
} else {
return view('admin.common.registration')->with('fail','Something Went Wrong !!');
}
}
}
i'm trying to check user is login or not
#if (auth()->check())
<p>User is login.</p>
#else
<p>User is not login.</p>
#endif
but it is showing: "User is not login"
even if i´m logged in
insertData method
public function insertData($table_name, $data)
{
$resp = DB::table($table_name)->insert($data);
return $resp;
}
Please add this line after Auth::attempt(). I think it's the missing points.
$request->session()->regenerate();
It looks like this
if (Auth::attempt($credentials)) {
$request->session()->regenerate();
return redirect("dashboard");
}
And it will be run correctly like this
please am trying to create a forgot password and reset password API in Laravel using JWT but it gave me this error ' "email": "passwords.throttled"',
I want it to send a password reset link to the email provided but it gives me that error.
or if anyone has any idea of how I will go about it
please can anyone help
this is my code
public function forgotPassword(Request $request){
// $request->validate(['email' => 'required|email']);
$email = $request->only('email');
$rules = ['email'=>'required:users,email'];
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
// handler errors
$erros = $validator->errors();
// echo $erros;
return $erros;
}else{
$user = User::where('email', '=', $email)->first();
try {
// verify the credentials and create a token for the user
if (! $token = JWTAuth::fromUser($user)) {
return response()->json(['error' => 'invalid_credentials'], 401);
}
} catch (JWTException $e) {
// something went wrong
return response()->json(['error' => 'could_not_create_token'], 500);
}
// if no errors are encountered we can return a JWT
// return response()->json(compact('token'));
$status = Password::sendResetLink($email);
return $status === Password::RESET_LINK_SENT
? response()->json(['status' => $status])
: response()->json(['email' => $status]);
}
}
public function resetPassword(Request $request)
{
// $this->validate($request, [
// 'token' => 'required',
// 'email' => 'required|email',
// 'password' => 'required|confirmed',
// ]);
$rules = ['email'=>'required:users,email','password' => 'required|confirmed',
'token'=>'required '];
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
// handler errors
$erros = $validator->errors();
// echo $erros;
return $erros;
}else{
$credentials = $request->only(
'email', 'password', 'password_confirmation', 'token'
);
// $response = $request->password->reset($credentials, function($user, $password) {
// $user->password = bcrypt($password);
// $user->save();
// $this->auth->login($user);
// });
// return json_encode($response);
}
I use passport in my laravel project to authenticate users by api. API work correctly on my local host. But after i deploy it on Plesk server token doesnt create. Always show Server Error.
public function login(Request $request) {
$validator = Validator::make($request->all(),[
'email' => 'required',
'password' => 'required',
]);
if($validator->fails()) {
return response()->json(["validation errors" => $validator->errors()]);
}
$email = $request->email;
$password = $request->password;
error_log($password);
$user = DB::table("users")->where([["email", "=", $email]])->first();
if(is_null($user)) {
return response()->json(["success" => false, "message" => "User doesn't exist"]);
}
if(Auth::attempt(['email' => request('email'), 'password' => request('password')])) {
$user = Auth::user();
$token = $user->createToken('token')->accessToken;
$success['success'] = true;
$success['user'] = $user;
$success['message'] = "Success! you are logged in successfully";
$success['token'] = $token;
return response()->json(['success' => $success ], 200);
} else {
return response()->json(['error' => 'Unauthorised'], 401);
}
}
$token = $user->createToken('token')->accessToken;
This line throw error
Problem was in my AuthServiceProvider
class AuthServiceProvider extends ServiceProvider
{
protected $policies = [
'Medicare\Model' => 'Medicare\Policies\ModelPolicy',
];
public function boot()
{
$this->registerPolicies();
Passport::routes();
//
}
}
After i commented 'Medicare\Model' => 'Medicare\Policies\ModelPolicy' everything works fine.
My code is given below.
I am facing problem. When I want check by username and password.
password change every time. so I am unable to give result by email password.
public function login()
{
$data = Input::all();
print_r($data);
$email= $data['email'];
$password= bcrypt($data['password']);
echo $password;
$count = User::where('email', '=',$email);
$count->Where('password', '=', $password);
$count_row=$count->get()->count();
echo $count_row; die;
if($count_row==1)
{
$users = User::where('email', '=',$email);
$users->Where('password', '=', $password);
$users->select(
'id','name','email',
'username','address','zip',
'city','country','phone_number',
'domain','type') ;
$result=$users->get();
$response= response()->json(['success'=>true,'message'=>'success', 'data'=>$result]);
return $response;
}
else
{
$response= response()->json(['success'=>false,'message'=>'Not Login successfull']);
return $response;
}
}
According to the docs, the correct way to verify a password is
Hash::check('plain-text', $hashedPassword)
So you can rewrite your function as
public function login()
{
$email = Input::get('email');
$user = User::where('email', '=', $email)->first();
if (!$user) {
return response()->json(['success'=>false, 'message' => 'Not Login successfull']);
}
if (!Hash::check(Input::get('password'), $user->password)) {
return response()->json(['success'=>false, 'message' => 'Not Login successfull']);
}
return response()->json(['success'=>true,'message'=>'success', 'data' => $user]);
}
Or even simpler
public function authenticate(Request $request)
{
$credentials = $request->only('email', 'password');
if (!Auth::attempt($credentials)) {
return response()->json(['success'=>false, 'message' => 'Not Login successfull']);
}
$user = User::where('email', '=', $request->get('email'))->first()
return response()->json(['success'=>true,'message'=>'success', 'data' => $user]);
}
I have simple function to reset my password. In my function there is minimum requirement for password value is 1 digit but when i try to update the password it is not updated, when i put 6 digits in password it is working fine.
I found that in vendor\laravel\framework\src\Illuminate\Auth\Passwords a passwordBroker.phpfile has one function
protected function validatePasswordWithDefaults(array $credentials)
{
list($password, $confirm) = [
$credentials['password'],
$credentials['password_confirmation'],
];
return $password === $confirm && mb_strlen($password) >= 6; // here it is
}
and it contains validation that ($password) >= 6 how can i remove it, when i changes in this file it is working. on my .gitignore vendor folder not updated in live. what is the solution ? how can override this validation ?
for reference here is my resetpassword function
public function resetPassword(ResetPasswordRequest $request, JWTAuth $JWTAuth)
{
$validator = Validator::make($request->all(), User::resetPasswordRules());
if ($validator->fails()) {
return response()->json([
'message' => "422 Unprocessable Entity",
'errors' => $validator->messages(),
'status_code' => 422,
]);
}
$response = $this->broker()->reset(
$this->credentials($request), function ($user, $password) {
$this->reset($user, $password);
}
);
if($response !== Password::PASSWORD_RESET) {
return response()->json([
'message' => "Internal Server Error",
'status_code' => 500,
]);
}
$user = User::where('email', '=', $request->get('email'))->first();
$user->UserDeviceData()->firstOrCreate([
'device_id' => $request->device_id
]);
return (new UserTransformer)->transform($user,[
'request_type' => 'reset_password',
'token' => $JWTAuth->fromUser($user)
]);
}
This is how you can fix this:
public function resetPassword(ResetPasswordRequest $request, JWTAuth $JWTAuth)
{
... // Validator check and json response
$broker = $this->broker();
// Replace default validation of the PasswordBroker
$broker->validator(function (array $credentials) {
return true; // Password match is already validated in PasswordBroker so just return true here
});
$response = $broker->reset(
$this->credentials($request), function ($user, $password) {
$this->reset($user, $password);
});
...
}
First you gen an instance of the broker and then you add a callable function which it will use for the validation instead of validatePasswordWithDefaults. In there you just need to return true because the PasswordBroker already has a check $password === $confirm.