亚洲最大看欧美片,亚洲图揄拍自拍另类图片,欧美精品v国产精品v呦,日本在线精品视频免费

  • 站長資訊網(wǎng)
    最全最豐富的資訊網(wǎng)站

    Laravel的Auth模塊使用

    本文是基于Laravel 5.4 版本的Auth模塊代碼進行分析書寫;

    模塊組成

    Auth模塊從功能上分為用戶認證和權(quán)限管理兩個部分;從文件組成上,IlluminateAuthPasswords目錄下是密碼重置或忘記密碼處理的小模塊,IlluminateAuth是負責用戶認證和權(quán)限管理的模塊,IlluminateFoundationAuth提供了登錄、修改密碼、重置密碼等一系統(tǒng)列具體邏輯實現(xiàn);下圖展示了Auth模塊各個文件的關(guān)系,并進行簡要說明;

    Laravel的Auth模塊使用

    用戶認證

    HTTP本身是無狀態(tài),通常在系統(tǒng)交互的過程中,使用賬號或者Token標識來確定認證用戶;

    配置文件解讀

    return [     'defaults' => [         'guard' => 'web',         ...     ],     'guards' => [           'web' => [             'driver' => 'session',             'provider' => 'users',         ],         'api' => [                 'driver' => 'token',              'provider' => 'users',         ],     ],     'providers' => [         'users' => [             'driver' => 'eloquent',             'model' => AppUser::class,         ],      ], ],  ];

    從下往上,理解;

    providers是提供用戶數(shù)據(jù)的接口,要標注驅(qū)動對象和目標對象;此處,鍵名users是一套provider的名字,采用eloquent驅(qū)動,modal是AppUser::class;

    guards部分針對認證管理部分進行配置;有兩種認證方式,一種叫web,還有一種是api;web認證是基于Session交互,根據(jù)sessionId獲取用戶id,在users這個provider查詢出此用戶;api認證是基于token值交互,也采用users這個provider;

    defaults項顯示默認使用web認證;

    認證

    Session綁定認證信息:

    // $credentials數(shù)組存放認證條件,比如郵箱或者用戶名、密碼 // $remember 表示是否要記住,生成 `remember_token` public function attempt(array $credentials = [], $remember = false)    public function login(AuthenticatableContract $user, $remember = false)   public function loginUsingId($id, $remember = false)

    HTTP基本認證,認證信息放在請求頭部;后面的請求訪問通過sessionId;

    public function basic($field = 'email', $extraConditions = [])

    只在當前會話中認證,session中不記錄認證信息:

    public function once(array $credentials = []) public function onceUsingId($id) public function onceBasic($field = 'email', $extraConditions = [])

    認證過程中(包括注冊、忘記密碼),定義的事件有這些:

    Attempting 嘗試驗證事件

    Authenticated 驗證通過事件

    Failed 驗證失敗事件

    Lockout 失敗次數(shù)超過限制,鎖住該請求再次訪問事件

    Logi 通過‘remember_token’成功登錄時,調(diào)用的事件

    Logout 用戶退出事件

    Registered 用戶注冊事件

    還有一些其他的認證方法:

    檢查是否存在認證用戶:Auth::check()

    獲取當前認證用戶:Auth::user()

    退出系統(tǒng):Auth::logout()

    密碼處理

    配置解讀

    return [     'defaults' => [         'passwords' => 'users',         ...     ],          'passwords' => [         'users' => [             'provider' => 'users',             'table' => 'password_resets',             'expire' => 60,         ],     ], ]

    從下往上,看配置;

    passwords數(shù)組是重置密碼的配置;users是配置方案的別名,包含三個元素:provider(提供用戶的方案,是上面providers數(shù)組)、table(存放重置密碼token的表)、expire(token過期時間)

    default 項會設置默認的 passwords 重置方案;

    重置密碼的調(diào)用與實現(xiàn)

    先看看Laravel的重置密碼功能是怎么實現(xiàn)的:

    public function reset(array $credentials, Closure $callback) {     // 驗證用戶名、密碼和 token 是否有效     $user = $this->validateReset($credentials);     if (! $user instanceof CanResetPasswordContract) {          return $user;     }              $password = $credentials['password'];     // 回調(diào)函數(shù)執(zhí)行修改密碼,及持久化存儲     $callback($user, $password);     // 刪除重置密碼時持久化存儲保存的 token     $this->tokens->delete($user);     return static::PASSWORD_RESET; }

    再看看FoundationAuth模塊封裝的重置密碼模塊是怎么調(diào)用的:

    // 暴露的重置密碼 API public function reset(Request $request)   {     // 驗證請求參數(shù) token、email、password、password_confirmation     $this->validate($request, $this->rules(), $this->validationErrorMessages());     // 調(diào)用重置密碼的方法,第二個參數(shù)是回調(diào),做一些持久化存儲工作     $response = $this->broker()->reset(         $this->credentials($request), function ($user, $password) {         $this->resetPassword($user, $password);         }     );     // 封裝 Response     return $response == Password::PASSWORD_RESET         ? $this->sendResetResponse($response)         : $this->sendResetFailedResponse($request, $response); } // 獲取重置密碼時的請求參數(shù) protected function credentials(Request $request)  {     return $request->only(         'email', 'password', 'password_confirmation', 'token'     ); } // 重置密碼的真實性驗證后,進行的持久化工作 protected function resetPassword($user, $password) {     // 修改后的密碼、重新生成 remember_token     $user->forceFill([         'password' => bcrypt($password),         'remember_token' => Str::random(60),     ])->save();     // session 中的用戶信息也進行重新賦值                                          $this->guard()->login($user); }

    “忘記密碼 => 發(fā)郵件 => 重置密碼” 的大體流程如下:

    點擊“忘記密碼”,通過路由配置,跳到“忘記密碼”頁面,頁面上有“要發(fā)送的郵箱”這個字段要填寫;

    驗證“要發(fā)送的郵箱”是否是數(shù)據(jù)庫中存在的,如果存在,即向該郵箱發(fā)送重置密碼郵件;

    重置密碼郵件中有一個鏈接(點擊后會攜帶 token 到修改密碼頁面),同時數(shù)據(jù)庫會保存這個 token 的哈希加密后的值;

    填寫“郵箱”,“密碼”,“確認密碼”三個字段后,攜帶 token 訪問重置密碼API,首頁判斷郵箱、密碼、確認密碼這三個字段,然后驗證 token是否有效;如果是,則重置成功;

    權(quán)限管理

    權(quán)限管理是依靠內(nèi)存空間維護的一個數(shù)組變量abilities來維護,結(jié)構(gòu)如下:

    $abilities = array(     '定義的動作名,比如以路由的 as 名(common.dashboard.list)' => function($user) {         // 方法的參數(shù),第一位是 $user, 當前 user, 后面的參數(shù)可以自行決定         return true;  // 返回 true 意味有權(quán)限, false 意味沒有權(quán)限     },     ...... );

    但只用 $abilities,會使用定義的那部分代碼集中在一起太煩索,所以有policy策略類的出現(xiàn);

    policy策略類定義一組實體及實體權(quán)限類的對應關(guān)系,比如以文章舉例:

    有一個 Modal實體類叫 Post,可以為這個實體類定義一個PostPolicy權(quán)限類,在這個權(quán)限類定義一些動作為方法名;

    class PostPolicy {     // update 權(quán)限,文章作者才可以修改     public function update(User $user, Post $post) {         return $user->id === $post->user_id;     } }

    然后在ServiceProvider中注冊,這樣系統(tǒng)就知道,如果你要檢查的類是Post對象,加上你給的動作名,系統(tǒng)會找到PostPolicy類的對應方法;

    protected $policies = [     Post::class => PostPolicy::class, ];

    怎么調(diào)用呢?

    對于定義在abilities數(shù)組的權(quán)限:

    當前用戶是否具備common.dashboard.list權(quán)限:Gate::allows('common.dashboard.list')

    當前用戶是否具備common.dashboard.list權(quán)限:! Gate::denies('common.dashboard.list')

    當前用戶是否具備common.dashboard.list權(quán)限:$request->user()->can('common.dashboard.list')

    當前用戶是否具備common.dashboard.list權(quán)限:! $request->user()->cannot('common.dashboard.list')

    指定用戶是否具備common.dashboard.list權(quán)限:Gate::forUser($user)->allows('common.dashboard.list')

    對于policy策略類調(diào)用的權(quán)限:

    當前用戶是否可以修改文章(Gate 調(diào)用):Gate::allows('update', $post)

    當前用戶是否可以修改文章(user 調(diào)用):$user->can('update', $post)

    當前用戶是否可以修改文章(用幫助函數(shù)):policy($post)->update($user, $post)

    當前用戶是否可以修改文章(Controller 類方法中調(diào)用):$this->authorize('update', $post);

    當前用戶是否可以修改文章(Controller 類同名方法中調(diào)用):$this->authorize($post);

    指定用戶是否可以修改文章(Controller 類方法中調(diào)用):$this->authorizeForUser($user, 'update', $post);

    有用的技巧

    獲取當前系統(tǒng)注冊的權(quán)限,包括兩部分abilities和policies數(shù)組內(nèi)容,代碼如下:

    $gate = app(IlluminateContractsAuthAccessGate::class); $reflection_gate = new ReflectionClass($gate); $policies = $reflection_gate->getProperty('policies'); $policies->setAccessible(true); // 獲取當前注冊的 policies 數(shù)組 dump($policies->getValue($gate));                                                                                                          $abilities = $reflection_gate->getProperty('abilities');                                        $abilities->setAccessible(true); // 獲取當前注冊的 abilities 數(shù)組 dump($abilities->getValue($gate));

    推薦教程:《Laravel教程》

    贊(0)
    分享到: 更多 (0)
    網(wǎng)站地圖   滬ICP備18035694號-2    滬公網(wǎng)安備31011702889846號