我的控制器中有一个正常运行的用户登录路由,但是该方法本身很长,并且处理了多个问题,例如用户被禁止的可能性,IP日志记录等。我想分解该方法,使其更易于管理,我想知道这是否可能?以下是 'postLogin()' 是路由的 3 种方法:
public function postLogin()
{
$validator = Validator::make(Input::all(), array(
'login-username' => 'required',
'login-password' => 'required'
));
if($validator->fails())
return Redirect::back()->withErrors($validator)->withInput();
else
{
$user_attempt = Input::get('login-username');
$pass_attempt = Input::get('login-password');
$auth = Auth::attempt(array(
'username' => $user_attempt,
'password' => $pass_attempt
), true);
if($auth)
$this->handleAuth();
else
return Redirect::route('home')->with('fail', 'Incorrect username or password, username: ' . $user_attempt . ' pass: ' . $pass_attempt);
}
}
private function handleAuth()
{
$username = Auth::user()->username;
$banned_info = UserBans::getBanned($username);
$stored_ip = Auth::user()->ip_address;
$current_ip = User::getIp();
if($stored_ip != $current_ip)
User::updateIp(Auth::user(), $current_ip);
if(is_null($banned_info))
return Redirect::intended('/');
else
$this->handleBan($banned_info, $current_ip);
}
private function handleBan($banned_info, $current_ip)
{
if(UserBans::isBanned($banned_info['ban_end']))
{
$message = "This account is currently banned until: " . $banned_info['ban_end'] . " Reason: " . $banned_info['reason'];
if($banned_info['ip_address'] != $current_ip)
{
$banned_model = UserBans::getBannedModel($banned_info['id']);
User::updateIP($banned_model, $current_ip);
}
Auth::logout();
return Redirect::route('home')->with('fail', $message);
}
else
{
UserBans::destroy($banned_info['id']);
return Redirect::intended('/');
}
}
我发现的问题是主控制器方法将毫无问题地调用辅助方法,但是辅助器方法尝试重定向到路由,例如在handleAuth()中:
if(is_null($banned_info))
return Redirect::intended('/');
如果用户未被禁止并且具有正确的凭据,则会发生这种情况,通常它会重定向到主页并且您将登录,但是当此方法调用预期时,我在"postLogin"路由 url 处留下了一个空白页面。如果您刷新页面,您将在主页上并已登录。以下是相关路线:
Route::group(array('before' => 'guest'), function()
{
Route::group(array('before' => 'csrf'), function()
{
Route::post('/user/login', array('uses' => 'UserController@postLogin', 'as' => 'postLogin'));
});
});
这可以用拉拉维尔路由/控制器吗? 如果没有,你能就如何处理这种情况给出任何建议吗?
在 handleAuth()
,return Redirect::intended('/');
正在向postLogin()
返回一些东西。您需要从postLogin()
返回该值。
因此,请在postLogin()
处添加return
。
if($auth)
return $this->handleAuth();
其他修复
在 handleAuth()
中,还要添加return
else
return $this->handleBan($banned_info, $current_ip);
看起来你忘了返回句柄Ban() 结果
public function postLogin()
{
//...
if($auth)
return $this->handleAuth();
//...
}
private function handleAuth()
{
//...
if(is_null($banned_info))
return Redirect::intended('/');
else
return $this->handleBan($banned_info, $current_ip);
}