Laravel forgot and reset password API with jwt authentication - laravel

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);
}

Related

not able to authenticate login user in laravel 9

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

Laravel passport create token doesnt work on plesk server

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.

Undefined Variable: token in Laravel Login Postman test

I wrote an API in Laravel 5.8 for User Login and Register.
I use JWTAuth in Laravel 5.8. When I tested the Login on Postman, it generated an error, undefined variable: token. I tried to write the API for register, when I tested it, it worked perfectly. Based on what I saw online, I tried adding \Illuminate\View\Middleware\ShareErrorsFromSession::class, to the kernel but still the same error.
LoginController
public function login(Request $request)
{
$credentials = $request->json()->all();
try
{
if(! $token == JWTAuth::attempt($credentials))
{
return response()->json(['error' => 'invalid_credentials'], 400);
}
}
catch(JWTException $e)
{
return response()->json(['error' => 'could_not_create_token'], 500);
}
return response()->json(compact('token'));
}
public function register(Request $request)
{
$validator = Validator::make($request->json()->all() , [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6',
'username' => 'required|string|max:255',
]);
if($validator->fails()){
return response()->json($validator->errors()->toJson(), 400);
}
$user = User::create([
'name' => $request->json()->get('name'),
'email' => $request->json()->get('email'),
'password' => Hash::make($request->json()->get('password')),
'username' => $request->json()->get('username'),
]);
$token = JWTAuth::fromUser($user);
return response()->json(compact('user', 'token'), 201);
}
api.php
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::post('register', 'UserController#register');
Route::post('login', 'UserController#login');
Route::get('profile', 'UserController#getAuthenticatedUser');
I expected success, but it gave error:
ErrorException: Undefined variable: token in file C:\xampp\htdocs\laravelapi\app\Http\Controllers\UserController.php on line 52
This is my line 52:
if(! $token == JWTAuth::attempt($credentials))
define $token before line 52
$token = null;
You should use assignment operator and not equal ==:
$token = JWTAuth::attempt($credentials))
Also in the login function you should generate a token from user to return
public function login(Request $request)
{
$credentials = $request->json()->all();
try
{
if(! $token = JWTAuth::attempt($credentials))
{
return response()->json(['error' => 'invalid_credentials'], 400);
} else {
// Generate token from user
$token = JWTAuth::attempt($credentials);
return response()->json(compact('token'));
}
}
catch(JWTException $e)
{
return response()->json(['error' => 'could_not_create_token'], 500);
}
}

Is There A Way To Include Data With Http/Guzzle Response In Laravel

So I am trying to return User data with login request. I am using guzzle and I do not know how to attach data to response.
Here is the login method
public function login(Request $request)
{
$http = new \GuzzleHttp\Client;
try {
$response = $http->post(config('services.passport.login_endpoint'), [
'form_params' => [
'grant_type' => 'password',
'client_id' => config('services.passport.client_id'),
'client_secret' => config('services.passport.client_secret'),
'username' => $request->username,
'password' => $request->password,
]
]);
return $response->getBody();
} catch (\GuzzleHttp\Exception\BadResponseException $e) {
if ($e->getCode() === 400) {
return response()->json('Invalid Request. Please enter a username or a password.', $e->getCode());
} else if ($e->getCode() === 401) {
return response()->json('Your credentials are incorrect. Please try again', $e->getCode());
}
return response()->json('Something went wrong on the server.', $e->getCode());
}
}
I would like to do something like this
$user = User::where('email', $request->username)->get();
$token = $response->getBody();
return response()->json($token, $user);
However when I try this I get error. Any help would be greatly appreciated. Currently I am having to make separate request after access token to return the user data thus I would like for it to happen at the same time....
The first argument of json method can be an array:
return response()->json(['token' => $token, 'user' => $user ]);
I was recommended the following discussion and it solved my issue. here is the final code
public function login(Request $request)
{
$http = new \GuzzleHttp\Client;
try {
$response = $http->post(config('services.passport.login_endpoint'), [
'form_params' => [
'grant_type' => 'password',
'client_id' => config('services.passport.client_id'),
'client_secret' => config('services.passport.client_secret'),
'username' => $request->username,
'password' => $request->password,
]
]);
$token = $response->getBody();
$data = json_decode($token, true);
$user = User::where('email', $request->username)->with('role.rules')->get();
$rules = $user->pluck('role')->collapse()->pluck('rules');
$rules->put('access_token', $data['access_token']);
return response()->json($rules);
} catch (\GuzzleHttp\Exception\BadResponseException $e) {
if ($e->getCode() === 400) {
return response()->json('Invalid Request. Please enter a username or a password.', $e->getCode());
} else if ($e->getCode() === 401) {
return response()->json('Your credentials are incorrect. Please try again', $e->getCode());
}
return response()->json('Something went wrong on the server.', $e->getCode());
}
}

Laravel : login failed after changing password on API

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

Resources