最近在和同學(xué)參與一個創(chuàng)業(yè)項(xiàng)目淋淀,用到了laravel震鹉,仔細(xì)研究了一下纲爸,發(fā)現(xiàn)laravel封裝了很多開箱即用的方法亥鸠,通過traits實(shí)現(xiàn)引入后,就可以使用這些方法识啦,今天我們來分析一下<code>AuthenticatesAndRegistersUsers ThrottlesLogins</code>负蚊,這兩個類,第一個是內(nèi)部封裝了<code>getLogin postLogin getRegister postRegister getLogout</code>的一個類颓哮,通過使用<code>traits AuthenticatesAndRegistersUsers</code>就可以實(shí)現(xiàn)把<code>AuthenticatesAndRegistersUsers</code>引入到<code>authController<code>中家妆,具體實(shí)現(xiàn)稍后會有代碼來說明。<code>ThrottlesLogins</code>是內(nèi)部封裝了一個限制登錄次數(shù)的一個類冕茅。下面來通過代碼說明伤极。<p>
明白這些內(nèi)容,需要明白laravel的多用戶認(rèn)證系統(tǒng)姨伤,稍后有時(shí)間我會寫一篇哨坪,把自己項(xiàng)目分析一下。<p>
//先展示一個登錄驗(yàn)證的路由乍楚,兩種方法
//第一種是通過Route::group實(shí)現(xiàn)路由組
Route::group(['middleware=>['web']],function(){
Route::resource('/article','ArticleController');
//登錄
Route::get('auth/login','Auth\AuthController@getLogin');
Route::post('auth/login','Auth\AuthController@postLogin');
//認(rèn)證
Route::get('auth/register','Auth\AuthController@getRegister');
Route::post('auth/register','Auth\AuthController@postRegister');
//登出
Route::get('auth/logout','Auth\AuthController@getLogout');
})
//第二種是通過Route::group實(shí)現(xiàn)路由組
Route::controllers([
'auth'=>'Auth\AuthController';
''password'=>'Auth\PasswordController'
])
(1)上面這些在laravel 5.2里面都是要包含在web這個中間件的<code>['middleware' => ['web']</code> </li>
(2)login 和 register是在“保護(hù)”內(nèi)的当编,而logout則不是,具體可以看AuthController.php徒溪,主要是因?yàn)閘ogout比較隨意忿偷,也不能用session來限制其訪問</li>
下面是Authcontroller的代碼
namespace App\Http\Controllers\Auth;
use App\Models\User;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class AuthController extends Controller{
use AuthenticatesUsers, ThrottlesLogins;//通過traits引入
/** * Create a new authentication controller instance. */
public function __construct(){
$this->middleware('guest', ['except' => 'getLogout']);//排除了logout,不在中間件保護(hù)范圍內(nèi)
}
protected function validator(array $data)//這里自帶了一個驗(yàn)證邏輯臊泌,request的驗(yàn)證有2種方法鲤桥,一種是寫request文件,一種就是用validator
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
protected function create(array $data)//這個就是create缺虐,在函數(shù)體里面就是用了model的create方法芜壁,直接在數(shù)據(jù)庫生成數(shù)據(jù)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}
在<code>AuthenticatesAndRegistersUsers</code>看到了<code>use AuthenticatesUsers, RegistersUsers </code>這里是重點(diǎn),使用了兩個類高氮,一個是驗(yàn)證用戶慧妄,一個是注冊用戶。<p>
下面是AuthenticatesUsers
namespace Illuminate\Foundation\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Lang;
trait AuthenticatesUsers
{
use RedirectsUsers;
/**
* Show the application login form.
*
* @return \Illuminate\Http\Response
*/
public function getLogin()
{
return $this->showLoginForm();//調(diào)用本類的showLoginForm方法
}
/**
* Show the application login form.
*
* @return \Illuminate\Http\Response
*/
public function showLoginForm()//供getLogin調(diào)用
{
$view = property_exists($this, 'loginView')//判斷本類是否存在loginView屬性剪芍,存在就調(diào)用塞淹,否則調(diào)用auth.authenticate
? $this->loginView : 'auth.authenticate';
if (view()->exists($view)) {//如果存在就調(diào)用
return view($view);//調(diào)用view這個視圖模板
}
return view('auth.login');//如果不存在就調(diào)用auth文件夾下的login模板
}
/**
* Handle a login request to the application.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function postLogin(Request $request)//這里有了request請求
{
return $this->login($request);//調(diào)用login,request是參數(shù)
}
/**
* Handle a login request to the application.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function login(Request $request)//IOC注入request
{
$this->validateLogin($request);//通過本類validateLogin驗(yàn)證request
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
$throttles = $this->isUsingThrottlesLoginsTrait();//判斷是否限制登錄次數(shù)
if ($throttles && $lockedOut = $this->hasTooManyLoginAttempts($request)) {//hasTooManyLoginAttempts來判斷登錄次數(shù)罪裹,系統(tǒng)默認(rèn)五次饱普。
$this->fireLockoutEvent($request);//觸發(fā)鎖定登錄运挫,一分鐘。
return $this->sendLockoutResponse($request);
}
$credentials = $this->getCredentials($request);//調(diào)用getCredentials驗(yàn)證
if (Auth::guard($this->getGuard())->attempt($credentials, $request->has('remember'))) {//使用auth::guard來訪問指定的guard實(shí)例套耕,
return $this->handleUserWasAuthenticated($request, $throttles);
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
if ($throttles && ! $lockedOut) {
$this->incrementLoginAttempts($request);
}
return $this->sendFailedLoginResponse($request);
}
/**
* Validate the user login request.
*
* @param \Illuminate\Http\Request $request
* @return void
*/
protected function validateLogin(Request $request)//驗(yàn)證request
{
$this->validate($request, [
$this->loginUsername() => 'required', 'password' => 'required',
]);
}
/**
* Send the response after the user was authenticated.
*
* @param \Illuminate\Http\Request $request
* @param bool $throttles
* @return \Illuminate\Http\Response
*/
protected function handleUserWasAuthenticated(Request $request, $throttles)
{
if ($throttles) {
$this->clearLoginAttempts($request);
}
if (method_exists($this, 'authenticated')) {
return $this->authenticated($request, Auth::guard($this->getGuard())->user());
}
return redirect()->intended($this->redirectPath());
}
/**
* Get the failed login response instance.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
protected function sendFailedLoginResponse(Request $request)
{
return redirect()->back()
->withInput($request->only($this->loginUsername(), 'remember'))
->withErrors([
$this->loginUsername() => $this->getFailedLoginMessage(),
]);
}
/**
* Get the failed login message.
*
* @return string
*/
protected function getFailedLoginMessage()
{
return Lang::has('auth.failed')
? Lang::get('auth.failed')
: 'These credentials do not match our records.';
}
/**
* Get the needed authorization credentials from the request.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
protected function getCredentials(Request $request)//單獨(dú)獲取部分輸入數(shù)據(jù)
{
return $request->only($this->loginUsername(), 'password');//單獨(dú)獲取部分輸入數(shù)據(jù)
}
/**
* Log the user out of the application.
*
* @return \Illuminate\Http\Response
*/
public function getLogout()
{
return $this->logout();
}
/**
* Log the user out of the application.
*
* @return \Illuminate\Http\Response
*/
public function logout()
{
Auth::guard($this->getGuard())->logout();//判斷是否是其他用戶登出
return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/');//判斷是否有登出后跳轉(zhuǎn)這個選項(xiàng)
}
/**
* Get the guest middleware for the application.
*/
public function guestMiddleware()//判斷哪種中間件
{
$guard = $this->getGuard();
return $guard ? 'guest:'.$guard : 'guest';
}
/**
* Get the login username to be used by the controller.
*
* @return string
*/
public function loginUsername()//判斷是否存在username屬性谁帕,存在就獲取,否則獲取email
{
return property_exists($this, 'username') ? $this->username : 'email';
}
/**
* Determine if the class is using the ThrottlesLogins trait.
*
* @return bool
*/
protected function isUsingThrottlesLoginsTrait()
{
return in_array(
ThrottlesLogins::class, class_uses_recursive(static::class)
);
}
/**
* Get the guard to be used during authentication.
*
* @return string|null
*/
protected function getGuard()//判斷是否存在guard屬性冯袍,判斷哪個用戶
{
return property_exists($this, 'guard') ? $this->guard : null;
}
}
因?yàn)槁酚缮峡吹揭幚韌etlogin匈挖,postlogin,getregister康愤,postregister儡循,而AuthenticatesUsers就是主要處理getlogin,postlogin的征冷。<p>
再看RegistersUsers.php
namespace Illuminate\Foundation\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
trait RegistersUsers
{
use RedirectsUsers;
/**
* Show the application registration form.
*
* @return \Illuminate\Http\Response
*/
public function getRegister()//注冊
{
return $this->showRegistrationForm();
}
/**
* Show the application registration form.
*
* @return \Illuminate\Http\Response
*/
public function showRegistrationForm()//展示注冊頁面
{
if (property_exists($this, 'registerView')) {//如果設(shè)置了注冊頁面择膝,就進(jìn)去
return view($this->registerView);
}
return view('auth.register');//否則調(diào)用auth.register的頁面
}
/**
* Handle a registration request for the application.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function postRegister(Request $request)
{
return $this->register($request);
}
/**
* Handle a registration request for the application.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function register(Request $request)
{
$validator = $this->validator($request->all());//驗(yàn)證request
if ($validator->fails()) {
$this->throwValidationException(
$request, $validator
);
}
Auth::guard($this->getGuard())->login($this->create($request->all()));//先訪問指定的guard實(shí)例,然后登入到一個指定的用戶上
return redirect($this->redirectPath());
}
/**
* Get the guard to be used during registration.
*
* @return string|null
*/
protected function getGuard()
{
return property_exists($this, 'guard') ? $this->guard : null;
}
}