2015-11-09 24 views
0

我是Laravel的新用戶並使用授權。我正在尋找更改Auth默認sql的方式。其實,Laravel做它用在下面這個簡單的SQL命令:在Laravel中爲授權設置自定義的SQL 5

SELECT * FROM users WHERE login="something" AND password = "something" LIMIT 1 

我試圖更改默認的SQL是這樣的:

SELECT 
u.id, u.name, c.company 
FROM 
users u, companies c 
WHERE 
u.login="something" AND 
u.password = "something" AND 
u.companyId = c.id 
LIMIT 1 

我明白我應該創建自定義授權系統:箱新用戶提供者和授權提供者。

首先,我創建驗證文件夾內的應用程序,並添加有CustomUserProvider.php

CustomUserProvider.php

<?php namespace App\Auth; 

use Illuminate\Contracts\Auth\Authenticatable as UserContract; 
use Illuminate\Contracts\Auth\UserProvider as UserProviderInterface; 
use App\Models\User; 

class CustomUserProvider implements UserProviderInterface { 

    protected $model; 

    public function __construct(UserContract $model) 
    { 
     $this->model = $model; 
    } 

    public function retrieveById($identifier) 
    { 

    } 

    public function retrieveByToken($identifier, $token) 
    { 

    } 

    public function updateRememberToken(UserContract $user, $token) 
    { 

    } 

    public function retrieveByCredentials(array $credentials) 
    { 

    } 

    public function validateCredentials(UserContract $user, array $credentials) 
    { 

    } 

} 

customAuthProvider.php文件,在App/Providers

<?php namespace App\Providers; 

use App\Models\User; 
use Illuminate\Support\Facades\Auth; 
use App\Auth\CustomUserProvider; 
use Illuminate\Support\ServiceProvider; 

class CustomAuthProvider extends ServiceProvider { 

    /** 
    * Bootstrap the application services. 
    * 
    * @return void 
    */ 
    public function boot() 
    { 
     $this->app['auth']->extend('custom',function() 
     { 
      return new CustomUserProvider(new User); 
     }); 
    } 

    /** 
    * Register the application services. 
    * 
    * @return void 
    */ 
    public function register() 
    { 
     // 
    } 

} 

最後,我把司機設定爲客戶湯姆config/Auth.php

'driver' => 'custom' 

我要找我使用如何使用自定義的SQL命令授權(登錄)這個自定義類的方式? 或者這種方式是錯誤的?

回答

1

如果您只需要在驗證期間從數據庫中提取用戶的查詢的附加約束條件,則可以使用更簡單的方法實現此目的。

首先,Laravel提供AuthenticatesUsers特徵,您可以在控制器中使用它來處理驗證請求。默認實現使用username字段從數據庫中提取用戶,然後,如果找到匹配的用戶,則驗證其密碼。

可以通過在控制器中重寫getCredentials方法來定製用於從數據庫中提取用戶的屬性列表。在你的情況下,下面應該是足夠使用他們的用戶名和公司ID加載用戶:

protected function getCredentials(Request $request) 
{ 
    return $request->only($this->loginUsername(), 'password', 'companyId); 
} 

一旦你添加,用戶應登錄表單中提供自己的用戶名,companyId和密碼,他們將進行身份驗證只有存在具有屬於給定公司的給定用戶名並且所提供的密碼有效的用戶。

更新:如果您決定不使用該特徵,但希望手動驗證用戶,則可以採用非常類似的方式進行驗證。當調用Auth::attempt()你只需要傳遞應該用於對用戶進行認證的所有標準,如:

Auth::attempt([ 
    'username' => Input::get('username'), 
    'companyId' => Input::get('companyId'), 
    'password' => Input::get('password') 
]); 
+0

有一些誤解。我應該在哪裏準確地放置這段代碼?哪個控制器? 'loginUsername()'給出一個錯誤,說這個方法不存在。它將如何識別'companyId'? – Rashad

+0

您應該將AuthenticatesUsers trait添加到要處理登錄請求的控制器,例如AuthController應該與新的Laravel項目捆綁在一起。這種方法是這個特徵的一部分。 –

+0

我已經更新了答案 - 它現在包含示例如何使用附加條件驗證用戶,而不使用特徵或AuthController –