首頁  >  文章  >  後端開發  >  如何重寫Laravel 的attempt方法呢?因為加密方法是自訂的。

如何重寫Laravel 的attempt方法呢?因為加密方法是自訂的。

WBOY
WBOY原創
2016-08-04 09:20:171779瀏覽

<code>Auth::attempt(array('username' => $username, 'password' => $password),false)
</code>

這個東西裡頭password是想用自己定義的方法加密

回覆內容:

<code>Auth::attempt(array('username' => $username, 'password' => $password),false)
</code>

這個東西裡頭password是想用自己定義的方法加密

文檔確實沒有寫,但是我們可以看看源碼

Auth方法的實作都在 IlluminateAuthGuard裡面

<code>    /**
     * Attempt to authenticate a user using the given credentials.
     *
     * @param  array  $credentials
     * @param  bool   $remember
     * @param  bool   $login
     * @return bool
     */
    public function attempt(array $credentials = [], $remember = false, $login = true)
    {
        $this->fireAttemptEvent($credentials, $remember, $login);

        $this->lastAttempted = $user = $this->provider->retrieveByCredentials($credentials);            
        
        // 看这里
        // If an implementation of UserInterface was returned, we'll ask the provider
        // to validate the user against the given credentials, and if they are in
        // fact valid we'll log the users into the application and return true.
        if ($this->hasValidCredentials($user, $credentials)) {
            if ($login) {
                $this->login($user, $remember);
            }

            return true;
        }

        return false;
    }
    
    /**
     * Determine if the user matches the credentials.
     *
     * @param  mixed  $user
     * @param  array  $credentials
     * @return bool
     */
    protected function hasValidCredentials($user, $credentials)
    {
        // 执行认证驱动器的validCredentials方法
        return ! is_null($user) && $this->provider->validateCredentials($user, $credentials);
    }</code>

預設是使用eloquent作為認證驅動器,所以看看IlluminateAuthEloquentUserProvider裡面的實作

<code>    public function validateCredentials(UserContract $user, array $credentials)
    {
        $plain = $credentials['password'];

        return $this->hasher->check($plain, $user->getAuthPassword());
    }</code>

所以如果要改驗證的邏輯,可以繼承原有的驅動器,然後重寫validateCredentials裡面的邏輯

<code>class TestUserProvider extend EloquentUserProvider
{
    public function validateCredentials(UserContract $user, array $credentials)
    {
        $plain = $credentials['password'];

        return md5($plain) == $user->getAuthPassword();
    }
}</code>

最後設定驅動器,建議載入AppServiceProvider的boot()裡面

<code>Auth::setProvider(new TestUserProvider());</code>

文檔裡有寫!不要偷懶不看文檔,你最近提的問題都是文檔寫的。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn