расширение laravel 5 встроенной аутентификации для входа в систему только "если пользователь == активен"

Я использую включенную аутентификацию laravel 5.1.6 и хочу знать, как я могу ее расширить, чтобы работать следующим образом:

if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) { // The user is active, not suspended, and exists. } 

Если пользователь не является «активным», вход в систему невозможен. У меня есть столбец «active» в таблице users, с 0 или 1 как значение. Как я могу это сделать, все еще используя встроенную аутентификацию с использованием дросселирования входа.

редактировать:

У меня нет функции postLogin в AuthController, только для use AuthenticatesAndRegistersUsers, ThrottlesLogins; , __construct() , validator() и функцию create() . Должен ли я что-то изменить в признаке Illuminate\Foundation\Auth\.. или я должен добавить postLogin() в AuthController?

Вы можете просто переопределить метод getCredentials() в вашем AuthController:

 class AuthController extends Controller { use AuthenticatesAndRegistersUsers; public function getCredentials($request) { $credentials = $request->only($this->loginUsername(), 'password'); return array_add($credentials, 'active', '1'); } } 

При попытке аутентификации пользователя это добавит ограничение active = 1 .

EDIT: Если вам требуется отдельное сообщение об ошибке, например, BrokenBinary , то Laravel позволяет вам определить метод под названием authenticated который вызывается после аутентификации пользователя, но перед перенаправлением, что позволяет выполнять любую обработку после входа. Таким образом, вы можете использовать это, проверяя, активен ли аутентифицированный пользователь, и выдают исключение или отображают сообщение об ошибке, если нет:

 class AuthController extends Controller { use AuthenticatesAndRegistersUsers; public function authenticated(Request $request, User $user) { if ($user->active) { return redirect()->intended($this->redirectPath()); } else { // Raise exception, or redirect with error saying account is not active } } } 

Не забудьте импортировать класс класса « Request » и «Модель User ».

Теперь я изменил промежуточное ПО auth /app/Http/Middleware/Authenticate.php (добавил блок ниже комментария):

 /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if ($this->auth->guest()) { if ($request->ajax()) { return response('Unauthorized.', 401); } else { return redirect()->guest('auth/login'); } } #logout if user not active if($this->auth->check() && $this->auth->user()->active !== 1){ $this->auth->logout(); return redirect('auth/login')->withErrors('sorry, this user account is deactivated'); } return $next($request); } из /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if ($this->auth->guest()) { if ($request->ajax()) { return response('Unauthorized.', 401); } else { return redirect()->guest('auth/login'); } } #logout if user not active if($this->auth->check() && $this->auth->user()->active !== 1){ $this->auth->logout(); return redirect('auth/login')->withErrors('sorry, this user account is deactivated'); } return $next($request); } 

Кажется, он также выводит неактивных пользователей, если они уже вошли в систему.

Я бы добавил следующее в функции postLogin() .

  $this->validate($request, [ 'email' => 'required|email', 'password' => 'required', ]); if ($this->auth->validate(['email' => $request->email, 'password' => $request->password, 'active' => 0])) { return redirect($this->loginPath()) ->withInput($request->only('email', 'remember')) ->withErrors('Your account is Inactive or not verified'); } 

active – это флаг в пользовательской таблице. 0 = Неактивный, 1 = активный. поэтому вся функция будет выглядеть следующим образом ..

 public function postLogin(Request $request) { $this->validate($request, [ 'email' => 'required|email', 'password' => 'required', ]); if ($this->auth->validate(['email' => $request->email, 'password' => $request->password, 'active' => 0])) { return redirect($this->loginPath()) ->withInput($request->only('email', 'remember')) ->withErrors('Your account is Inactive or not verified'); } $credentials = array('email' => $request->email, 'password' => $request->password); if ($this->auth->attempt($credentials, $request->has('remember'))){ return redirect()->intended($this->redirectPath()); } return redirect($this->loginPath()) ->withInput($request->only('email', 'remember')) ->withErrors([ 'email' => 'Incorrect email address or password', ]); } 

Решено : эта ссылка (учебник) поможет вам: https://medium.com/@mshanak/solved-tutorial-laravel-5-3-disable-enable-block-user-login-web-passport-oauth-4bfb74b0c810

шаг 1:

 add new field to the User table called 'status' (1:enabled, 0:disabed) 

шаг 2:

 to block the web login , in app/Http/Controllers/Auth/LoginController.php add the follwoing function: /** * Get the needed authorization credentials from the request. * * @param \Illuminate\Http\Request $request * @return array */ protected function credentials(\Illuminate\Http\Request $request) { $credentials = $request->only($this->username(), 'password'); return array_add($credentials, 'status', '1'); } 

Шаг 3:

 to block the user when using passport authentication ( token ) , in the User.php model add the following function : public function findForPassport($identifier) { return User::orWhere('email', $identifier)->where('status', 1)->first(); } 

Готово 🙂

На Laravel 5.3.* app/Http/Controllers/Auth/LoginController обновления app/Http/Controllers/Auth/LoginController

 class LoginController extends Controller { use AuthenticatesUsers; /** * Get the needed authorization credentials from the request. * * @param \Illuminate\Http\Request $request * @return array */ protected function credentials(\Illuminate\Http\Request $request) { $credentials = $request->only($this->username(), 'password'); return array_add($credentials, 'active', '1'); } // your code here