{"id":1120,"date":"2016-12-23T12:05:40","date_gmt":"2016-12-23T04:05:40","guid":{"rendered":"http:\/\/hesiwei.cn\/?p=1120"},"modified":"2016-12-23T12:05:40","modified_gmt":"2016-12-23T04:05:40","slug":"laravel%e8%87%aa%e5%ae%9a%e4%b9%89%e7%94%a8%e6%88%b7%e8%ae%a4%e8%af%81","status":"publish","type":"post","link":"http:\/\/hesiwei.cn\/?p=1120","title":{"rendered":"laravel\u81ea\u5b9a\u4e49\u7528\u6237\u8ba4\u8bc1"},"content":{"rendered":"<div id=\"MathJax_Message\"><\/div>\n<h2 id=\"wiz_toc_0\">\u6dfb\u52a0\u81ea\u5b9a\u4e49\u7684 Guard<\/h2>\n<p>\u9700\u8981\u901a\u8fc7Auth\u95e8\u9762\u7684extend\u65b9\u6cd5\u5b9a\u4e49\u81ea\u5df1\u7684\u8ba4\u8bc1guard\uff0c\u5728App\\Providers\\AuthServiceProvider\u7684boot\u65b9\u6cd5\u4e2d\u5b9e\u73b0\uff1a<\/p>\n<pre><code>public function boot()\n{\n    $this-&gt;registerPolicies();\n\n    Auth::extend('XXX', function($app, $name, array $config) {\n        \/\/ \u8fd4\u56de Illuminate\\Contracts\\Auth\\Guard \u5b9e\u4f8b\n        $guard = new XXXGuard($name,Auth::createUserProvider($config['provider']),$this-&gt;app['session.store']);\n        \/\/\u4e8b\u4ef6\n        if (method_exists($guard, 'setDispatcher')) {\n            $guard-&gt;setDispatcher($this-&gt;app['events']);\n        }\n        \/\/\u8bf7\u6c42\n        if (method_exists($guard, 'setRequest')) {\n            $guard-&gt;setRequest($this-&gt;app-&gt;refresh('request', $guard, 'setRequest'));\n        }\n        return $guard;\n    });\n}\n<\/code><\/pre>\n<p><!--more--><\/p>\n<p>\u4f20\u9012\u7ed9 extend \u65b9\u6cd5\u7684\u95ed\u5305\u56de\u8c03\u9700\u8981\u8fd4\u56de Illuminate\\Contracts\\Auth\\Guard \u7684\u5b9e\u73b0\u5b9e\u4f8b\uff0c\u8be5\u63a5\u53e3\u5305\u542b\u4e86\u81ea\u5b9a\u4e49\u8ba4\u8bc1 guard \u9700\u8981\u7684\u4e00\u4e9b\u65b9\u6cd5:<\/p>\n<pre><code>&lt;?php\nnamespace App\\Services\\Auth;\nuse Illuminate\\Auth\\Events\\Authenticated;\nuse Illuminate\\Auth\\Events\\Failed;\nuse Illuminate\\Auth\\Events\\Login;\nuse Illuminate\\Auth\\Events\\Attempting;\nuse Illuminate\\Auth\\Events\\Logout;\nuse Illuminate\\Contracts\\Auth\\Authenticatable;\nuse Illuminate\\Contracts\\Auth\\Guard;\nuse Illuminate\\Auth\\GuardHelpers;\nuse Illuminate\\Contracts\\Auth\\UserProvider;\nuse Illuminate\\Contracts\\Events\\Dispatcher;\nuse Symfony\\Component\\HttpFoundation\\Request;\nuse Symfony\\Component\\HttpFoundation\\Session\\SessionInterface;\n\nclass XXXGuard implements Guard\n{\n    use GuardHelpers;\n\n    protected $session;\n    protected $name;\n    protected $loggedOut = false;\n    protected $request;\n    protected $events;\n\n    public function __construct($name,UserProvider $provider,SessionInterface $session,Request $request = null)\n    {\n        $this-&gt;name = $name;\n        $this-&gt;provider = $provider;\n        $this-&gt;session = $session;\n        $this-&gt;request = $request;\n    }\n\n    \/**\n     * Attempt to authenticate a user using the given credentials.\n     *\n     * @param  array  $credentials\n     * @param  bool   $remember\n     * @param  bool   $login\n     * @return bool\n     *\/\n    public function attempt(array $credentials = [], $remember = false, $login = true)\n    {\n        $this-&gt;fireAttemptEvent($credentials, $remember, $login);\n        $user = $this-&gt;provider-&gt;retrieveByCredentials($credentials);\n        if ($this-&gt;hasValidCredentials($user, $credentials)) {\n            if ($login) {\n                $this-&gt;login($user, $remember);\n            }\n            return true;\n        }\n        if ($login) {\n            $this-&gt;fireFailedEvent($user, $credentials);\n        }\n        return false;\n    }\n\n    \/**\n     * Determine if the user matches the credentials.\n     *\n     * @param  mixed  $user\n     * @param  array  $credentials\n     * @return bool\n     *\/\n    protected function hasValidCredentials($user, $credentials)\n    {\n        return ! is_null($user) &amp;&amp; $this-&gt;provider-&gt;validateCredentials($user, $credentials);\n    }\n\n    \/**\n     * Log a user into the application.\n     *\n     * @param  \\Illuminate\\Contracts\\Auth\\Authenticatable  $user\n     * @param  bool  $remember\n     * @return void\n     *\/\n    public function login(Authenticatable $user, $remember = false)\n    {\n        $this-&gt;updateSession($user-&gt;getAuthIdentifier());\n\n        \/\/ If we have an event dispatcher instance set we will fire an event so that\n        \/\/ any listeners will hook into the authentication events and run actions\n        \/\/ based on the login and logout events fired from the guard instances.\n        $this-&gt;fireLoginEvent($user, $remember);\n        $this-&gt;setUser($user);\n    }\n\n    \/**\n     * Update the session with the given ID.\n     *\n     * @param  string  $id\n     * @return void\n     *\/\n    protected function updateSession($id)\n    {\n        $this-&gt;session-&gt;set($this-&gt;getName(), $id);\n\n        $this-&gt;session-&gt;migrate(true);\n    }\n\n    \/**\n     * Get a unique identifier for the auth session value.\n     *\n     * @return string\n     *\/\n    public function getName()\n    {\n        return 'login_'.$this-&gt;name.'_'.sha1(static::class);\n    }\n\n\n    \/**\n     * Get the currently authenticated user.\n     *\n     * @return \\Illuminate\\Contracts\\Auth\\Authenticatable|null\n     *\/\n    public function user()\n    {\n        if ($this-&gt;loggedOut) {\n            return;\n        }\n\n        \/\/ If we've already retrieved the user for the current request we can just\n        \/\/ return it back immediately. We do not want to fetch the user data on\n        \/\/ every call to this method because that would be tremendously slow.\n        if (! is_null($this-&gt;user)) {\n            return $this-&gt;user;\n        }\n\n        $id = $this-&gt;session-&gt;get($this-&gt;getName());\n        \/\/ First we will try to load the user using the identifier in the session if\n        \/\/ one exists. Otherwise we will check for a \"remember me\" cookie in this\n        \/\/ request, and if one exists, attempt to retrieve the user using that.\n        $user = null;\n\n        if (! is_null($id)) {\n            if ($user = $this-&gt;provider-&gt;retrieveById($id)) {\n                $this-&gt;fireAuthenticatedEvent($user);\n            }\n        }\n\n        return $this-&gt;user = $user;\n    }\n\n    public function id()\n    {\n        if ($this-&gt;loggedOut) {\n            return;\n        }\n\n        if ($this-&gt;user()) {\n            return $this-&gt;user()-&gt;getAuthIdentifier();\n        }\n\n        return $this-&gt;session-&gt;get($this-&gt;getName());\n    }\n\n    \/**\n     * Validate a user's credentials.\n     *\n     * @param  array  $credentials\n     * @return bool\n     *\/\n    public function validate(array $credentials = [])\n    {\n        return $this-&gt;attempt($credentials, false, false);\n    }\n\n    \/**\n     * Fire the login event if the dispatcher is set.\n     *\n     * @param  \\Illuminate\\Contracts\\Auth\\Authenticatable  $user\n     * @param  bool  $remember\n     * @return void\n     *\/\n    protected function fireLoginEvent($user, $remember = false)\n    {\n        if (isset($this-&gt;events)) {\n            $this-&gt;events-&gt;fire(new Login($user, $remember));\n        }\n    }\n\n    \/**\n     * Fire the authenticated event if the dispatcher is set.\n     *\n     * @param  \\Illuminate\\Contracts\\Auth\\Authenticatable  $user\n     * @return void\n     *\/\n    protected function fireAuthenticatedEvent($user)\n    {\n        if (isset($this-&gt;events)) {\n            $this-&gt;events-&gt;fire(new Authenticated($user));\n        }\n    }\n\n    \/**\n     * Fire the attempt event with the arguments.\n     *\n     * @param  array  $credentials\n     * @param  bool  $remember\n     * @param  bool  $login\n     * @return void\n     *\/\n    protected function fireAttemptEvent(array $credentials, $remember, $login)\n    {\n        if (isset($this-&gt;events)) {\n            $this-&gt;events-&gt;fire(new Attempting(\n                $credentials, $remember, $login\n            ));\n        }\n    }\n\n    \/**\n     * Fire the failed authentication attempt event with the given arguments.\n     *\n     * @param  \\Illuminate\\Contracts\\Auth\\Authenticatable|null  $user\n     * @param  array  $credentials\n     * @return void\n     *\/\n    protected function fireFailedEvent($user, array $credentials)\n    {\n        if (isset($this-&gt;events)) {\n            $this-&gt;events-&gt;fire(new Failed($user, $credentials));\n        }\n    }\n\n\n    \/**\n     * Log the user out of the application.\n     *\n     * @return void\n     *\/\n    public function logout()\n    {\n        $user = $this-&gt;user();\n\n        \/\/ If we have an event dispatcher instance, we can fire off the logout event\n        \/\/ so any further processing can be done. This allows the developer to be\n        \/\/ listening for anytime a user signs out of this application manually.\n        $this-&gt;clearUserDataFromStorage();\n\n        if (isset($this-&gt;events)) {\n            $this-&gt;events-&gt;fire(new Logout($user));\n        }\n\n        \/\/ Once we have fired the logout event we will clear the users out of memory\n        \/\/ so they are no longer available as the user is no longer considered as\n        \/\/ being signed into this application and should not be available here.\n        $this-&gt;user = null;\n\n        $this-&gt;loggedOut = true;\n    }\n\n    \/**\n     * Remove the user data from the session and cookies.\n     *\n     * @return void\n     *\/\n    protected function clearUserDataFromStorage()\n    {\n        $this-&gt;session-&gt;remove($this-&gt;getName());\n    }\n\n    \/**\n     * Get the event dispatcher instance.\n     *\n     * @return \\Illuminate\\Contracts\\Events\\Dispatcher\n     *\/\n    public function getDispatcher()\n    {\n        return $this-&gt;events;\n    }\n\n    \/**\n     * Set the event dispatcher instance.\n     *\n     * @param  \\Illuminate\\Contracts\\Events\\Dispatcher  $events\n     * @return void\n     *\/\n    public function setDispatcher(Dispatcher $events)\n    {\n        $this-&gt;events = $events;\n    }\n\n    \/**\n     * Get the session store used by the guard.\n     *\n     * @return \\Illuminate\\Session\\Store\n     *\/\n    public function getSession()\n    {\n        return $this-&gt;session;\n    }\n\n    \/**\n     * Get the user provider used by the guard.\n     *\n     * @return \\Illuminate\\Contracts\\Auth\\UserProvider\n     *\/\n    public function getProvider()\n    {\n        return $this-&gt;provider;\n    }\n\n    \/**\n     * Set the user provider used by the guard.\n     *\n     * @param  \\Illuminate\\Contracts\\Auth\\UserProvider  $provider\n     * @return void\n     *\/\n    public function setProvider(UserProvider $provider)\n    {\n        $this-&gt;provider = $provider;\n    }\n\n    \/**\n     * Return the currently cached user.\n     *\n     * @return \\Illuminate\\Contracts\\Auth\\Authenticatable|null\n     *\/\n    public function getUser()\n    {\n        return $this-&gt;user;\n    }\n\n    \/**\n     * Set the current user.\n     *\n     * @param  \\Illuminate\\Contracts\\Auth\\Authenticatable  $user\n     * @return $this\n     *\/\n    public function setUser(Authenticatable $user)\n    {\n        $this-&gt;user = $user;\n\n        $this-&gt;loggedOut = false;\n\n        $this-&gt;fireAuthenticatedEvent($user);\n\n        return $this;\n    }\n\n    public function setRequest(Request $request)\n    {\n        $this-&gt;request = $request;\n\n        return $this;\n    }\n}\n<\/code><\/pre>\n<p>\u5b9a\u4e49\u597d\u81ea\u5df1\u7684\u8ba4\u8bc1 guard \u4e4b\u540e\uff0c\u53ef\u4ee5\u5728\u914d\u7f6e\u6587\u4ef6 auth.php \u7684 guards \u914d\u7f6e\u4e2d\u4f7f\u7528\u8bdd\u8fd9\u4e2a guard\uff1a<\/p>\n<pre><code>'guards' =&gt; [\n    'api' =&gt; [\n        'driver' =&gt; 'XXX',\n        'provider' =&gt; 'users',\n    ],\n],\n<\/code><\/pre>\n<h2 id=\"wiz_toc_1\">\u6dfb\u52a0\u81ea\u5b9a\u4e49\u7528\u6237\u63d0\u4f9b\u8005<\/h2>\n<p>\u540c\u6837\u5728App\\Providers\\AuthServiceProvider\u7684boot\u65b9\u6cd5\u4e2d\u5b9e\u73b0\uff1a<\/p>\n<pre><code>public function boot()\n{\n    $this-&gt;registerPolicies();\n    \/\/\n    Auth::provider('YYY', function($app, array $config) {\n        \/\/ \u8fd4\u56de Illuminate\\Contracts\\Auth\\UserProvider\u5b9e\u4f8b\n        return new YYYProvider($config['model']);\n    });\n}\n<\/code><\/pre>\n<p>\u5b9a\u4e49\u63d0\u4f9b\u8005,\u8fd4\u56deIlluminate\\Contracts\\Auth\\UserProvider\u7684\u5b9e\u73b0\u5b9e\u4f8b\uff1a<\/p>\n<pre><code>&lt;?php\nnamespace App\\Services\\Auth;\n\nuse Illuminate\\Contracts\\Auth\\Authenticatable;\nuse Illuminate\\Contracts\\Auth\\UserProvider;\nuse Illuminate\\Support\\Str;\n\nclass YYYProvider implements UserProvider\n{\n    protected $model;\n\n    public function __construct($model)\n    {\n        $this-&gt;model = $model;\n    }\n\n    public function createModel()\n    {\n        $class = '\\\\'.ltrim($this-&gt;model, '\\\\');\n\n        return new $class;\n    }\n\n    \/**\n     * Retrieve a user by their unique identifier.\n     *\n     * @param  mixed  $identifier\n     * @return \\Illuminate\\Contracts\\Auth\\Authenticatable|null\n     *\/\n    public function retrieveById($identifier)\n    {\n        return $this-&gt;createModel()-&gt;newQuery()-&gt;find($identifier);\n    }\n\n    \/**\n     * Retrieve a user by their unique identifier and \"remember me\" token.\n     *\n     * @param  mixed   $identifier\n     * @param  string  $token\n     * @return \\Illuminate\\Contracts\\Auth\\Authenticatable|null\n     *\/\n    public function retrieveByToken($identifier, $token)\n    {\n        \/\/todo \u6839\u636etoken\u5b9e\u73b0\u8bb0\u4f4f\u529f\u80fd\n        return null;\n    }\n\n    \/**\n     * Update the \"remember me\" token for the given user in storage.\n     *\n     * @param  \\Illuminate\\Contracts\\Auth\\Authenticatable  $user\n     * @param  string  $token\n     * @return void\n     *\/\n    public function updateRememberToken(Authenticatable $user, $token)\n    {\n        \/\/code\n    }\n\n    \/**\n     * Retrieve a user by the given credentials.\n     *\n     * @param  array  $credentials\n     * @return \\Illuminate\\Contracts\\Auth\\Authenticatable|null\n     *\/\n    public function retrieveByCredentials(array $credentials)\n    {\n        if (empty($credentials)) {\n            return;\n        }\n        \/\/ First we will add each credential element to the query as a where clause.\n        \/\/ Then we can execute the query and, if we found a user, return it in a\n        \/\/ Eloquent User \"model\" that will be utilized by the Guard instances.\n        $query = $this-&gt;createModel()-&gt;newQuery();\n\n        foreach ($credentials as $key =&gt; $value) {\n            if (! Str::contains($key, 'password')) {\n                $query-&gt;where($key, $value);\n            }\n        }\n        return $query-&gt;first();\n    }\n\n    \/**\n     * Validate a user against the given credentials.\n     *\n     * @param  \\Illuminate\\Contracts\\Auth\\Authenticatable  $user\n     * @param  array  $credentials\n     * @return bool\n     *\/\n    public function validateCredentials(Authenticatable $user, array $credentials)\n    {\n        $plain = $credentials['password'];\n        \/\/\u5177\u4f53\u9a8c\u8bc1\u5bc6\u7801\u6709\u6548\u6027\u65b9\u6cd5\n        return $user-&gt;Password==md5($plain);\n    }\n\n    \/**\n     * Gets the name of the Eloquent user model.\n     *\n     * @return string\n     *\/\n    public function getModel()\n    {\n        return $this-&gt;model;\n    }\n\n    \/**\n     * Sets the name of the Eloquent user model.\n     *\n     * @param  string  $model\n     * @return $this\n     *\/\n    public function setModel($model)\n    {\n        $this-&gt;model = $model;\n\n        return $this;\n    }\n}\n<\/code><\/pre>\n<p>\u4e4b\u540e\u53ef\u4ee5\u5728\u914d\u7f6e\u6587\u4ef6 config\/auth.php \u4e2d\u5207\u6362\u5230\u65b0\u7684\u7528\u6237\u63d0\u4f9b\u8005<\/p>\n<pre><code>'providers' =&gt; [\n    'users' =&gt; [\n        'driver' =&gt; 'YYY',\n    ],\n],\n<\/code><\/pre>\n<p>\u7136\u540e\uff0c\u5c31\u53ef\u4ee5\u5728\u4f60\u7684 guards \u914d\u7f6e\u4e2d\u4f7f\u7528\u8fd9\u4e2a\u63d0\u4f9b\u8005\u3002<\/p>\n<h2 id=\"wiz_toc_2\">\u5b8c\u7ed3<\/h2>\n<div><a title=\"null\" href=\"http:\/\/www.wiz.cn\/i\/1464f1d5\">null<\/a><\/div>\n","protected":false},"excerpt":{"rendered":"<p>\u6dfb\u52a0\u81ea\u5b9a\u4e49\u7684 Guard \u9700\u8981\u901a\u8fc7Auth\u95e8\u9762\u7684extend\u65b9\u6cd5\u5b9a\u4e49\u81ea\u5df1\u7684\u8ba4\u8bc1guard\uff0c\u5728App\\Provi [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[17],"tags":[],"class_list":["post-1120","post","type-post","status-publish","format-standard","hentry","category-php"],"_links":{"self":[{"href":"http:\/\/hesiwei.cn\/index.php?rest_route=\/wp\/v2\/posts\/1120","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/hesiwei.cn\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/hesiwei.cn\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/hesiwei.cn\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/hesiwei.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=1120"}],"version-history":[{"count":0,"href":"http:\/\/hesiwei.cn\/index.php?rest_route=\/wp\/v2\/posts\/1120\/revisions"}],"wp:attachment":[{"href":"http:\/\/hesiwei.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=1120"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/hesiwei.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=1120"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/hesiwei.cn\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=1120"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}