not able to authenticate login user in laravel 9 - laravel

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

Related

FatalThrowableError in Call to a member function get_one() on null

i have some laravel code like this
public function update_password(Request $request)
{
$data = array(
'password_current' => $request->input('password_current'),
'password_new' => $request->input('password_new'),
'password_new_confirmation' => $request->input('password_new_confirmation'),
);
$rules = [
'password_current' => 'required',
'password_new' => 'required|confirmed',
'password_new_confirmation' => 'required',
];
$validator = Validator::make($data, $rules);
if ($validator->fails()) {
return redirect()->action('Editor\ProfileController#edit_password')->withInput()->withErrors(['New password confirmation failed!']);
} else {
$user = $this->UserRepository->get_one(Auth::user()->id);
if(Hash::check($request->input('password_current'), $user->password))
{
$this->UserRepository->change_password(Auth::user()->id, $request->input('password_new'));
return redirect()->action('Editor\ProfileController#show');
} else {
return redirect()->action('Editor\ProfileController#edit_password')->withInput()->withErrors(['Current password mismatch!']);
}
}
}
but when i run the program, the program notification is FatalThrowableError, Call to a member function get_one() on null. i change with other script in google but no one is work.
$user = $this->UserRepository->get_one(Auth::user()->id);
anyone ever had this problem?
I try to change script like
use Auth;
$user_id = Auth::user()->id;
and still not work.

How to Reset Password without entering email field

I'm creating a reset password with the help of the internet I'm able to make it function, but it needs to input an email address in the email field. I want to hide the email field and only the password field need to input. How can i do that?
My ForgotPasswordController
class ForgotPasswordController extends Controller
{
public function getEmail()
{
return view('auth.passwords.email');
}
public function postEmail(Request $request)
{
$request->validate([
'email' => 'required|email|exists:users',
]);
$token = Str::random(60);
DB::table('password_resets')->insert(
['email' => $request->email, 'token' => $token, 'created_at' => Carbon::now()]
);
Mail::send('auth.verify',['token' => $token], function($message) use ($request) {
$message->from('noreply#taskproph.com');
$message->to($request->email);
$message->subject('Reset Password Notification');
});
Toastr::success('We have e-mailed your password reset link! :)','Success');
return back();
}
}
My ResetPasswordController
class ResetPasswordController extends Controller
{
public function getPassword($token)
{
return view('auth.passwords.reset', ['token' => $token]);
}
public function updatePassword(Request $request)
{
$request->validate([
'email' => 'required|email|exists:users',
'password' => 'required|string|min:6|confirmed',
'password_confirmation' => 'required',
]);
$updatePassword = DB::table('password_resets')->where(['email' => $request->email, 'token' => $request->token])->first();
if(!$updatePassword)
{
Toastr::error('Invalid token! :)','Error');
return back();
}else{
$user = User::where('email', $request->email)->update(['password' => Hash::make($request->password)]);
DB::table('password_resets')->where(['email' => $request->email ])-> delete();
Toastr::success('Your Password has been changed! :)','Success');
return redirect('/login');
}
}
}
In your getPassword method you may get email. Then you can use it email to updatePassword method by passing on it hiddenly.
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Support\Facades\Password;
public function getPassword(Request $request, $token)
{
$email = $request->input('email');
$user = User::where('email', $email)->firstOrFail();
if(!Password::tokenExists($user, $token)) {
Toastr::error('Invalid token!','Error');
return redirect()->route('password.request');
}
return view('auth.passwords.reset', ['token' => $token, 'email' => $email ]);
}
public function updatePassword(ResetPasswordRequest $request)
{
$credentials = $request->validated(); // email, token, password, password_confirmation
$status = Password::reset($credentials, function($user) use($request) {
$user->forceFill([
'password' => bcrypt($request->password)
])->save();
event(new PasswordReset($user));
});
if ($status != Password::PASSWORD_RESET) {
Toastr::error(__($status), 'Error');
return back();
}
$request->session()->flash('statusForgotPassword', __($status));
Toastr::success('Your Password has been changed!','Success');
return redirect('/login');
}
auth.passwords.reset
<input type="hidden" name="email" value="{{ $email }}">

Laravel forgot and reset password API with jwt authentication

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

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.

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