最近在和同学参与一个创业项目,用到了laravel,仔细研究了一下,发现laravel封装了很多开箱即用的方法,通过traits实现引入后,就可以使用这些方法,今天我们来分析一下<code>AuthenticatesAndRegistersUsers ThrottlesLogins</code>,这两个类,第一个是内部封装了<code>getLogin postLogin getRegister postRegister getLogout</code>的一个类,通过使用<code>traits AuthenticatesAndRegistersUsers</code>就可以实现把<code>AuthenticatesAndRegistersUsers</code>引入到<code>authController<code>中,具体实现稍后会有代码来说明。<code>ThrottlesLogins</code>是内部封装了一个限制登录次数的一个类。下面来通过代码说明。<p>
明白这些内容,需要明白laravel的多用户认证系统,稍后有时间我会写一篇,把自己项目分析一下。<p>
//先展示一个登录验证的路由,两种方法
//第一种是通过Route::group实现路由组
Route::group(['middleware=>['web']],function(){
Route::resource('/article','ArticleController');
//登录
Route::get('auth/login','Auth\AuthController@getLogin');
Route::post('auth/login','Auth\AuthController@postLogin');
//认证
Route::get('auth/register','Auth\AuthController@getRegister');
Route::post('auth/register','Auth\AuthController@postRegister');
//登出
Route::get('auth/logout','Auth\AuthController@getLogout');
})
//第二种是通过Route::group实现路由组
Route::controllers([
'auth'=>'Auth\AuthController';
''password'=>'Auth\PasswordController'
])
(1)上面这些在laravel 5.2里面都是要包含在web这个中间件的<code>['middleware' => ['web']</code> </li>
(2)login 和 register是在“保护”内的,而logout则不是,具体可以看AuthController.php,主要是因为logout比较随意,也不能用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,不在中间件保护范围内
}
protected function validator(array $data)//这里自带了一个验证逻辑,request的验证有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,在函数体里面就是用了model的create方法,直接在数据库生成数据
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}
在<code>AuthenticatesAndRegistersUsers</code>看到了<code>use AuthenticatesUsers, RegistersUsers </code>这里是重点,使用了两个类,一个是验证用户,一个是注册用户。<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();//调用本类的showLoginForm方法
}
/**
* Show the application login form.
*
* @return \Illuminate\Http\Response
*/
public function showLoginForm()//供getLogin调用
{
$view = property_exists($this, 'loginView')//判断本类是否存在loginView属性,存在就调用,否则调用auth.authenticate
? $this->loginView : 'auth.authenticate';
if (view()->exists($view)) {//如果存在就调用
return view($view);//调用view这个视图模板
}
return view('auth.login');//如果不存在就调用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);//调用login,request是参数
}
/**
* 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验证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();//判断是否限制登录次数
if ($throttles && $lockedOut = $this->hasTooManyLoginAttempts($request)) {//hasTooManyLoginAttempts来判断登录次数,系统默认五次。
$this->fireLockoutEvent($request);//触发锁定登录,一分钟。
return $this->sendLockoutResponse($request);
}
$credentials = $this->getCredentials($request);//调用getCredentials验证
if (Auth::guard($this->getGuard())->attempt($credentials, $request->has('remember'))) {//使用auth::guard来访问指定的guard实例,
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)//验证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)//单独获取部分输入数据
{
return $request->only($this->loginUsername(), 'password');//单独获取部分输入数据
}
/**
* 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 : '/');//判断是否有登出后跳转这个选项
}
/**
* 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;
}
}
因为路由上看到要处理getlogin,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')) {//如果设置了注册页面,就进去
return view($this->registerView);
}
return view('auth.register');//否则调用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());//验证request
if ($validator->fails()) {
$this->throwValidationException(
$request, $validator
);
}
Auth::guard($this->getGuard())->login($this->create($request->all()));//先访问指定的guard实例,然后登入到一个指定的用户上
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;
}
}