Login only if user is active using Laravel

前端 未结 19 1578
孤城傲影
孤城傲影 2020-11-30 23:26

I\'m currently working on my Laravel app and to prevent spam I decided that only active users are able to login. I\'m currently using Laravel\'s login system just like in La

相关标签:
19条回答
  • 2020-11-30 23:30

    Works on Laravel 7

    I know this has already been answered many times but here was my approach and it isn't much different from some of the others but I wanted to provide a little more detailed explanation for some of the choices I made.

    I decided for my app that it was ok to simply abort 403 if the user is not active, returning validation exceptions has already been fairly covered here.

    My suggestion here is to override the login method from vendor/laravel/ui/auth-backend/AuthenticatesUsers.php by copying it into app/Http/Controllers/Auth/LoginController.php. I would also suggest adding this check after the throttle check as that should take precedent imo.

    Here's what my LoginController looks like. Just pulling in the login method and added about 3-4 lines of code.

    use AuthenticatesUsers;
    
    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;
    
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }
    
    /**
     * Handle a login request to the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Http\JsonResponse
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function login(Request $request)
    {
        $this->validateLogin($request);
    
        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        if (method_exists($this, 'hasTooManyLoginAttempts') &&
            $this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);
    
            return $this->sendLockoutResponse($request);
        }
    
        // Check if user is active
        $user = User::where('email', $request->email)->first();
        if ($user && !$user->active) {
            abort(403, 'Your account has been disabled by an administrator.');
        }
    
        if ($this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        }
    
        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);
    
        return $this->sendFailedLoginResponse($request);
    }
    
    0 讨论(0)
  • 2020-11-30 23:33

    in AuthController override method getCredentials like this:

    protected function getCredentials(Request $request) {
    
            $request['active'] = TRUE;
            return $request->only($this->loginUsername(), 'password', 'active');
    }
    

    make sure you have the column active on user table...

    0 讨论(0)
  • 2020-11-30 23:33

    Most logical, and clean, is to handle this within the validateLogin method.

    LoginController.php (Laravel 6.x)

    /**
     * Validate the user login request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return void
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    protected function validateLogin(Request $request)
    {
        // Get the user details from database and check if email is verified.
        $user = User::where('username', '=', $request->input($this->username()))->first();
        if ($user->email_verified_at == NULL) {
            throw ValidationException::withMessages([$this->username() => __('auth.failed_login_missing_email_verification')]);
        }
    
        // Email is verified, validate input.
        return $request->validate([
            $this->username() => 'required|string',
            'password' => 'required|string',
        ]);
    }
    
    0 讨论(0)
  • 2020-11-30 23:34

    On laravel 7, you only need to put this method on LoginController:

    /**
     * Custom credentials to validate the status of user.
     */
    public function credentials(Request $request)
    {
        return [
            'email'     => $request->email,
            'password'  => $request->password,
            'is_active' => '1'
        ];
    }
    

    In this way, you can validate any condition for login.

    0 讨论(0)
  • 2020-11-30 23:34

    Thanks @Can_Celik

    this was how I was able to solve my issue becos i was using json response with jquery.

    /**
         * Validate the user login request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @return void
         */
        protected function validateLogin(Request $request)
        {
            $this->validate($request, [
                'email' => 'required|email|exists:users_table,email,account_status_colunm,active_value',
                'password' => 'required',
            ]);
        }
    

    then in the validation.php file add this to your Custom Validation strings

    ...
    'email' => [
            'exists' => 'Account has been disabled. Contact our team.'
        ],
    

    that's about all...works fine ...

    0 讨论(0)
  • 2020-11-30 23:36

    In Laravel 5.4 open Auth/LoginController.php

    and add this function:

    /**
         * Get the needed authorization credentials from the request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @return array
         */
        protected function credentials(\Illuminate\Http\Request $request)
        {
            //return $request->only($this->username(), 'password');
            return ['email' => $request->{$this->username()}, 'password' => $request->password, 'status' => 1];
        }
    

    And you are done..!

    0 讨论(0)
提交回复
热议问题