Laravel 4 jenssegers-mongodb - how can I implement Auth with facebook

961 views Asked by At

I need help now I can't login with facebook let's see my code.

$code = Input::get('code');
if (strlen($code) == 0) 
    return Redirect::to('/')->with('message', 'There was an error communicating with Facebook');

$facebook = new Facebook(Config::get('facebook'));
$uid = $facebook->getUser();

if ($uid == 0) 
    return Redirect::to('/')->with('message', 'There was an error');

$me = $facebook->api('/me');

$existing_user = User::whereFBid($uid);

if (empty($existing_user))
{
    $user['name'] = $me['first_name'].' '.$me['last_name'];
    $user['email'] = $me['email'];
    $user['photo'] = 'https://graph.facebook.com/'.$me['username'].'/picture?type=large';

    $user['fbid'] = $uid;
    $user['username'] = $me['username'];
    $user['access_token'] = $facebook->getAccessToken();

    $rsUser = User::registerUser($user);
}
else
{
    $user = new User();
    $user->fbid = $uid;
    Auth::login($user);
}

return Redirect::to('/')->with('message', 'Logged in with Facebook');

My Route File

Route::get('/', function()
{
    $data = array();

    if (Auth::check())
    {
        $data = Auth::user();
        var_dump($data);exit;
    }
    else
    {
        echo 'auth check failed';exit;
    }

    return View::make('hello', array('data'=>$data));
});

My User models already added use Jenssegers\Mongodb\Model as Eloquent

Auth::login($user) it's pass but when my code redirect to '/' and Auth::check() it's not work is going to else condition. How can I solved that, anyone can help ? Thank you very much, sorry for my English.

1

There are 1 answers

2
Jaco On

In your else statement, you reinstantiate the User, but that doesn't make sense to me. Before your if statement, you are trying to find the User. Then there is your if statement, for when the user doesn't exist. Then there is your else statement, for when the user does exist. So you do not have to create a new User model:

else
{
    $user = new User();
    $user->fbid = $uid;
    Auth::login($user);
}

But you have to use the $existing_user variable to log in.

else
{
    Auth::login($existing_user);
}