laravel使用谷歌帐户登录

时间:2014-05-22 09:34:37

标签: laravel google-login

我正在申请,我希望用户使用他们的Google帐户登录。我有用户oauth-4-laravel,我有这个:

UserController.php

// get data from input
        $code = Input::get('code');

        // get google service
        $googleService = Artdarek\OAuth\Facade\OAuth::consumer("Google");

        if (!empty($code)) {

            // This was a callback request from google, get the token
            $token = $googleService->requestAccessToken($code);

            // Send a request with it
            $result = json_decode($googleService->request('https://www.googleapis.com/oauth2/v1/userinfo'), true);

            $user = DB::select('select id from users where email = ?', array($result['email']));

            if (empty($user)) {
                $data = new User;
                $data->Username = $result['name'];
                $data->email = $result['email'];
                $data->first_name = $result['given_name'];
                $data->last_name = $result['family_name'];
                $data->save();
            }
            if (Auth::attempt(array('email' => $result['email']))) {

            return Redirect::to('/');
            }  else {
            echo 'error';    
            }
        }
        // if not ask for permission first
        else {
            // get googleService authorization
            $url = $googleService->getAuthorizationUri();

            // return to facebook login url
            return Redirect::to((string) $url);
        }
    }

在此之后,我获得了成功的用户信息并可以在我的数据库中保存用户名。问题是,在此之后我想将用户重定向到主页并且无法执行此操作,因为正常登录i chec身份验证:

if (Auth::attempt(array('email' => Input::get('email'), 'password' => Input::get('password')))) {
            return Response::json(["redirect_to" => "/"]);

使用google登录我会获得用户名,用户ID和电子邮件。如何在google登录后直接登录用户?

1 个答案:

答案 0 :(得分:2)

如果您需要将现有用户实例记录到您的应用程序中,您可以使用实例调用login方法:

$user = User::find(1);

Auth::login($user);

这相当于使用企图方法通过凭据登录用户。

有关详细信息,请参阅:http://laravel.com/docs/security#manually

相关问题