Laravel5.2 default auth check if user is verified in database before login and display custom message - laravel

I am using laravel5.2 auth and I have added an additional field : verified(y/n) in users table. Now before login I want to check if user is verified(Y) in database and if not verified display a message that your account is not yet verified.

If method authenticated exists in the AuthController it will be called from Laravel trait AuthenticatesUser. Use this method to block the user if it is not verified yet and, if required, resend the email.
public function authenticated(Request $request, $user)
{
if (!$user->activated) {
$this->activationService->sendActivationMail($user);
auth()->logout();
return back()->with('warning', 'You need to verify your account. We have sent you an activation code, please check your email.');
}
return redirect()->intended($this->redirectPath());
}

In /vendor/laravel/framework/src/Illuminate/Foundation/Auth you will find AuthenticatesAndRegistersUsers.php there you define what you want to do with your login.

Related

How to restrict users to use application

I am using laravel framework to develop api’s ,it’s an existing application .there is a requirement if more than 5users registered from 6th user onwards i have to restrict them to use application until they approved by manager or they paid for registration fee then only the user will allow to use the application.
Can anyone give me the idea how to acheive this scenario or suggest me any package in laravel
Solution:
You can add 'status' field in your table. Now when your api is registering a user, you can check the No. of users in the database. If more than or equals to 5, you can set the status to 0. Now show the manager list of user with status 0 and when the status changes you can use the application.
Make sure to add condition where status = 1 when user is getting logged in.
I hope it helps!
Well, you can just put a isApproved column to indicate if the user is already approved or just like the email_verified_at that accepts timestamp as a value then create a middleware where you can check if the user is approved or not. then add a method to the user model to check if the user is approve :
User model
class User extends Authenticatable
{
public function isApproved()
{
// check if the account_approved_at column is not null.
return ! is_null($this->account_approved_at);
}
}
Middleware
class EnsureUserIsApproved
{
public function handle(Request $request, Closure $next)
{
if(! $request->user()->isApproved()) {
// can also use abort(403) instead of redirect
return redirect('route-where-you-want-the-user-to-redirect')
}
return $next($request);
}
}
You can check this for more information about middleware

Get Auth User ID Laravel

I Made Laravel Project And install the Breeze package for multi authentication And the Create a guard call admin in order to control user assess to dashboard It works fine Here is the route
Route::get('/dashbord',[AdminController::class, 'Dashbord'])
->name('admin.dashbord')
->middleware('Admin');
Route::get('/profile/edit',[AdminProfileSettings::class, 'index'])
->name('admin.profile.settings')
->middleware('Admin');
Here Is the middleware
public function handle(Request $request, Closure $next)
{
if(!Auth::guard('admin')->check()) {
return redirect()->route('login_form')->with('error','please Login First');
}
return $next($request);
}
This code works fine but the problem is when I log in to the dashboard and try to get admin ID to admin.profile.settings route it wont get the Id, I Passed the logged admin id by using AdminProfileSettings controller like this
public function index()
{
$id=Auth::user()->id;
$adminData = Admin::find($id);
return view('admin.admin_profile_settings',compact('adminData'));
}
But, when I try to access it in the admin.admin_profile_settings view it show me this error:
Trying to get property 'id' of non-object
But, if I use $adminData = Admin::find(1); it get the Id without any problem but when I try to get auth user id it show me the error and if I have logged in using default guard this error wont show but it get the id from users table
You're not using the auth:admin middleware, so the Auth facade is going to pull the user from the default guard defined in the config (which is web, unless you've changed it).
Without using the auth:admin middleware, you'll need to specify the guard for which to get the user.
$adminUser = Auth::guard('admin')->user();
Note 1: if you have the $request variable, you can also pull the user off of the $request with $request->user(), instead of reaching out to the Auth facade. It's just a matter of preference. The user() method also takes a guard as a parameter, if needed.
$adminUser = $request->user('admin');
Note 2: the user() method (Auth and request) returns the fully hydrated model. There is no need to get the id and re-retrieve the model.

