Skip to content
Snippets Groups Projects
Commit 0894eff3 authored by Sonia Zorba's avatar Sonia Zorba Committed by zonia3000
Browse files

Refactoring

parent 4a5ba99f
No related branches found
No related tags found
No related merge requests found
Showing
with 472 additions and 970 deletions
<?php
/* ----------------------------------------------------------------------------
* INAF - National Institute for Astrophysics
* IRA - Radioastronomical Institute - Bologna
* OATS - Astronomical Observatory - Trieste
* ----------------------------------------------------------------------------
*
* Copyright (C) 2016 Istituto Nazionale di Astrofisica
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License Version 3 as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* This page MUST be protected by Shibboleth authentication
* On Apache httpd:
* AuthType shibboleth
* ShibRequestSetting requireSession 1
* Require valid-user
*/
include '../../include/init.php';
startSession();
if (isset($_SERVER['Shib-Session-ID'])) {
// Retrieving eduPersonPrincipalName (eppn)
$eppn = $_SERVER['eppn'];
// Search if the user is already registered into RAP using the eppn.
// The persistent id should be a more appropriate identifier, however at IA2
// we need to import all INAF user into RAP, even if they will never register,
// and in that case we know only their eppn.
$user = $userHandler->findUserByIdentity(RAP\Identity::EDU_GAIN, $eppn);
if ($user === null) {
// Creating a new user
$user = new RAP\User();
$identity = new RAP\Identity(RAP\Identity::EDU_GAIN);
$identity->email = $_SERVER['mail'];
$identity->name = $_SERVER['givenName'];
$identity->surname = $_SERVER['sn'];
$identity->typedId = $eppn;
$identity->eppn = $eppn;
//$_SERVER['Shib-Identity-Provider']
$user->addIdentity($identity);
$session->userToLogin = $user;
$session->save();
header('Location: ' . $BASE_PATH . '/tou-check');
die();
}
$auditLog->info("LOGIN,eduGAIN," . $user->id);
$callbackHandler->manageLoginRedirect($user, $session);
} else {
http_response_code(500);
die("Shib-Session-ID not found!");
}
<?php
/* ----------------------------------------------------------------------------
* INAF - National Institute for Astrophysics
* IRA - Radioastronomical Institute - Bologna
* OATS - Astronomical Observatory - Trieste
* ----------------------------------------------------------------------------
*
* Copyright (C) 2016 Istituto Nazionale di Astrofisica
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License Version 3 as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* This page uses the Facebook API for generating the redirect URL to use for Facebook login */
include '../../include/init.php';
startSession();
// Retrieve Facebook configuration
$Facebook = $AUTHENTICATION_METHODS['Facebook'];
$fb = new Facebook\Facebook([
'app_id' => $Facebook['id'],
'app_secret' => $Facebook['secret'],
'default_graph_version' => $Facebook['version'],
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email']; // Optional permissions: we need user email
$loginUrl = $helper->getLoginUrl($Facebook['callback'], $permissions);
header("Location: $loginUrl");
?>
<?php
/* ----------------------------------------------------------------------------
* INAF - National Institute for Astrophysics
* IRA - Radioastronomical Institute - Bologna
* OATS - Astronomical Observatory - Trieste
* ----------------------------------------------------------------------------
*
* Copyright (C) 2016 Istituto Nazionale di Astrofisica
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License Version 3 as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Facebook callback page */
include '../../include/init.php';
startSession();
// Retrieve Facebook configuration
$Facebook = $AUTHENTICATION_METHODS['Facebook'];
$fb = new Facebook\Facebook([
'app_id' => $Facebook['id'],
'app_secret' => $Facebook['secret'],
'default_graph_version' => $Facebook['version'],
]);
$helper = $fb->getRedirectLoginHelper();
if (isset($_GET['state'])) {
$helper->getPersistentDataHandler()->set('state', $_GET['state']);
}
try {
// obtaining current URL without query string
$url = "https://$_SERVER[HTTP_HOST]" . strtok($_SERVER["REQUEST_URI"], '?');
$accessToken = $helper->getAccessToken($url);
} catch (Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
http_response_code(500);
die('Graph returned an error: ' . $e->getMessage());
} catch (Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
http_response_code(500);
die('Facebook SDK returned an error: ' . $e->getMessage());
}
if (!isset($accessToken)) {
if ($helper->getError()) {
$errorMessage = "Error: " . $helper->getError() . "<br>";
$errorMessage = $errorMessage . "Error Code: " . $helper->getErrorCode() . "<br>";
$errorMessage = $errorMessage . "Error Reason: " . $helper->getErrorReason() . "<br>";
$errorMessage = $errorMessage . "Error Description: " . $helper->getErrorDescription();
} else {
$errorMessage = "Bad request";
}
http_response_code(500);
die($errorMessage);
}
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get('/me?fields=id,first_name,last_name,email', $accessToken);
} catch (Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch (Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$_SESSION['fb_access_token'] = (string) $accessToken;
$fbUser = $response->getGraphUser();
$typedId = $fbUser["id"];
// Search if the user is already registered into RAP using the Facebook ID.
$user = $userHandler->findUserByIdentity(RAP\Identity::FACEBOOK, $typedId);
if ($user === null) {
// Create new user
$user = new RAP\User();
$identity = new RAP\Identity(RAP\Identity::FACEBOOK);
$identity->email = $fbUser["email"];
$identity->name = $fbUser["first_name"];
$identity->surname = $fbUser["last_name"];
$identity->typedId = $typedId;
$user->addIdentity($identity);
$session->userToLogin = $user;
$session->save();
header('Location: ' . $BASE_PATH . '/tou-check');
die();
}
$auditLog->info("LOGIN,Facebook," . $user->id);
$callbackHandler->manageLoginRedirect($user, $session);
?>
<?php
/* ----------------------------------------------------------------------------
* INAF - National Institute for Astrophysics
* IRA - Radioastronomical Institute - Bologna
* OATS - Astronomical Observatory - Trieste
* ----------------------------------------------------------------------------
*
* Copyright (C) 2016 Istituto Nazionale di Astrofisica
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License Version 3 as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Google redirect and callback page */
include '../../include/init.php';
startSession();
// Retrieve Google configuration
$Google = $AUTHENTICATION_METHODS['Google'];
$client = new Google_Client(array(
'client_id' => $Google['id'],
'client_secret' => $Google['secret'],
'redirect_uri' => $Google['callback'],
));
// Ask permission to obtain user email and profile information
$client->setScopes(array(Google_Service_People::USERINFO_EMAIL, Google_Service_People::USERINFO_PROFILE));
if (isset($_REQUEST['logout'])) {
// Reset the access token stored into the session
unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
// An access token has been returned from the auth URL.
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
}
//if (isset($_SESSION['access_token'])) {
// $client->setAccessToken($_SESSION['access_token']);
//}
if ($client->getAccessToken()) {
// Query web service for retrieving user information
$service = new Google_Service_People($client);
try {
$res = $service->people->get('people/me', array('requestMask.includeField' => 'person.names,person.email_addresses'));
} catch (Google_Service_Exception $e) {
echo '<p>' . json_encode($e->getErrors()) . '</p>';
$thisPage = $PROTOCOL . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
echo '<p><a href="' . $thisPage . '?logout">Click here to unset the access token</a></p>';
}
$name = $res->getNames()[0]->getGivenName();
$surname = $res->getNames()[0]->getFamilyName();
$emailAddresses = [];
foreach ($res->getEmailAddresses() as $addr) {
array_push($emailAddresses, $addr->value);
}
$typedId = explode('/', $res->getResourceName())[1];
// Search if the user is already registered into RAP using the Google ID.
$user = $userHandler->findUserByIdentity(RAP\Identity::GOOGLE, $typedId);
if ($user === null) {
// Create new user
$user = new RAP\User();
$identity = new RAP\Identity(RAP\Identity::GOOGLE);
$identity->email = $emailAddresses[0];
$identity->name = $name;
$identity->surname = $surname;
$identity->typedId = $typedId;
$user->addIdentity($identity);
$session->userToLogin = $user;
$session->save();
header('Location: ' . $BASE_PATH . '/tou-check');
die();
}
$auditLog->info("LOGIN,Google," . $user->id);
$callbackHandler->manageLoginRedirect($user, $session);
die();
} else {
// Redirect to Google authorization URL for obtaining an access token
$authUrl = $client->createAuthUrl();
header('Location: ' . $authUrl);
die();
}
?>
<?php
/* ----------------------------------------------------------------------------
* INAF - National Institute for Astrophysics
* IRA - Radioastronomical Institute - Bologna
* OATS - Astronomical Observatory - Trieste
* ----------------------------------------------------------------------------
*
* Copyright (C) 2016 Istituto Nazionale di Astrofisica
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License Version 3 as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* This page redirects to LinkedIn login page */
include '../../include/init.php';
startSession();
// Retrieve LinkedIn configuration
$LinkedIn = $AUTHENTICATION_METHODS['LinkedIn'];
$url = "https://www.linkedin.com/oauth/v2/authorization?response_type=code";
$url .= "&client_id=" . $LinkedIn['id'];
$url .= "&redirect_uri=" . $LinkedIn['callback'];
$url .= "&state=789654123";
$url .= "&scope=r_basicprofile r_emailaddress";
header("Location: $url");
?>
<?php
/* ----------------------------------------------------------------------------
* INAF - National Institute for Astrophysics
* IRA - Radioastronomical Institute - Bologna
* OATS - Astronomical Observatory - Trieste
* ----------------------------------------------------------------------------
*
* Copyright (C) 2016 Istituto Nazionale di Astrofisica
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License Version 3 as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* LinkedIn callback page. Curl is used, because LinkedIn doesn't provide official PHP API. */
include '../../include/init.php';
startSession();
// Retrieve LinkedIn configuration
$LinkedIn = $AUTHENTICATION_METHODS['LinkedIn'];
if (!isset($_REQUEST['code'])) {
die("Unable to get LinkedIn client code");
}
//create array of data to be posted to get AccessToken
$post_data = array(
'grant_type' => "authorization_code",
'code' => $_REQUEST['code'],
'redirect_uri' => $LinkedIn['callback'],
'client_id' => $LinkedIn['id'],
'client_secret' => $LinkedIn['secret']);
//traverse array and prepare data for posting (key1=value1)
foreach ($post_data as $key => $value) {
$post_items[] = $key . '=' . $value;
}
//create the final string to be posted
$post_string = implode('&', $post_items);
//create cURL connection
$conn1 = curl_init('https://www.linkedin.com/oauth/v2/accessToken');
//set options
curl_setopt($conn1, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($conn1, CURLOPT_RETURNTRANSFER, true);
curl_setopt($conn1, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($conn1, CURLOPT_FOLLOWLOCATION, 1);
//set data to be posted
curl_setopt($conn1, CURLOPT_POSTFIELDS, $post_string);
//perform our request
$result1 = curl_exec($conn1);
$info1 = curl_getinfo($conn1);
if ($info1['http_code'] === 200) {
$my_token = json_decode($result1, TRUE);
$access_token = $my_token['access_token'];
$expires_in = $my_token['expires_in'];
curl_close($conn1);
} else {
//show information regarding the error
$errorMessage = "Error: LinkedIn server response code: " . $info1['http_code'] . " - ";
$errorMessage .= curl_error($conn1);
curl_close($conn1);
http_response_code(500);
die($errorMessage);
}
// Call to API
$conn2 = curl_init();
curl_setopt($conn2, CURLOPT_URL, "https://api.linkedin.com/v1/people/~:(first-name,last-name,email-address,id)?format=json");
curl_setopt($conn2, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer ' . $access_token
));
curl_setopt($conn2, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($conn2);
$info2 = curl_getinfo($conn2);
if ($info2['http_code'] === 200) {
$data = json_decode($result, TRUE);
curl_close($conn2);
if (isset($data['errorCode'])) {
$errorMessage = $data['message'];
die($errorMessage);
}
$typedId = $data['id'];
// Search if the user is already registered into RAP using the LinkedIn ID.
$user = $userHandler->findUserByIdentity(RAP\Identity::LINKEDIN, $typedId);
if ($user === null) {
// Create new user
$user = new RAP\User();
$identity = new RAP\Identity(RAP\Identity::LINKEDIN);
$identity->email = $data['emailAddress'];
$identity->name = $data['firstName'];
$identity->surname = $data['lastName'];
$identity->typedId = $typedId;
$user->addIdentity($identity);
$session->userToLogin = $user;
$session->save();
header('Location: ' . $BASE_PATH . '/tou-check');
die();
}
$auditLog->info("LOGIN,LinkedIn," . $user->id);
$callbackHandler->manageLoginRedirect($user, $session);
} else {
//show information regarding the error
$errorMessage = "Error: LinkedIn server response code: " . $info2['http_code'] . " - ";
$errorMessage = $errorMessage . curl_error($conn2);
curl_close($conn2);
die($errorMessage);
}
?>
<?php
/* ----------------------------------------------------------------------------
* INAF - National Institute for Astrophysics
* IRA - Radioastronomical Institute - Bologna
* OATS - Astronomical Observatory - Trieste
* ----------------------------------------------------------------------------
*
* Copyright (C) 2016 Istituto Nazionale di Astrofisica
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License Version 3 as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* This page must be protected by client certificate authentication
* On Apache httpd:
* SSLVerifyClient require
* SSLVerifyDepth 10
* SSLOptions +ExportCertData
*/
include '../../include/init.php';
startSession();
if (isset($_SERVER['SSL_CLIENT_VERIFY']) && isset($_SERVER['SSL_CLIENT_V_REMAIN']) &&
$_SERVER['SSL_CLIENT_VERIFY'] === 'SUCCESS' && $_SERVER['SSL_CLIENT_V_REMAIN'] > 0) {
$x509Data = RAP\X509Data::parse($_SERVER);
$user = $userHandler->findUserByIdentity(RAP\Identity::X509, $x509Data->serialNumber);
if ($user === null) {
/**
* We want to extract name and surname from the X.509 certificate, however X.509
* puts name and surname together (inside the CN field).
* If name and surname are single words it is possible to retrieve them splitting
* on the space character, otherwise the user has to choose the correct combination.
* In that case partial X.509 data is temporarily stored into the user session and
* the page views/x509-name-surname.php is shown to the user before completing the
* registration, in order to allow him/her selecting the correct name and surname.
*/
if ($x509Data->name === null) {
$session->x509DataToRegister = $x509Data;
$session->save();
header('Location: ' . $BASE_PATH . '/x509-name-surname');
} else {
$session->userToLogin = $x509Data->toUser();
$session->save();
header('Location: ' . $BASE_PATH . '/tou-check');
}
die();
} else {
$auditLog->info("LOGIN,X.509," . $user->id);
$callbackHandler->manageLoginRedirect($user, $session);
}
} else {
http_response_code(500);
die("Unable to verify client certificate");
}
<?php
/* ----------------------------------------------------------------------------
* INAF - National Institute for Astrophysics
* IRA - Radioastronomical Institute - Bologna
* OATS - Astronomical Observatory - Trieste
* ----------------------------------------------------------------------------
*
* Copyright (C) 2016 Istituto Nazionale di Astrofisica
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License Version 3 as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
namespace RAP;
/**
* Manage callback URL validation and redirection
*/
class CallbackHandler {
private $locator;
public function __construct(Locator $locator) {
$this->locator = $locator;
}
/**
* If a callback URL is not in the configured list we should return null.
*/
public function filterCallbackURL($callbackURL) {
foreach ($this->callbacks as $callback) {
if ($callback['url'] === $callbackURL) {
return $callbackURL;
}
}
return null;
}
/**
* Each callback has a title and a logo in order to avoid confusion in users
* and show in which application they are logging in using RAP.
* @param type $callbackURL
* @return type the callback title or null if the callback URL is not listed
* in configuration file or it doesn't have a title.
*/
public function getCallbackTitle($callbackURL) {
foreach ($this->callbacks as $callback) {
if ($callback['url'] === $callbackURL) {
return $callback['title'];
}
}
return null;
}
/**
* Each callback has a title and a logo in order to avoid confusion in users
* and show in which application they are logging in using RAP.
* @param type $callbackURL
* @return type the callback logo or null if the callback URL is not listed
* in configuration file or it doesn't have a logo.
*/
public function getCallbackLogo($callbackURL) {
foreach ($this->callbacks as $callback) {
if ($callback['url'] === $callbackURL) {
if (array_key_exists('logo', $callback)) {
return $callback['logo'];
} else {
return null;
}
}
}
return null;
}
public function manageLoginRedirect(User $user, SessionData $session) {
if($session->getOAuth2Data() !== null) {
$session->user = $user;
$session->save();
$redirectUrl = $this->locator->getOAuth2RequestHandler()->getCodeResponseUrl();
$session->setOAuth2Data(null);
header('Location: ' . $redirectUrl);
die();
}
if ($session->getCallbackURL() === null) {
http_response_code(401);
die("Unauthorized callback URL");
}
if ($session->getCallbackURL() === $this->basePath . '/') {
// Login in session
$session->user = $user;
$session->save();
// Return to index
header('Location: ' . $this->basePath);
die();
} else {
// External login using token
header('Location: ' . $this->getLoginWithTokenURL($user->id, $session->getCallbackURL()));
die();
}
}
public function getLoginWithTokenURL($userId, $callbackURL) {
$token = Util::createNewToken();
$this->dao->createLoginToken($token, $userId);
return $callbackURL . '?token=' . $token;
}
}
...@@ -23,7 +23,7 @@ class IdTokenBuilder { ...@@ -23,7 +23,7 @@ class IdTokenBuilder {
private function createPayloadArray(AccessToken $accessToken) { private function createPayloadArray(AccessToken $accessToken) {
$user = $this->locator->getDAO()->findUserById($accessToken->userId); $user = $this->locator->getUserDAO()->findUserById($accessToken->userId);
$payloadArr = array( $payloadArr = array(
'iss' => $this->locator->config->jwtIssuer, 'iss' => $this->locator->config->jwtIssuer,
......
...@@ -32,11 +32,21 @@ class Locator { ...@@ -32,11 +32,21 @@ class Locator {
return $this->getProtocol() . $_SERVER['HTTP_HOST'] . $this->config->contextRoot; return $this->getProtocol() . $_SERVER['HTTP_HOST'] . $this->config->contextRoot;
} }
public function getDAO(): DAO { public function getUserDAO(): UserDAO {
$databaseConfig = $this->config->databaseConfig; $databaseConfig = $this->config->databaseConfig;
switch ($databaseConfig->dbtype) { switch ($databaseConfig->dbtype) {
case 'MySQL': case 'MySQL':
return new MySQLDAO($this); return new MySQLUserDAO($this);
default:
throw new \Exception($databaseConfig->dbtype . ' not supported yet');
}
}
public function getOAuth2ClientDAO(): OAuth2ClientDAO {
$databaseConfig = $this->config->databaseConfig;
switch ($databaseConfig->dbtype) {
case 'MySQL':
return new MySQLOAuth2ClientDAO($this);
default: default:
throw new \Exception($databaseConfig->dbtype . ' not supported yet'); throw new \Exception($databaseConfig->dbtype . ' not supported yet');
} }
...@@ -67,7 +77,7 @@ class Locator { ...@@ -67,7 +77,7 @@ class Locator {
} }
public function getUserHandler(): UserHandler { public function getUserHandler(): UserHandler {
return new UserHandler($this->getDAO()); return new UserHandler($this);
} }
public function getMailSender(): MailSender { public function getMailSender(): MailSender {
......
...@@ -20,7 +20,7 @@ class OAuth2RequestHandler { ...@@ -20,7 +20,7 @@ class OAuth2RequestHandler {
throw new BadRequestException("Redirect URI is required"); throw new BadRequestException("Redirect URI is required");
} }
$client = $this->locator->getDAO()->getOAuth2ClientByClientId($params['client_id']); $client = $this->locator->getOAuth2ClientDAO()->getOAuth2ClientByClientId($params['client_id']);
if ($client === null) { if ($client === null) {
throw new BadRequestException("Invalid client id: " . $params['client_id']); throw new BadRequestException("Invalid client id: " . $params['client_id']);
} }
...@@ -60,7 +60,7 @@ class OAuth2RequestHandler { ...@@ -60,7 +60,7 @@ class OAuth2RequestHandler {
$accessToken = new \RAP\AccessToken(); $accessToken = new \RAP\AccessToken();
$accessToken->code = base64_encode(bin2hex(openssl_random_pseudo_bytes(64))); $accessToken->code = base64_encode(bin2hex(openssl_random_pseudo_bytes(64)));
$accessToken->token = base64_encode(bin2hex(openssl_random_pseudo_bytes(128))); $accessToken->token = base64_encode(bin2hex(openssl_random_pseudo_bytes(128)));
$accessToken->userId = $session->user->id; $accessToken->userId = $session->getUser()->id;
$accessToken->clientId = $session->getOAuth2Data()->clientId; $accessToken->clientId = $session->getOAuth2Data()->clientId;
$accessToken->redirectUri = $session->getOAuth2Data()->redirectUrl; $accessToken->redirectUri = $session->getOAuth2Data()->redirectUrl;
$accessToken->scope = $session->getOAuth2Data()->scope; $accessToken->scope = $session->getOAuth2Data()->scope;
...@@ -128,7 +128,7 @@ class OAuth2RequestHandler { ...@@ -128,7 +128,7 @@ class OAuth2RequestHandler {
} }
$accessToken = $this->locator->getAccessTokenDAO()->getAccessToken($token); $accessToken = $this->locator->getAccessTokenDAO()->getAccessToken($token);
$user = $this->locator->getDAO()->findUserById($accessToken->userId); $user = $this->locator->getUserDAO()->findUserById($accessToken->userId);
$result = []; $result = [];
$result['exp'] = $this->getExpiresIn($accessToken); $result['exp'] = $this->getExpiresIn($accessToken);
......
...@@ -31,8 +31,8 @@ class UserHandler { ...@@ -31,8 +31,8 @@ class UserHandler {
private $dao; private $dao;
public function __construct(DAO $dao) { public function __construct(Locator $locator) {
$this->dao = $dao; $this->dao = $locator->getUserDAO();
} }
/** /**
......
...@@ -203,9 +203,7 @@ class X509Data { ...@@ -203,9 +203,7 @@ class X509Data {
return $parsedData; return $parsedData;
} }
public function toUser() { public function toIdentity() {
$user = new User();
$identity = new Identity(Identity::X509); $identity = new Identity(Identity::X509);
$identity->email = $this->email; $identity->email = $this->email;
...@@ -214,9 +212,7 @@ class X509Data { ...@@ -214,9 +212,7 @@ class X509Data {
$identity->typedId = $this->serialNumber; $identity->typedId = $this->serialNumber;
$identity->institution = $this->institution; $identity->institution = $this->institution;
$user->addIdentity($identity); return $identity;
return $user;
} }
} }
<?php
namespace RAP;
/**
* CRUD methods for OAuth2Clients (used by admin interface).
*/
interface OAuth2ClientDAO {
function getOAuth2Clients(): array;
function createOAuth2Client($client): OAuth2Client;
function updateOAuth2Client($client): OAuth2Client;
function deleteOAuth2Client($clientId);
/**
* Retrieve the client from the configured client id (the one associated to
* the secret, not the database id).
*/
function getOAuth2ClientByClientId($clientId): ?OAuth2Client;
}
...@@ -24,11 +24,7 @@ ...@@ -24,11 +24,7 @@
namespace RAP; namespace RAP;
/** interface UserDAO {
* Data Access Object interface for accessing the RAP database.
* Current implementations: RAP\MySQLDAO
*/
interface DAO {
/** /**
* Create a new identity. * Create a new identity.
...@@ -98,20 +94,4 @@ interface DAO { ...@@ -98,20 +94,4 @@ interface DAO {
*/ */
function deleteJoinRequest($token); function deleteJoinRequest($token);
/**
* CRUD methods for OAuth2Clients (used by admin interface).
*/
function getOAuth2Clients();
function createOAuth2Client($client): OAuth2Client;
function updateOAuth2Client($client): OAuth2Client;
function deleteOAuth2Client($clientId);
/**
* Retrieve the client from the configured client id (the one associated to
* the secret, not the database id).
*/
function getOAuth2ClientByClientId($clientId): ?OAuth2Client;
} }
<?php
namespace RAP;
class MySQLOAuth2ClientDAO extends BaseMySQLDAO implements OAuth2ClientDAO {
public function __construct($config) {
parent::__construct($config);
}
function getOAuth2Clients(): array {
$dbh = $this->getDBHandler();
// Load clients info
$queryClient = "SELECT id, title, icon, client, secret, redirect_url, scope FROM oauth2_client";
$stmtClients = $dbh->prepare($queryClient);
$stmtClients->execute();
$clientsMap = [];
foreach ($stmtClients->fetchAll() as $row) {
$client = new OAuth2Client();
$client->id = $row['id'];
$client->title = $row['title'];
$client->icon = $row['icon'];
$client->client = $row['client'];
$client->secret = $row['secret'];
$client->redirectUrl = $row['redirect_url'];
$client->scope = $row['scope'];
$clientsMap[$client->id] = $client;
}
// Load authentication methods info
$queryAuthNMethods = "SELECT client_id, auth_method FROM oauth2_client_auth_methods";
$stmtAuthNMethods = $dbh->prepare($queryAuthNMethods);
$stmtAuthNMethods->execute();
foreach ($stmtAuthNMethods->fetchAll() as $row) {
$id = $row['client_id'];
array_push($clientsMap[$id]->authMethods, $row['auth_method']);
}
$clients = [];
foreach ($clientsMap as $id => $client) {
array_push($clients, $client);
}
return $clients;
}
function createOAuth2Client($client): OAuth2Client {
$dbh = $this->getDBHandler();
try {
$dbh->beginTransaction();
$stmt = $dbh->prepare("INSERT INTO `oauth2_client`(`title`, `icon`, `client`, `secret`, `redirect_url`, `scope`)"
. " VALUES(:title, :icon, :client, :secret, :redirect_url, :scope)");
$stmt->bindParam(':title', $client->title);
$stmt->bindParam(':icon', $client->icon);
$stmt->bindParam(':client', $client->client);
$stmt->bindParam(':secret', $client->secret);
$stmt->bindParam(':redirect_url', $client->redirectUrl);
$stmt->bindParam(':scope', $client->scope);
$stmt->execute();
$client->id = $dbh->lastInsertId();
foreach ($client->authMethods as $method) {
$stmt = $dbh->prepare("INSERT INTO `oauth2_client_auth_methods`(`client_id`, `auth_method`)"
. " VALUES(:client_id, :auth_method)");
$stmt->bindParam(':client_id', $client->id);
$stmt->bindParam(':auth_method', $method);
$stmt->execute();
}
$dbh->commit();
} catch (Exception $ex) {
$dbh->rollBack();
throw $ex;
}
return $client;
}
function updateOAuth2Client($client): OAuth2Client {
$dbh = $this->getDBHandler();
try {
$dbh->beginTransaction();
$stmt = $dbh->prepare("UPDATE `oauth2_client` SET `title` = :title, `icon` = :icon, "
. " `client` = :client, `secret` = :secret, `redirect_url` = :redirect_url, `scope` = :scope "
. " WHERE id = :id");
$stmt->bindParam(':title', $client->title);
$stmt->bindParam(':icon', $client->icon);
$stmt->bindParam(':client', $client->client);
$stmt->bindParam(':secret', $client->secret);
$stmt->bindParam(':redirect_url', $client->redirectUrl);
$stmt->bindParam(':scope', $client->scope);
$stmt->bindParam(':id', $client->id);
$stmt->execute();
// Delete old authentication methods
$stmt = $dbh->prepare("DELETE FROM oauth2_client_auth_methods WHERE client_id = :id");
$stmt->bindParam(':id', $client->id);
$stmt->execute();
// Re-add authentication methods
foreach ($client->authMethods as $method) {
$stmt = $dbh->prepare("INSERT INTO `oauth2_client_auth_methods`(`client_id`, `auth_method`)"
. " VALUES(:client_id, :auth_method)");
$stmt->bindParam(':client_id', $client->id);
$stmt->bindParam(':auth_method', $method);
$stmt->execute();
}
$dbh->commit();
} catch (Exception $ex) {
$dbh->rollBack();
throw $ex;
}
return $client;
}
function deleteOAuth2Client($clientId) {
$dbh = $this->getDBHandler();
try {
$dbh->beginTransaction();
$stmt = $dbh->prepare("DELETE FROM `oauth2_client_auth_methods` WHERE client_id = :id");
$stmt->bindParam(':id', $clientId);
$stmt->execute();
$stmt = $dbh->prepare("DELETE FROM `oauth2_client` WHERE id = :id");
$stmt->bindParam(':id', $clientId);
$stmt->execute();
$dbh->commit();
} catch (Exception $ex) {
$dbh->rollBack();
throw $ex;
}
}
function getOAuth2ClientByClientId($clientId): ?OAuth2Client {
$dbh = $this->getDBHandler();
// Load clients info
$queryClient = "SELECT id, title, icon, client, secret, redirect_url, scope FROM oauth2_client WHERE client = :client";
$stmtClient = $dbh->prepare($queryClient);
$stmtClient->bindParam(':client', $clientId);
$stmtClient->execute();
$result = $stmtClient->fetchAll();
if (count($result) === 0) {
return null;
}
if (count($result) > 1) {
throw new Exception("Found multiple clients associated to the same client id!");
}
$row = $result[0];
$client = new OAuth2Client();
$client->id = $row['id'];
$client->title = $row['title'];
$client->icon = $row['icon'];
$client->client = $row['client'];
$client->secret = $row['secret'];
$client->redirectUrl = $row['redirect_url'];
$client->scope = $row['scope'];
// Load authentication methods info
$queryAuthNMethods = "SELECT auth_method FROM oauth2_client_auth_methods WHERE client_id = :id";
$stmtAuthNMethods = $dbh->prepare($queryAuthNMethods);
$stmtAuthNMethods->bindParam(':id', $client->id);
$stmtAuthNMethods->execute();
foreach ($stmtAuthNMethods->fetchAll() as $row) {
array_push($client->authMethods, $row['auth_method']);
}
return $client;
}
}
...@@ -27,7 +27,7 @@ namespace RAP; ...@@ -27,7 +27,7 @@ namespace RAP;
/** /**
* MySQL implementation of the DAO interface. See comments on the DAO interface. * MySQL implementation of the DAO interface. See comments on the DAO interface.
*/ */
class MySQLDAO extends BaseMySQLDAO implements DAO { class MySQLUserDAO extends BaseMySQLDAO implements UserDAO {
public function __construct(Locator $locator) { public function __construct(Locator $locator) {
parent::__construct($locator); parent::__construct($locator);
...@@ -277,193 +277,4 @@ class MySQLDAO extends BaseMySQLDAO implements DAO { ...@@ -277,193 +277,4 @@ class MySQLDAO extends BaseMySQLDAO implements DAO {
$stmt->execute(); $stmt->execute();
} }
function getOAuth2Clients() {
$dbh = $this->getDBHandler();
// Load clients info
$queryClient = "SELECT id, title, icon, client, secret, redirect_url, scope FROM oauth2_client";
$stmtClients = $dbh->prepare($queryClient);
$stmtClients->execute();
$clientsMap = [];
foreach ($stmtClients->fetchAll() as $row) {
$client = new OAuth2Client();
$client->id = $row['id'];
$client->title = $row['title'];
$client->icon = $row['icon'];
$client->client = $row['client'];
$client->secret = $row['secret'];
$client->redirectUrl = $row['redirect_url'];
$client->scope = $row['scope'];
$clientsMap[$client->id] = $client;
}
// Load authentication methods info
$queryAuthNMethods = "SELECT client_id, auth_method FROM oauth2_client_auth_methods";
$stmtAuthNMethods = $dbh->prepare($queryAuthNMethods);
$stmtAuthNMethods->execute();
foreach ($stmtAuthNMethods->fetchAll() as $row) {
$id = $row['client_id'];
array_push($clientsMap[$id]->authMethods, $row['auth_method']);
}
$clients = [];
foreach ($clientsMap as $id => $client) {
array_push($clients, $client);
}
return $clients;
}
function createOAuth2Client($client): OAuth2Client {
$dbh = $this->getDBHandler();
try {
$dbh->beginTransaction();
$stmt = $dbh->prepare("INSERT INTO `oauth2_client`(`title`, `icon`, `client`, `secret`, `redirect_url`, `scope`)"
. " VALUES(:title, :icon, :client, :secret, :redirect_url, :scope)");
$stmt->bindParam(':title', $client->title);
$stmt->bindParam(':icon', $client->icon);
$stmt->bindParam(':client', $client->client);
$stmt->bindParam(':secret', $client->secret);
$stmt->bindParam(':redirect_url', $client->redirectUrl);
$stmt->bindParam(':scope', $client->scope);
$stmt->execute();
$client->id = $dbh->lastInsertId();
foreach ($client->authMethods as $method) {
$stmt = $dbh->prepare("INSERT INTO `oauth2_client_auth_methods`(`client_id`, `auth_method`)"
. " VALUES(:client_id, :auth_method)");
$stmt->bindParam(':client_id', $client->id);
$stmt->bindParam(':auth_method', $method);
$stmt->execute();
}
$dbh->commit();
} catch (Exception $ex) {
$dbh->rollBack();
throw $ex;
}
return $client;
}
function updateOAuth2Client($client): OAuth2Client {
$dbh = $this->getDBHandler();
try {
$dbh->beginTransaction();
$stmt = $dbh->prepare("UPDATE `oauth2_client` SET `title` = :title, `icon` = :icon, "
. " `client` = :client, `secret` = :secret, `redirect_url` = :redirect_url, `scope` = :scope "
. " WHERE id = :id");
$stmt->bindParam(':title', $client->title);
$stmt->bindParam(':icon', $client->icon);
$stmt->bindParam(':client', $client->client);
$stmt->bindParam(':secret', $client->secret);
$stmt->bindParam(':redirect_url', $client->redirectUrl);
$stmt->bindParam(':scope', $client->scope);
$stmt->bindParam(':id', $client->id);
$stmt->execute();
// Delete old authentication methods
$stmt = $dbh->prepare("DELETE FROM oauth2_client_auth_methods WHERE client_id = :id");
$stmt->bindParam(':id', $client->id);
$stmt->execute();
// Re-add authentication methods
foreach ($client->authMethods as $method) {
$stmt = $dbh->prepare("INSERT INTO `oauth2_client_auth_methods`(`client_id`, `auth_method`)"
. " VALUES(:client_id, :auth_method)");
$stmt->bindParam(':client_id', $client->id);
$stmt->bindParam(':auth_method', $method);
$stmt->execute();
}
$dbh->commit();
} catch (Exception $ex) {
$dbh->rollBack();
throw $ex;
}
return $client;
}
function deleteOAuth2Client($clientId) {
$dbh = $this->getDBHandler();
try {
$dbh->beginTransaction();
$stmt = $dbh->prepare("DELETE FROM `oauth2_client_auth_methods` WHERE client_id = :id");
$stmt->bindParam(':id', $clientId);
$stmt->execute();
$stmt = $dbh->prepare("DELETE FROM `oauth2_client` WHERE id = :id");
$stmt->bindParam(':id', $clientId);
$stmt->execute();
$dbh->commit();
} catch (Exception $ex) {
$dbh->rollBack();
throw $ex;
}
}
function getOAuth2ClientByClientId($clientId): ?OAuth2Client {
$dbh = $this->getDBHandler();
// Load clients info
$queryClient = "SELECT id, title, icon, client, secret, redirect_url, scope FROM oauth2_client WHERE client = :client";
$stmtClient = $dbh->prepare($queryClient);
$stmtClient->bindParam(':client', $clientId);
$stmtClient->execute();
$result = $stmtClient->fetchAll();
if (count($result) === 0) {
return null;
}
if (count($result) > 1) {
throw new Exception("Found multiple clients associated to the same client id!");
}
$row = $result[0];
$client = new OAuth2Client();
$client->id = $row['id'];
$client->title = $row['title'];
$client->icon = $row['icon'];
$client->client = $row['client'];
$client->secret = $row['secret'];
$client->redirectUrl = $row['redirect_url'];
$client->scope = $row['scope'];
// Load authentication methods info
$queryAuthNMethods = "SELECT auth_method FROM oauth2_client_auth_methods WHERE client_id = :id";
$stmtAuthNMethods = $dbh->prepare($queryAuthNMethods);
$stmtAuthNMethods->bindParam(':id', $client->id);
$stmtAuthNMethods->execute();
foreach ($stmtAuthNMethods->fetchAll() as $row) {
array_push($client->authMethods, $row['auth_method']);
}
return $client;
}
} }
<?php
namespace RAP;
class FacebookLogin extends LoginHandler {
public function __construct(Locator $locator) {
parent::__construct($locator, Identity::FACEBOOK);
}
public function login() {
// Retrieve Facebook configuration
$Facebook = $this->locator->config->authenticationMethods->Facebook;
$fb = new \Facebook\Facebook([
'app_id' => $Facebook->id,
'app_secret' => $Facebook->secret,
'default_graph_version' => $Facebook->version,
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email']; // Optional permissions: we need user email
$loginUrl = $helper->getLoginUrl($Facebook->callback, $permissions);
header("Location: $loginUrl");
}
public function retrieveToken() {
// Retrieve Facebook configuration
$Facebook = $this->locator->config->authenticationMethods->Facebook;
$fb = new \Facebook\Facebook([
'app_id' => $Facebook->id,
'app_secret' => $Facebook->secret,
'default_graph_version' => $Facebook->version,
]);
$helper = $fb->getRedirectLoginHelper();
if (isset($_GET['state'])) {
$helper->getPersistentDataHandler()->set('state', $_GET['state']);
}
try {
// obtaining current URL without query string
$url = "https://$_SERVER[HTTP_HOST]" . strtok($_SERVER["REQUEST_URI"], '?');
$accessToken = $helper->getAccessToken($url);
} catch (Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
http_response_code(500);
die('Graph returned an error: ' . $e->getMessage());
} catch (Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
http_response_code(500);
die('Facebook SDK returned an error: ' . $e->getMessage());
}
if (!isset($accessToken)) {
if ($helper->getError()) {
$errorMessage = "Error: " . $helper->getError() . "<br>";
$errorMessage = $errorMessage . "Error Code: " . $helper->getErrorCode() . "<br>";
$errorMessage = $errorMessage . "Error Reason: " . $helper->getErrorReason() . "<br>";
$errorMessage = $errorMessage . "Error Description: " . $helper->getErrorDescription();
} else {
$errorMessage = "Bad request";
}
http_response_code(500);
die($errorMessage);
}
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get('/me?fields=id,first_name,last_name,email', $accessToken);
} catch (Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch (Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$_SESSION['fb_access_token'] = (string) $accessToken;
$fbUser = $response->getGraphUser();
$typedId = $fbUser["id"];
return $this->onIdentityDataReceived($typedId, function($identity) use($fbUser) {
$identity->email = $fbUser["email"];
$identity->name = $fbUser["first_name"];
$identity->surname = $fbUser["last_name"];
});
}
}
...@@ -2,15 +2,13 @@ ...@@ -2,15 +2,13 @@
namespace RAP; namespace RAP;
class GoogleLogin { class GoogleLogin extends LoginHandler {
protected $locator;
public function __construct(Locator $locator) { public function __construct(Locator $locator) {
$this->locator = $locator; parent::__construct($locator, Identity::GOOGLE);
} }
public function call() { public function login() {
// Retrieve Google configuration // Retrieve Google configuration
$Google = $this->locator->config->authenticationMethods->Google; $Google = $this->locator->config->authenticationMethods->Google;
...@@ -58,40 +56,19 @@ class GoogleLogin { ...@@ -58,40 +56,19 @@ class GoogleLogin {
$typedId = explode('/', $res->getResourceName())[1]; $typedId = explode('/', $res->getResourceName())[1];
// Search if the user is already registered into RAP using the Google ID. return $this->onIdentityDataReceived($typedId, function($identity) use($emailAddresses, $name, $surname) {
$user = $this->locator->getUserHandler()->findUserByIdentity(Identity::GOOGLE, $typedId);
$session = $this->locator->getSession();
if ($user === null) {
// Create new user
$user = new \RAP\User();
$identity = new Identity(Identity::GOOGLE);
$identity->email = $emailAddresses[0]; $identity->email = $emailAddresses[0];
$identity->name = $name; $identity->name = $name;
$identity->surname = $surname; $identity->surname = $surname;
$identity->typedId = $typedId; });
$user->addIdentity($identity);
$session->userToLogin = $user;
$session->save();
header('Location: ' . $this->locator->getBasePath() . '/tou-check');
die();
}
$this->locator->getAuditLogger()->info("LOGIN,Google," . $user->id);
$this->locator->getCallbackHandler()->manageLoginRedirect($user, $session);
die();
} else { } else {
// Redirect to Google authorization URL for obtaining an access token // Redirect to Google authorization URL for obtaining an access token
$authUrl = $client->createAuthUrl(); $authUrl = $client->createAuthUrl();
header('Location: ' . $authUrl); header('Location: ' . $authUrl);
die(); die();
} }
return null;
} }
} }
<?php
namespace RAP;
class LinkedInLogin extends LoginHandler {
public function __construct(Locator $locator) {
parent::__construct($locator, Identity::FACEBOOK);
}
public function login() {
// Retrieve LinkedIn configuration
$LinkedIn = $this->locator->config->authenticationMethods->LinkedIn;
$url = "https://www.linkedin.com/oauth/v2/authorization?response_type=code";
$url .= "&client_id=" . $LinkedIn->id;
$url .= "&redirect_uri=" . $LinkedIn->callback;
$url .= "&state=789654123";
$url .= "&scope=r_basicprofile r_emailaddress";
header("Location: $url");
}
public function retrieveToken() {
// Retrieve LinkedIn configuration
$LinkedIn = $this->locator->config->authenticationMethods->LinkedIn;
if (!isset($_REQUEST['code'])) {
die("Unable to get LinkedIn client code");
}
//create array of data to be posted to get AccessToken
$post_data = array(
'grant_type' => "authorization_code",
'code' => $_REQUEST['code'],
'redirect_uri' => $LinkedIn->callback,
'client_id' => $LinkedIn->id,
'client_secret' => $LinkedIn->secret
);
//traverse array and prepare data for posting (key1=value1)
foreach ($post_data as $key => $value) {
$post_items[] = $key . '=' . $value;
}
//create the final string to be posted
$post_string = implode('&', $post_items);
//create cURL connection
$conn1 = curl_init('https://www.linkedin.com/oauth/v2/accessToken');
//set options
curl_setopt($conn1, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($conn1, CURLOPT_RETURNTRANSFER, true);
curl_setopt($conn1, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($conn1, CURLOPT_FOLLOWLOCATION, 1);
//set data to be posted
curl_setopt($conn1, CURLOPT_POSTFIELDS, $post_string);
//perform our request
$result1 = curl_exec($conn1);
$info1 = curl_getinfo($conn1);
if ($info1['http_code'] === 200) {
$my_token = json_decode($result1, TRUE);
$access_token = $my_token['access_token'];
$expires_in = $my_token['expires_in'];
curl_close($conn1);
} else {
//show information regarding the error
$errorMessage = "Error: LinkedIn server response code: " . $info1['http_code'] . " - ";
$errorMessage .= curl_error($conn1);
curl_close($conn1);
http_response_code(500);
die($errorMessage);
}
// Call to API
$conn2 = curl_init();
curl_setopt($conn2, CURLOPT_URL, "https://api.linkedin.com/v1/people/~:(first-name,last-name,email-address,id)?format=json");
curl_setopt($conn2, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer ' . $access_token
));
curl_setopt($conn2, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($conn2);
$info2 = curl_getinfo($conn2);
if ($info2['http_code'] === 200) {
$data = json_decode($result, TRUE);
curl_close($conn2);
if (isset($data['errorCode'])) {
$errorMessage = $data['message'];
die($errorMessage);
}
$typedId = $data['id'];
return $this->onIdentityDataReceived($typedId, function($identity) use($data) {
$identity->email = $data['emailAddress'];
$identity->name = $data['firstName'];
$identity->surname = $data['lastName'];
});
} else {
//show information regarding the error
$errorMessage = "Error: LinkedIn server response code: " . $info2['http_code'] . " - ";
$errorMessage = $errorMessage . curl_error($conn2);
curl_close($conn2);
die($errorMessage);
}
return null;
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment