簡體   English   中英

Laravel 4 Auth ::嘗試使用電子郵件或用戶名和密碼

[英]Laravel 4 Auth::attempt using either email or username and password

在laravel中嘗試登錄時,我通常使用如下所示的內容:

if (Auth::attempt(array('email' => $usernameinput, 'password' => $password), true))
{
    // The user is being remembered...
}

基本上$usernameinput將檢查表中的email

我當時正在考慮以另一種方式來執行此操作,例如表中有emailusernamepassword $usernameinput可以是我表中的emailusername段。

如何使用以下條件進行Auth::attempt

(email==$usernameinput OR username==$usernameinput) AND password == $password

好吧,您可以簡單地檢查$usernameinput與電子郵件模式匹配,如果匹配,則使用email字段,否則使用username字段。 這聽起來是合理的,因為,好吧,您的數據庫中實際上不應該包含任何不匹配該模式的電子郵件。 像這樣:

$field = filter_var($usernameinput, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';

if (Auth::attempt([$field => $usernameinput, 'password' => $password], true)) {
    // ...
}

另一個選項是擴展Illuminate\\Auth\\Guard ,在新的服務提供者中添加所需的功能並將其設置為auth組件。

可以這樣做

$field = Validator::make(array('email' => $usernameinput, array('email' => 'email'))->passes() ? 'email' : 'username';
if (Auth::attempt(array($field => $usernameinput, 'password' => $password), true)) {
    return Redirect::intended('profile');
}

用戶可以使用電子郵件字段作為其用戶名,並且該名稱可能與他們用於電子郵件字段的電子郵件不匹配。 更安全地嘗試兩次身份驗證:

if (Auth::attempt(array(
            'email'     => Input::get('email_or_username'),
            'password'  => Input::get('password')
        )) ||
    Auth::attempt(array(
            'username'     => Input::get('email_or_username'),
            'password'  => Input::get('password')
        ))) {
    // SUCCESS
} else {
    // FAILURE
}

這是完整的工作解決方案:(使用Laravel 5.3測試)

只需將此方法(或可以說重寫)添加到app \\ Http \\ Controllers \\ Auth \\ LoginController.php中

public function login(Request $request)
    {
        $usernameinput = $request->input('email');
        $password = $request->input('password');
        $field = filter_var($usernameinput, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';

        if (Auth::attempt([$field => $usernameinput, 'password' => $password])) {
            return redirect()->intended('/');
        } else {
            return $this->sendFailedLoginResponse($request);
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM