Created
June 12, 2016 11:42
-
-
Save trinvh2/fdcae2a380d0f90f35fee6bfa98e1b37 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public function facebook(Request $request) | |
{ | |
$client = new \GuzzleHttp\Client(); | |
$params = [ | |
'code' => $request->input('code'), | |
'client_id' => $request->input('clientId'), | |
'redirect_uri' => $request->input('redirectUri'), | |
'client_secret' => config('app.facebook_secret'), | |
]; | |
// Step 1. Exchange authorization code for access token. | |
$accessTokenResponse = $client->request('GET', 'https://graph.facebook.com/v2.5/oauth/access_token', [ | |
'query' => $params, | |
]); | |
$accessToken = json_decode($accessTokenResponse->getBody(), true); | |
// Step 2. Retrieve profile information about the current user. | |
$fields = 'id,email,first_name,last_name,link,name'; | |
$profileResponse = $client->request('GET', 'https://graph.facebook.com/v2.5/me', [ | |
'query' => [ | |
'access_token' => $accessToken['access_token'], | |
'fields' => $fields, | |
], | |
]); | |
$profile = json_decode($profileResponse->getBody(), true); | |
if (empty($profile['email'])) { | |
$profile['email'] = $profile['id'] . '@facebook.com'; | |
} | |
// Step 3a. If user is already signed in then link accounts. | |
if ($request->header('Authorization')) { | |
$user = User::where('facebook', '=', $profile['id']); | |
/*if ($user->first()) { | |
return response()->json(['message' => 'There is already a Facebook account that belongs to you'], 409); | |
}*/ | |
$token = explode(' ', $request->header('Authorization'))[1]; | |
$payload = (array) JWT::decode($token, config('app.token_secret'), array('HS256')); | |
$user = User::find($payload['sub']); | |
$user->facebook = $profile['id']; | |
$user->email = $user->email ?: $profile['email']; | |
$user->name = $user->name ?: $profile['name']; | |
$user->save(); | |
return $this->loginSuccess($user); | |
} | |
// Step 3b. Create a new user account or return an existing one. | |
else { | |
$user = User::where('facebook', '=', $profile['id']); | |
if ($user->first()) { | |
return $this->loginSuccess($user->first()); | |
} | |
$user = new User; | |
$user->facebook = $profile['id']; | |
$user->email = $profile['email']; | |
$user->name = $profile['name']; | |
$user->save(); | |
return $this->loginSuccess($user); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment