Throw not found error if user not exist in database Laravel - laravel

I'm using Auth::attempt($credentials) to authenticate login data from users.
$credentials = [
'user_name' => $request->user_name,
'password' => $request->password,
];
if (Auth::attempt($credentials)) {
return redirect()->route('admin.dashboard');
} else {
return redirect()->back()->with('status', 'Invalid credentials!');
}
If a user types the wrong password or wrong username, I throw an invalid credentials error. But I want if a user does not exist in the database, I can throw an error that the user does not exist.
My Auth::attempt($credentials) returns true or false, so I don't know how to do this. Can you help?

$user = User::where('user_name',$request->user_name)->first();
if($user) {
$credentials = [
'user_name' => $request->user_name,
'password' => $request->password,
];
if (Auth::attempt($credentials)) {
return redirect()->route('admin.dashboard');
} else {
return redirect()->back()->with('status', 'Invalid credentials!');
}
} else {
return redirect()->back()->with('status', 'Not found!');
}

It would be an security issue sir as #fubar said, but the simple logic is
Find at users table if email is exists.
if exists then go to auth attempt like the way you implement already.
if not exists throw 404.

Related

Why with additive checks on login fail user is entered into the system?

In laravel 9 with breeze 1.11 I need to add additive checks on field if user is admin.
In app/Http/Requests/Auth/LoginRequest.php I add lines :
public function authenticate()
{
$this->ensureIsNotRateLimited();
if (! Auth::attempt($this->only('email', 'password'), $this->boolean('remember'))) {
RateLimiter::hit($this->throttleKey());
throw ValidationException::withMessages([
'email' => trans('auth.failed'),
]);
}
\Log::info(varDump(Auth::user()->is_admin, ' -1 Auth::user()->is_admin::')); // I see data of logged user
if(!Auth::user()->is_admin) {
\Log::info(varDump(-13, 'RAISE ERROR')); // I see this log line
throw ValidationException::withMessages([
'email' => trans('You have no admin credentials'),
]);
}
RateLimiter::clear($this->throttleKey());
}
But anyway user is logged into dashboard.
Which method is correct for this task ?
Thanks!
I fixed this issue with manual logout method :
if(!Auth::user()->is_admin) {
Auth::guard('web')->logout();
throw ValidationException::withMessages([
'email' => 'You have no admin credentials',
]);
}

Two columns for password in Laravel for login

I have two password column one is password and other in temp_password, user can login with either password or temp_password for that i'm using following code:
if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){
echo "User Logged In";
} else if(Auth::attempt(['email' => request('email'), 'temp_password' => \Crypt::encrypt(request('password'))])) {
echo "User Logged in";
} else {
echo "Incorrect Credentials";
}
i'm getting this error :
Undefined index: password", exception: "ErrorException"
if i remove else if part it is working properly.
Any help is highly appreciated.
Auth::Attempt() method expects an array with email and password indexes.
#Documentation
If you dont provide them, it will fail. 'password' is not a dynamic field to it, it must be password. You need to do it manually for the temp_password field
if (Auth::attempt(['email' => request('email'), 'password' => request('password')])) {
echo "User Logged In";
} else {
$user = User::where('email', '=', request('email'))->first();
if (!$user || !Hash::check(request('password'), $user->temp_password);) {
echo "Incorrect Credentials";
return;
}
Auth::guard()->login($user);
echo "User Logged In";
}

Laravel auth attempt not working or returning false always?

