laravel login with google account

家住魔仙堡 提交于 2020-01-04 09:55:03

问题


I am making an application and I want users to login with their google account. I have user oauth-4-laravel and I have this:

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);
        }
    }

After this i get successfully user info and can save user name, in my database. The problem is that after this I want to redirect user to home page and can't do this because with normal login i chec authentication:

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

and with google login i get onlu username , user id and email. How to login directly the user after google login?


回答1:


If you need to log an existing user instance into your application, you may simply call the login method with the instance:

$user = User::find(1);

Auth::login($user);

This is equivalent to logging in a user via credentials using the attempt method.

For further info see: http://laravel.com/docs/security#manually



来源:https://stackoverflow.com/questions/23802969/laravel-login-with-google-account

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!