How to hide login form after reaching the total of failed login attempts?

I want to hide the login form and display an error message instead, but I can't.
I tried to put the code below that rewrites the action on the controller that shows the form, but the method that checks for too many login attempts doesn't seem to work and never returns true.
public function showLoginForm(Request $request)
{
if (method_exists($this, 'hasTooManyLoginAttempts') &&
$this->hasTooManyLoginAttempts($request) ) {
$seconds = $this->limiter()->availableIn($this->throttleKey($request));
return view('auth.block', array(
'seconds' => $seconds
));
}
return view('auth.login');
}
I managed the authentication process with php artisan make: auth login controller is the default generated by Laravel, the only change is in the action that displays the form.
The function hasTooManyLoginAttempts() needs, in the $request, the username (usually the email) as a key to know if the user has reached his max login attempts.
If, in the $request, there is not the username with a value the function is unable to verify the user login attempts.
So you cannot really know who is the user that wants to get your login form, you know who is only after he submitted the form.
IMHO the only way could be to add a username parameter to the GET request but you shoud provide it with some workarounds: cookies, session etc.
Looking at Laravel's code, it checks for hasTooManyLoginAttempts based on throttleKey and maxAttempts.
The throttleKey is dependent on the user's email and IP address. So the output of the following code is something like: info#example.com|127.0.0.1 and that is your throttleKey.
protected function throttleKey(Request $request)
{
return Str::lower($request->input($this->username())).'|'.$request->ip();
}
Now Laravel gets the user's email (username) from $request->input($this->username()) when you send a POST request, which you don't have access to in the showLoginForm method because it's called on the GET request.
Anyway, if you want to block the login form you'll need to come up with your own unique throttleKey and then override the method. Say you want your throttleKey to be based only on the IP address - which is not recommended. Here's how you do it:
// In LoginController.php
protected function throttleKey(Request $request)
{
return $request->ip();
}

New hashing of password - redirect users to password reset on login attempt

Here is an "update" In the previous version of my project we didn't have any proper hashing on password. So I want to use Laravel's hashing, and invite the users to make a new password.
What I have is a new password column in my User table. If when the user tries to log in, the new password doesn't exist (empty column), we automatically do a "reset password." I would like to know where to do this verification:
class LoginController extends Controller
{
public function login(Request $request)
{
//check if the user has an empty password
//if yes
redirect('/password/reset');
//else
//use normal login function
}
}
Is that the correct place? And do I need to rewrite all login content in the "else" ? (sorry this is a basic question)
I suggest that you create a middleware ( EnsurePasswordIsAdded as an example ) for your case and not include the verification process in a controller, because a controller usually contains functions that interact either a database or an external API to provide a response to the user which is not the case for you, you're just filtering/verifying the request.
here's the documentation link about middlewares in Laravel:
https://laravel.com/docs/5.8/middleware
here's a code suggestion:
public function handle($request, Closure $next)
{
if ( !User::find($request->email)->hasPassword() ) {
return redirect('password-reset')->with('email',$request->email);
}
return $next($request);
}

Laravel 5.4 Authentication password reset redirect based on email address

I am involved in a web site using Laravel 5.4 and using the built-in authentication.
I have added a "Forgot Password" link that shows the ResetPasswordController#showLinkRequestForm which emails a password
reset link when submitted and then the ResetPasswordController#showResetForm redirects to the login page when submitted.
The problem I have is that we have two different Users - clients and admins. I have the ability to determine which is
which through the registered email address but I want the redirect following password reset be different for each type
(client = '/' and admin = '/admin').
How is this be done?
If you are using the ResetsPasswords trait in your controller, you can create your own redirectTo() method which will be called to redirect the user :
// import the needed trait
use Illuminate\Foundation\Auth\ResetsPasswords;
class YourResetPasswordController {
// use the needed trait
use ResetsPasswords;
// override the method that redirects the user
public function redirectTo()
{
if (auth()->user()->isAdmin()) {
return redirect('/admin');
} else {
return redirect('/');
}
}
}
Let me know if it helped you :)

Resources