自定义身份验证名称功能-Laravel

时间:2020-10-14 06:10:51

标签: laravel

我有多认证流明应用程序设置,一种用于企业,一种用于典型用户。当我被认证为企业时,我想说:

auth()-> business()-> id

而不是:

auth()-> user()-> id

2 个答案:

答案 0 :(得分:0)

创建一个新的班级

#define BAR( pfoo, field ) ( ( (pfoo)->field = (pfoo)->a ), true )

Foo foo;
if ( BAR( &foo, b ) )
    exit( EXIT_SUCCESS );

并更改您的<?php namespace Illuminate\Support\Facades; use Illuminate\Support\Facades\Auth; class CustomAuth extends Auth { public static function company() { return $this->user()->business; //I'm not shure, but some like that } }

config/app.php

您可以在laracast中阅读更多内容。

答案 1 :(得分:0)

如果您使用的是“网络”防护,那么它将使用SessionGuard类作为防护。您可以如下扩展:

class MySessionGuard extends SessionGuard {
    

     private function isAuthenticatedAsBusiness($user) {
         // do your check here
        return false; // or true accordingly
 
   
    public function user() {
         $user = parent::user();
         return !$this->isAuthenticatedAsBusiness($user) ? $user : null;
    }

    public function business() {
         $user = parent::user();
         return $this->isAuthenticatedAsBusiness($user) ? $user : null;
    }
}

然后在您的AuthServiceProvider中注册此警卫:

public function boot() {
   Auth::extend("myweb", function ($app,$name, array $config) {
       $guard = new MySessionGuard(
            $name, 
            Auth::createUserProvider($config['provider']),
            $app["session.store"],
            $app["request"]
        );
        // This is copied from https://github.com/laravel/framework/blob/43bea00fd27c76c01fd009e46725a54885f4d2a5/src/Illuminate/Auth/AuthManager.php#L121
        if (method_exists($guard, 'setDispatcher')) {
            $guard->setDispatcher($this->app['events']);
        }
        if (method_exists($guard, 'setCookieJar')) {
            $guard->setCookieJar($this->app['cookie']);
        }
        return $guard;
   });

   // ...


然后您可以更新您的config/auth.php

'guards' => [
        'web' => [
            'driver' => 'myweb',
            'provider' => 'users',
        ],

        // ...
    ],

您的默认守卫现在应该是您的自定义守卫。