I've been looking all over the place (I checked all the other duplicate questions and answers ), no luck. I don't understand what am I doing wrong, all the values are coming from post, but Auth:attempt keeps on failing/returning false, if I try to implement login manually it won't authenticate as I am expecting, Also do I have to make or use separate methods like for validation, credentials, username ..etc ?
Here is my login Controller > login method
public function login(Request $request)
{
$validator = Validator::make($request->all(), [
'usermail' => 'required|max:255',
'password' => 'required_with:usermail',
],[
'password.required_with' => "The password field is empty."
]);
if ($validator->fails()) {
return redirect()
->route('admin.login')
->withErrors($validator)
->withInput();
}
$usermail = $request->get('usermail');
$password = $request->get('password');
$remember = $request->get('rememberMe');
if(filter_var($usermail, FILTER_VALIDATE_EMAIL)) {
$isEmailExist = User::where('user_email',$usermail)->first();
if($isEmailExist != null){
if(Auth::attempt([
'user_email' => $usermail,
'user_pass' => $password
])){
return redirect()->intended('admin/dashboard');
}else{
return back()->with([
'message' => '<strong>ERROR</strong>: The password you entered for the email address <strong>'.$usermail.'</strong> is incorrect. Lost your password?'
]);
}
}else{
return back()->with([
'message' => '<strong>ERROR</strong>: Invalid email address.'
]);
}
}else{
$isUsernameExist = User::where('user_login',$usermail)->first();
if($isUsernameExist != null){
if(Auth::attempt([
'user_login' => $usermail,
'user_pass' => $password
],$remember)){
return redirect()->intended('admin/dashboard');
}else{
return back()->with([
'message' => '<strong>ERROR</strong>: The password you entered for the username <strong>'.$usermail.'</strong> is incorrect. Lost your password?'
]);
}
}else{
return back()->with([
'message' => '<strong>ERROR</strong>: Invalid username. Lost your password?'
]);
}
}
}
And this is my user migration schema,
Schema::create('vw_users', function (Blueprint $table) {
$table->bigIncrements('ID');
$table->string('user_login','60')->unique()->default('');
$table->string('user_pass');
$table->string('user_email','100')->unique()->default('');
$table->rememberToken();
});
Here is how i seed user,
User::create([
'user_login' => 'admin',
'user_pass' => Hash::make("123456"),
'user_email' => 'admin#gmail.com',
]);
OK OK OK,
I made it work, I think in laravel framework we can only create the column name for the password is "password" field in database authentication table.
I updated the following changes:-
I renamed the password field name from migration schema the "user_pass" to "password". (Also updated in login controller and user model).
Added following code into user model:-
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
...
}
I checked twice to confirm so I revert back it didn't work.
If i make any sense to anyone please let me know and help me understand.
I've looked into very similar posts like this Laravel: How can i change the default Auth Password field name
can I please have a reference book or blog for all the laravel predefined libraries and functions? I know the vendor folder is full of surprises but still, I need more references.
Thank you so much for your time.

Creating Password Reset Function without using Laravel make:auth

I'm dealing with Laravel 5.6. I am using JWT Authentication, and I create my own authentication controller.
This is my recover method at AuthController,
public function recover(Request $request)
{
$user = User::where('email', $request->email)->first();
if (!$user) {
$error_message = "Your email address was not found.";
return response()->json(['success' => false, 'error' => ['email'=> $error_message]], 401);
}
try {
Password::sendResetLink($request->only('email'), function (Message $message) {
$message->subject('Your Password Reset Link');
});
} catch (\Exception $e) {
$error_message = $e->getMessage();
return response()->json(['success' => false, 'error' => $error_message], 401);
}
return response()->json([
'success' => true, 'data'=> ['message'=> 'A reset email has been sent! Please check your email.']
]);
}
In postman, if I execute the recover method, I get this message
{
"success": false,
"error": "Route [password.reset] not defined."
}
How can I deal with this. thanks!
You need to give the route a name, in this case password.reset. In your routes.php (or wherever you've defined them) call the name method:
Route::post('/password/reset', 'AuthController#recover')->name('password.reset');
If you haven't run make:auth you don't have the route defined, as the error itself is saying.
Try to define the following route in routes/web.php
Route::post('/pwdreset', 'AuthController#recover')
->name('password.reset');

Check If user has a role In Laravel 5.5

I'm using entrust package to manage roles and I have used passport for authentication since it is API's.
Actually what I need is want to check user has a role,
I have tried with below code but it doesn't work
public function Adminlogin()
{
if(Auth::attempt(['email' => request('email'), 'password' => request('password')]))
{
$user = Auth::user();
if($user->hasRole('admin'));
{
$success['token'] = $user->createToken('MyApp')->accessToken;
return response()->json(['success' => $success], $this->successStatus);
}
return response()->json(['error'=>'Abort'], 403);
}
else
{
return response()->json(['error'=>'Unauthorised'], 401);
}
}
I want to generate access token only if user has admin role,If user has no role admin then show abort message.
if(Auth::user()->hasRole('admin'))
should work.
But you don't explain what is not working in your case so...

Resources