如何构建基于类的RequestGuards?

时间:2016-07-12 08:57:46

标签: php authentication lumen separation-of-concerns

我正在尝试构建一个有效的回调来处理Lumen 5.2中的身份验证请求。然而,业务逻辑变得混乱,这不是我喜欢的东西。

是否有可能构建与viaRequest完全相同但具有处理请求的隔离类的东西?

这是我的AuthServiceProvider.php代码:

public function boot()
{
    [...]

    $this->app['auth']->viaRequest('api', function ($request) {

        $typeOfLogins = ['password', 'oauth'];

        switch ($request->input('type'))
        {
            case 'password':
            {
                $user = AuthenticatingUser::where([
                    'email' => $request->input('email')
                ])->first();

                if (! $user || ! $user->authenticable || ! ($user->authenticable instanceof \Core\Entities\User)) {
                    return null;
                }

                return ($this->app['hash']->check($request->input('password'), $user->authenticable->password))
                    ? $user
                    : null;
            }

            case 'oauth':
            {
                $user = AuthenticatingUser::where([
                    'email' => $request->input('email')
                ])->first();

                if (! $user) {
                    return null;
                }

                $provider = Provider::where([
                    'user_id'          => $user->id,
                    'provider'         => $request->input('provider'),
                    'provider_user_id' => $request->input('user_id')
                ])->first();

                $methodName = "verify" . ucfirst($request->input('provider')) . "Token";

                $verification = $this->$methodName($request->input('token'), $request->input('user_id'));

                if (! $verification) {
                    return null;
                }

                return ($provider) ? $user : null;
            }
        }
    });
}

protected function verifyFacebookToken($token, $userId)
{
    $facebook = app(\SammyK\LaravelFacebookSdk\LaravelFacebookSdk::class);

    try
    {
        $response = $facebook->get('/me?fields=id,name', $token);

        $graphUser = $response->getGraphUser();

       return $graphUser->getId() === $userId;
    } catch (\Facebook\Exceptions\FacebookResponseException $e) {
        return false;
    }
}

0 个答案:

没有答案