public function createService($serviceName)
 {
     if (!$this->storage->hasConfig($serviceName)) {
         throw new \InvalidArgumentException('Service ' . $serviceName . ' unknown or not configured!');
     }
     if (array_key_exists($serviceName, $this->objectCache)) {
         return $this->objectCache[$serviceName];
     }
     if (null === $this->storage->getConsumerKey($serviceName)) {
         throw new \InvalidArgumentException('Service ' . $serviceName . ' has a configuration file, but the consumer key is not defined!');
     }
     if (null === $this->storage->getConsumerSecret($serviceName)) {
         throw new \InvalidArgumentException('Service ' . $serviceName . ' has a configuration file, but the consumer service is not defined!');
     }
     if (null === $this->storage->getCallbackUrl($serviceName)) {
         throw new \InvalidArgumentException('Service ' . $serviceName . ' has a configuration file, but the callback url is not defined!');
     }
     $callbackUrl = $this->storage->getCallbackUrl($serviceName);
     /** @var $serviceFactory \OAuth\ServiceFactory An OAuth service factory. */
     $serviceFactory = new \OAuth\ServiceFactory();
     $uriFactory = new \OAuth\Common\Http\Uri\UriFactory();
     $currentUri = $uriFactory->createFromAbsolute($callbackUrl);
     $credentials = new Credentials($this->storage->getConsumerKey($serviceName), $this->storage->getConsumerSecret($serviceName), $currentUri->getAbsoluteUri());
     $this->objectCache[$serviceName] = $serviceFactory->createService($serviceName, $credentials, $this->storage, $this->storage->getScope($serviceName));
     return $this->objectCache[$serviceName];
 }
 public function getAuthService($site, $landingPage)
 {
     $uriFactory = new \OAuth\Common\Http\Uri\UriFactory();
     $currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER);
     $currentUri->setQuery('');
     $serviceFactory = new \OAuth\ServiceFactory();
     $credentials = new Credentials($this->siteCredentials[$site]['key'], $this->siteCredentials[$site]['secret'], $landingPage);
     $storage = new Session();
     $service = $serviceFactory->createService($site, $credentials, $storage, array('userinfo_email', 'userinfo_profile'));
     return $service;
 }
 /**
  * Register the Social OAuth API class.
  *
  * @return void
  */
 protected function registerSocialAuth()
 {
     // Session storage
     $storage = new Session();
     $factory = new \OAuth\ServiceFactory();
     foreach ($this->config['active'] as $key => $social) {
         $this->app->singleton($social, function ($c) use($social, $factory, $storage) {
             // Setup the credentials for the requests
             $credentials = new Credentials($this->config[$social]['key'], $this->config[$social]['secret'], $this->app->request->getFullUrl());
             return $factory->createService($social, $credentials, $storage, []);
         });
     }
 }
    /**
     * @param bool $need_refresh_token
     *
     * @return array|null
     * @throws \OAuth\OAuth2\Service\Exception\MissingRefreshTokenException
     */
    protected function oauth_login($need_refresh_token = false)
    {
        $settings = $this->get_plugin_settings();
        if (!$settings) {
            $settings = $this->get_current_settings();
        }
        $redirect_url = get_admin_url(null, 'admin.php?page=gf_settings&subview=gravityformsbitrix24');
        /** @var $serviceFactory \OAuth\ServiceFactory An OAuth service factory. */
        $serviceFactory = new \OAuth\ServiceFactory();
        // Session storage
        $storage = new \OAuth\Common\Storage\Memory();
        // Setup the credentials for the requests
        $credentials = new \OAuth\Common\Consumer\Credentials($settings['clientId'], $settings['clientSecret'], $redirect_url);
        /** @var $provider \OAuth\OAuth2\Service\Bitrix24 */
        $provider = $serviceFactory->createService('Bitrix24', $credentials, $storage, array('crm'), new \OAuth\Common\Http\Uri\Uri('https://' . $settings['domain']));
        if ($need_refresh_token) {
            $token = new OAuth\OAuth2\Token\StdOAuth2Token();
            $token->setAccessToken($settings['authId']);
            $token->setRefreshToken($settings['refreshId']);
            $token = $provider->refreshAccessToken($token);
            $settings['authId'] = $token->getAccessToken();
            $settings['refreshId'] = $token->getRefreshToken();
            $settings['endOfLife'] = $token->getEndOfLife();
            $this->update_plugin_settings($settings);
            self::$api = null;
            return $settings;
        }
        if (!isset($_GET['code']) && empty($settings['oauthCode'])) {
            echo '<div class="error" style="padding: 10px; font-size: 12px;">' . __('Please enter the code', 'gravityformsbitrix24') . '</div>';
            echo '<script>window.open("' . $provider->getAuthorizationUri() . '", "_blank", "width=300, height=200");
			</script>';
        } else {
            $code = isset($_GET['code']) ? $_GET['code'] : $settings['oauthCode'];
            try {
                $token = $provider->requestAccessToken($code);
                $extra_params = $token->getExtraParams();
                $settings['memberId'] = $extra_params['member_id'];
                $settings['authId'] = $token->getAccessToken();
                $settings['refreshId'] = $token->getRefreshToken();
                $settings['endOfLife'] = $token->getEndOfLife();
                unset($settings['oauthCode']);
                $this->update_plugin_settings($settings);
                if (isset($_GET['code'])) {
                    wp_redirect($redirect_url);
                }
            } catch (\Exception $ex) {
                $markup = '<div class="error" style="padding: 10px; font-size: 12px;">' . __('Oauth code is not right.', 'gravityformsbitrix24') . '</div>';
                echo $markup;
            }
        }
    }
Example #5
0
 /**
  *
  * @param call
  * @return \OAuth\OAuth2\Service\GitHub
  */
 protected function _getGithubService($callbackUrl = null)
 {
     // Session storage
     $storage = new Session();
     $serviceFactory = new \OAuth\ServiceFactory();
     if (is_null($callbackUrl)) {
         $callbackUrl = $this->_getConfigData('base_url') . "/login/";
     }
     $apiKey = $this->_getConfigData('github_api_key');
     $apiSecret = $this->_getConfigData('github_api_secret');
     $credentials = new Credentials($apiKey, $apiSecret, $callbackUrl);
     $github = $serviceFactory->createService('GitHub', $credentials, $storage, array('user:email'));
     return $github;
 }
Example #6
0
 /**
  * {@inheritdoc}
  */
 public function getLibService()
 {
     // Check if lib service does not exist
     if (is_null($this->libService)) {
         // Get config
         $config = $this->getConfig();
         // Build new OAuth library service instance
         $libCredentials = new \OAuth\Common\Consumer\Credentials($config->getApiKey(), $config->getApiSecret(), $config->getReturnUrl());
         $libStorage = new \OAuth\Common\Storage\Memory();
         $libServiceFactory = new \OAuth\ServiceFactory();
         $this->libService = $libServiceFactory->createService($config->getPlatform(), $libCredentials, $libStorage, $config->getApiScopes());
     }
     return $this->libService;
 }
Example #7
0
 /**
  * EtsyService constructor.
  */
 public function __construct()
 {
     $this->etsyKey = config('app.etsy_api_key');
     $this->etsySecret = config('app.etsy_api_secret');
     $this->etsyCallbackUrl = config('app.etsy_callback_url');
     $this->storage = new Session();
     $uriFactory = new UriFactory();
     $currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER);
     $currentUri->setQuery('');
     $this->credentials = new Credentials($this->etsyKey, $this->etsySecret, url($this->etsyCallbackUrl));
     // Instantiate the Etsy service using the credentials, http client and storage mechanism for the token
     $serviceFactory = new \OAuth\ServiceFactory();
     $this->service = $serviceFactory->createService('Etsy', $this->credentials, $this->storage);
 }
Example #8
0
 public function __construct($consumer_key, $consumer_secret, $callbackUrl = null, \OAuth\Common\Storage\TokenStorageInterface $storageAdapter = null)
 {
     if ($callbackUrl == null) {
         $uriFactory = new \OAuth\Common\Http\Uri\UriFactory();
         $currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER);
         $currentUri->setQuery('');
         $callbackUrl = $currentUri->getAbsoluteUri();
     }
     $factory = new \OAuth\ServiceFactory();
     $credentials = new \OAuth\Common\Consumer\Credentials($consumer_key, $consumer_secret, $callbackUrl);
     if ($storageAdapter == null) {
         $storageAdapter = new \OAuth\Common\Storage\Session();
     }
     $this->service = $factory->createService('google', $credentials, $storageAdapter, ['fitness_activity_read']);
 }
Example #9
0
 /**
  * @param array $config
  *
  * param example:
  *
  * private $config = [
  *   'app_key' => 'APP KEY',
  *   'app_secret' => 'APP SECRET',
  *   'access_token' => 'USER TOKEN'
  * ];
  *
  */
 public function __construct($config)
 {
     $serviceFactory = new \OAuth\ServiceFactory();
     $serviceFactory->setHttpClient(new CurlClient());
     $token = new StdOAuth2Token();
     $token->setAccessToken($config['access_token']);
     $storage = new Session();
     $storage->storeAccessToken('linkedin', $token);
     $redirectUrl = '';
     if (isset($_SERVER['HTTP_HOST'])) {
         $redirectUrl = $_SERVER['HTTP_HOST'];
     }
     $credentials = new Credentials($config['app_key'], $config['app_secret'], $redirectUrl);
     $this->service = $serviceFactory->createService('linkedin', $credentials, $storage, ['r_fullprofile', 'r_emailaddress', 'rw_nus']);
 }
Example #10
0
function reg_with_fb()
{
    $_SESSION['fb_from'] = "register";
    $social = new Social();
    $social->includeFacebookLib();
    $client_id = Get::sett('social_fb_api');
    $client_secret = Get::sett('social_fb_secret');
    $redirect_uri = Get::sett('url') . 'index.php?modname=login&op=facebook_login';
    $serviceFactory = new \OAuth\ServiceFactory();
    $storage = new Session();
    $credentials = new Credentials($client_id, $client_secret, $redirect_uri);
    $facebookService = $serviceFactory->createService('facebook', $credentials, $storage, array());
    //, 'userinfo_profile'
    $authUrl = $facebookService->getAuthorizationUri();
    header('Location: ' . $authUrl);
    die;
}
 /**
  * Generate a new access token for google analytics API using client_id, client_secret and refresh_token, set in the config
  * @return string
  */
 public function access_token()
 {
     if (!$this->_access_token) {
         $config = Kohana::$config->load('services-manager.reports.googleanalytics');
         if (count($missing_keys = array_diff(array('refresh_token', 'client_id', 'client_secret'), array_keys($config)))) {
             throw new Kohana_Exception('Must set :keys for googleanalytics service configuration', array(':keys' => join(', ', $missing_keys)));
         }
         // require_once Kohana::find_file("vendor", "googleoauth");
         // Session storage
         $storage = new Session();
         // Setup the credentials for the requests
         $credentials = new Credentials($config['client_id'], $config['client_secret'], Request::current()->url());
         $serviceFactory = new \OAuth\ServiceFactory();
         // Instantiate the Google service using the credentials, http client and storage mechanism for the token
         $googleService = $serviceFactory->createService('google', $credentials, $storage, array('userinfo_email', 'userinfo_profile'));
         $tokenInterface = new \OAuth\OAuth2\Token\StdOAuth2Token(NULL, $config['refresh_token']);
         $token = $googleService->refreshAccessToken($tokenInterface);
         $this->_access_token = $token->getAccessToken();
     }
     return $this->_access_token;
 }
Example #12
0
 public function loginFacebook()
 {
     /**
      * Bootstrap the example
      *
      *require_once __DIR__ . '/bootstrap.php';
      */
     $storage = new Session();
     // Session storage
     $servicesCredentials['facebook']['key'] = '641605372625410';
     $servicesCredentials['facebook']['secret'] = 'ddcc4fda61288b868a6ab30eae14400c';
     // Setup the credentials for the requests
     $uriFactory = new \OAuth\Common\Http\Uri\UriFactory();
     $currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER);
     $currentUri->setHost($_SERVER['HTTP_HOST']);
     $currentUri->setQuery('');
     $credentials = new Credentials($servicesCredentials['facebook']['key'], $servicesCredentials['facebook']['secret'], $currentUri->getAbsoluteUri());
     // Instantiate the Facebook service using the credentials, http client and storage mechanism for the token
     /** @var $facebookService Facebook */
     $serviceFactory = new \OAuth\ServiceFactory();
     $facebookService = $serviceFactory->createService('facebook', $credentials, $storage, array());
     if (!empty($_GET['code'])) {
         // This was a callback request from facebook, get the token
         $token = $facebookService->requestAccessToken($_GET['code']);
         // Send a request with it
         $result = json_decode($facebookService->request('/me'), true);
         // Show some of the resultant data
         echo 'Your unique facebook user id is: ' . $result['id'] . ' and your name is ' . $result['name'];
         $user = User::register($result);
     } elseif (!empty($_GET['go']) && $_GET['go'] === 'go') {
         $url = $facebookService->getAuthorizationUri();
         header('Location: ' . $url);
     } else {
         $url = $currentUri->getRelativeUri() . '?go=go';
         echo "<a href='{$url}'>Login with Facebook!</a>";
     }
 }
 /**
  * Create connector
  * @param $name the unique connector name
  * @param $service array the service
  * @param $storage_type String the storage type
  * @return connector instance
  */
 public function createConnector($name, $service, $session, $storage_type)
 {
     if (array_key_exists("callback_url", $service) && $service['callback_url'] != "") {
         $callback_url = $service['callback_url'];
     } else {
         $callback_url = $this->router->generate("oauthexternal_connect", array("connectorName" => $name), true);
     }
     //handle special redirect callback for some services (have to be defined on the service website)
     if ($service['type'] == "twitter") {
         $callback_url = "oob";
     }
     //handle version of oauth by service type
     $version = 2;
     if (strtolower($service['type']) == "bitbucket" || strtolower($service['type']) == "etsy" || strtolower($service['type']) == "fitbit" || strtolower($service['type']) == "tumblr" || strtolower($service['type']) == "twitter") {
         $version = 1;
     }
     $connector = new ConnectorWrapper($name, null, $service['type'], $callback_url, $service['scopes'], $version);
     // Setup the storage
     if ($storage_type == "session") {
         $storage = new SymfonySession($session);
     } else {
         //memory
         $storage = new Memory();
     }
     $uriFactory = new \OAuth\Common\Http\Uri\UriFactory();
     $currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER);
     $currentUri->setQuery('');
     // Setup the credentials
     $credentials = new Credentials($service["client_id"], $service["client_secret"], "oob");
     //$currentUri->getAbsoluteUri()
     $serviceFactory = new \OAuth\ServiceFactory();
     //$serviceFactory->setHttpClient(new CurlClient());
     $client = $serviceFactory->createService($service["type"], $credentials, $storage);
     $connector->setService($client);
     return $connector;
 }
Example #14
0
 * @Copyright (C) 2014 VINADES.,JSC. All rights reserved
 * @License GNU/GPL version 2 or any later version
 * @Createdate Sun, 26 Oct 2014 08:34:25 GMT
 */
if (!defined('NV_IS_MOD_USER')) {
    die('Stop!!!');
}
require_once NV_ROOTDIR . '/modules/users/oAuthLib/autoload.php';
use OAuth\OAuth2\Service\Google;
use OAuth\Common\Storage\Session;
use OAuth\Common\Consumer\Credentials;
// Bootstrap the example
require_once NV_ROOTDIR . '/modules/users/oAuthLib/OAuth/bootstrap.php';
// Session storage
$storage = new Session();
$serviceFactory = new \OAuth\ServiceFactory();
// Setup the credentials for the requests
$credentials = new Credentials($global_config['google_client_id'], $global_config['google_client_secret'], NV_MAIN_DOMAIN . NV_BASE_SITEURL . 'index.php?' . NV_LANG_VARIABLE . '=' . NV_LANG_DATA . '&' . NV_NAME_VARIABLE . '=' . $module_name . '&' . NV_OP_VARIABLE . '=oauth&server=google');
// Instantiate the Google service using the credentials, http client and storage mechanism for the token
/** @var $googleService Google */
$googleService = $serviceFactory->createService('google', $credentials, $storage, array('userinfo_email', 'userinfo_profile'));
if (!empty($_GET['code'])) {
    // This was a callback request from google, get the token
    $googleService->requestAccessToken($_GET['code']);
    // Send a request with it
    $result = json_decode($googleService->request('https://www.googleapis.com/oauth2/v1/userinfo'), true);
    if (isset($result['email'])) {
        $attribs = array('identity' => $result['link'], 'result' => 'is_res', 'id' => $result['id'], 'contact/email' => $result['email'], 'namePerson/first' => $result['family_name'], 'namePerson/last' => $result['given_name'], 'namePerson' => $result['name'], 'person/gender' => $result['gender'], 'server' => $server, 'current_mode' => 3);
    } else {
        $attribs = array('result' => 'notlogin');
    }
Example #15
0
 /**
  *  List jobs print
  *
  *  @return  int                     0 if OK, >0 if KO
  */
 function list_jobs()
 {
     global $conf, $db, $langs, $bc;
     $error = 0;
     $html = '';
     // Token storage
     $storage = new DoliStorage($this->db, $this->conf);
     // Setup the credentials for the requests
     $credentials = new Credentials($this->google_id, $this->google_secret, DOL_MAIN_URL_ROOT . '/core/modules/oauth/getgoogleoauthcallback.php');
     $serviceFactory = new \OAuth\ServiceFactory();
     $apiService = $serviceFactory->createService('Google', $credentials, $storage, array());
     // Check if we have auth token
     $token_ok = true;
     try {
         $token = $storage->retrieveAccessToken('Google');
     } catch (Exception $e) {
         $this->errors[] = $e->getMessage();
         $token_ok = false;
         $error++;
     }
     $expire = false;
     // Is token expired or will token expire in the next 30 seconds
     if ($token_ok) {
         $expire = $token->getEndOfLife() !== -9002 && $token->getEndOfLife() !== -9001 && time() > $token->getEndOfLife() - 30;
     }
     // Token expired so we refresh it
     if ($token_ok && $expire) {
         try {
             // il faut sauvegarder le refresh token car google ne le donne qu'une seule fois
             $refreshtoken = $token->getRefreshToken();
             $token = $apiService->refreshAccessToken($token);
             $token->setRefreshToken($refreshtoken);
             $storage->storeAccessToken('Google', $token);
         } catch (Exception $e) {
             $this->errors[] = $e->getMessage();
             $error++;
         }
     }
     // Getting Jobs
     // Send a request with api
     try {
         $response = $apiService->request(self::PRINTERS_GET_JOBS);
     } catch (Exception $e) {
         $this->errors[] = $e->getMessage();
         $error++;
     }
     $responsedata = json_decode($response, true);
     //$html .= '<pre>'.print_r($responsedata,true).'</pre>';
     $html .= '<table width="100%" class="noborder">';
     $html .= '<tr class="liste_titre">';
     $html .= "<td>Id</td>";
     $html .= "<td>Owner</td>";
     $html .= '<td>Printer</td>';
     $html .= '<td>File</td>';
     $html .= '<td>Status</td>';
     $html .= '<td>Cancel</td>';
     $html .= '</tr>' . "\n";
     $var = True;
     $jobs = $responsedata['jobs'];
     //$html .= '<pre>'.print_r($jobs['0'],true).'</pre>';
     if (is_array($jobs)) {
         foreach ($jobs as $value) {
             $var = !$var;
             $html .= '<tr ' . $bc[$var] . '>';
             $html .= '<td>' . $value['id'] . '</td>';
             $html .= '<td>' . $value['ownerId'] . '</td>';
             $html .= '<td>' . $value['printerName'] . '</td>';
             $html .= '<td>' . $value['title'] . '</td>';
             $html .= '<td>' . $value['status'] . '</td>';
             $html .= '<td>&nbsp;</td>';
             $html .= '</tr>';
         }
     } else {
         $html .= '<tr ' . $bc[$var] . '>';
         $html .= '<td colspan="6">' . $langs->trans("None") . '</td>';
         $html .= '</tr>';
     }
     $html .= '</table>';
     $this->resprint = $html;
     return $error;
 }
|                                                                           |
|   Copyright (c) 2013 (Forma)                                              |
|   http://www.formalms.org                                                 |
|   License  http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt           |
|                                                                           |
\ ======================================================================== */
use OAuth\OAuth2\Service\Facebook;
use OAuth\Common\Storage\Session;
use OAuth\Common\Consumer\Credentials;
$social = new Social();
$social->includeFacebookLib();
$client_id = Get::sett('social_fb_api');
$client_secret = Get::sett('social_fb_secret');
$redirect_uri = Get::sett('url') . 'index.php?modname=login&op=facebook_login';
try {
    $serviceFactory = new \OAuth\ServiceFactory();
    $storage = new Session();
    $credentials = new Credentials($client_id, $client_secret, $redirect_uri);
    $facebookService = $serviceFactory->createService('facebook', $credentials, $storage, array());
    //, 'userinfo_profile'
    // facebook login
    // 1. no params $_REQUEST or $_REQUEST['connect'] -> GOTO URL AUTH OR CONNECT FACEBOOK ACCOUNT
    // 2. $_REQUEST['code'] -> RETURN OK FROM FACEBOOK AUTH
    // 3. $_REQUEST['error'] -> RETURN CANCEL FROM FACEBOOK AUTH
    switch (TRUE) {
        // 1. no params $_REQUEST -> GOTO URL AUTH
        case !isset($_REQUEST['code']) && !isset($_REQUEST['error_code']) || isset($_REQUEST['connect']):
            $authUrl = $facebookService->getAuthorizationUri();
            header('Location: ' . $authUrl);
            die;
            break;
Example #17
0
 /**
  * Callback for Linkedin.
  *
  * @deprecated
  */
 public function callbackLoginLinkedinAction()
 {
     $uriFactory = new \OAuth\Common\Http\Uri\UriFactory();
     $currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER);
     $currentUri->setQuery('');
     $config = $this->getServiceLocator()->get('Config');
     // Session storage
     $storage = new Session();
     // Setup the credentials for the requests
     $credentials = new Credentials($config['linkedin']['appId'], $config['linkedin']['secret'], $currentUri->getAbsoluteUri());
     $serviceFactory = new \OAuth\ServiceFactory();
     // Instantiate the Linkedin service using the credentials, http client and storage mechanism for the token
     /** @var $linkedinService Linkedin */
     $linkedinService = $serviceFactory->createService('linkedin', $credentials, $storage, array('r_basicprofile'));
     if (!empty($_GET['code'])) {
         // retrieve the CSRF state parameter
         $state = isset($_GET['state']) ? $_GET['state'] : null;
         // This was a callback request from linkedin, get the token
         $token = $linkedinService->requestAccessToken($_GET['code'], $state);
         // Send a request with it. Please note that XML is the default format.
         $result = json_decode($linkedinService->request('/people/~?format=json'), true);
         // Show some of the resultant data
         echo 'Your linkedin first name is ' . $result['firstName'] . ' and your last name is ' . $result['lastName'];
     } elseif (!empty($_GET['go']) && $_GET['go'] === 'go') {
         $url = $linkedinService->getAuthorizationUri();
         header('Location: ' . $url);
         exit;
     } else {
         $url = $currentUri->getRelativeUri() . '?go=go';
         echo "<a href='{$url}'>Login with Linkedin!</a>";
     }
 }
Example #18
0
 public function init($args = null)
 {
     $name = $this->tipsy()->request()->loc(1);
     if (!Tipsy::service('cfgr')->get('api-' . $name . '-key') || !Tipsy::service('cfgr')->get('api-' . $name . '-secret')) {
         die('no auth config for ' . $name);
     }
     $storage = new Session();
     $credentials = new Credentials(Tipsy::service('cfgr')->get('api-' . $name . '-key'), Tipsy::service('cfgr')->get('api-' . $name . '-secret'), $this->tipsy()->request()->url());
     $serviceFactory = new \OAuth\ServiceFactory();
     $scope = [];
     $email = Tipsy::service('cfgr')->get('apiconfig-email');
     if ($email) {
         switch ($name) {
             case 'facebook':
                 $scope = ['public_profile', 'email'];
                 break;
             case 'linkedin':
                 $scope = ['r_basicprofile', 'r_emailaddress'];
                 break;
             case 'github':
                 $scope = ['user:email'];
                 break;
             case 'google':
                 $scope = ['userinfo_email', 'userinfo_profile'];
                 break;
             case 'instagram':
                 $scope = ['basic'];
                 break;
         }
     } else {
         switch ($name) {
             case 'instagram':
                 $scope = ['basic'];
                 break;
         }
     }
     $service = $serviceFactory->createService($name, $credentials, $storage, $scope);
     $code = $name == 'twitter' ? 'oauth_token' : 'code';
     if (!empty($_GET[$code])) {
         switch ($name) {
             case 'twitter':
                 $token = $storage->retrieveAccessToken('Twitter');
                 $service->requestAccessToken($_GET['oauth_token'], $_GET['oauth_verifier'], $token->getRequestTokenSecret());
                 break;
             default:
                 $state = isset($_GET['state']) ? $_GET['state'] : null;
                 $token = $service->requestAccessToken($_GET[$code], $state);
                 break;
         }
         switch ($name) {
             case 'facebook':
                 $data = json_decode($service->request('/me?fields=name,gender' . ($email ? ',email' : '')), true);
                 $result = [id => $data['id'], name => $data['name'], email => $data['email'], gender => $data['gender']];
                 break;
             case 'twitter':
                 $data = json_decode($service->request('account/verify_credentials.json'), true);
                 $result = [id => $data['id'], name => $data['name']];
                 break;
             case 'instagram':
                 $data = json_decode($service->request('users/self'), true);
                 $result = [id => $data['data']['id'], name => $data['data']['full_name'], avatar => $data['data']['profile_picture'], website => $data['data']['website']];
                 break;
             case 'google':
                 $data = json_decode($service->request('userinfo'), true);
                 $result = [id => $data['id'], name => $data['name'], email => $data['email'], gender => $data['gender'], avatar => $data['picture']];
                 break;
             case 'linkedin':
                 $emailQ = Tipsy::service('cfgr')->get('apiconfig-email') ? ':(id,firstName,lastName,email-address)' : ':(id,firstName,lastName)';
                 $data = json_decode($service->request('/people/~' . $emailQ . '?format=json'), true);
                 $result = [id => $data['id'], name => $data['firstName'] . ' ' . $data['lastName'], email => $data['emailAddress']];
                 break;
             case 'github':
                 $data = json_decode($service->request('user'), true);
                 $result = [id => $data['id'], name => $data['name'], location => $data['location'], website => $data['blog'], email => $data['email'], avatar => $data['avatar_url']];
                 if ($email && !$result['email']) {
                     $data = json_decode($service->request('user/emails'), true);
                     $result['email'] = $data[0];
                 }
                 break;
         }
         if ($result['id']) {
             $user = \App\User::byAuth($result['id'], $name);
             if (!$user) {
                 if (!Tipsy::middleware('Session')->user()) {
                     $user = new \App\User();
                     foreach ($result as $key => $value) {
                         if ($key == 'id') {
                             continue;
                         }
                         $user->{$key} = $value;
                     }
                     $user->save();
                 } else {
                     $user = Tipsy::middleware('Session')->user();
                 }
                 $auth = new \App\Auth(['value' => $result['id'], 'type' => $name, 'user' => $user->id]);
                 $auth->save();
             }
             // user mismatch. fail
             if ($user && Tipsy::middleware('Session')->user() && $user->id != Tipsy::middleware('Session')->user()->id) {
                 header('Location: /account');
                 exit;
             }
             $_SESSION['user'] = $user->id;
             header('Location: /account');
         }
     } else {
         $request = [];
         if ($name == 'twitter') {
             $request = ['oauth_token' => $service->requestRequestToken()->getRequestToken()];
         }
         $url = $service->getAuthorizationUri($request);
         header('Location: ' . $url);
     }
 }
 public function initializeService($scopes = array())
 {
     $this->getStorage();
     // try {
     $handle = $this->getHandle();
     $serviceFactory = new \OAuth\ServiceFactory();
     $callbackUrl = \Craft\craft()->oauth->callbackUrl($handle);
     $credentials = new Credentials($this->clientId, $this->clientSecret, $callbackUrl);
     if (!$scopes) {
         $scopes = array();
     }
     $this->service = $serviceFactory->createService($handle, $credentials, $this->storage, $scopes);
     // }
     // catch(\Exception $e)
     // {
     // }
 }
Example #20
0
require_once __DIR__ . '/vendor/autoload.php';
$session = new Session();
$app = new \Slim\App(new \Slim\Container(Config::get('slimconfig')));
/* init php-view */
$container = $app->getContainer();
$container['view'] = function ($container) {
    return new \Slim\Views\PhpRenderer(__DIR__ . '/templates/');
};
/* landing page */
$app->get('/', function ($request, $response, $args) use($session) {
    return $this->view->render($response, 'index.html', $args);
});
/* GitHub OAuth login */
$app->get('/login', function ($request, $response) use($session) {
    $credentials = new \OAuth\Common\Consumer\Credentials(Config::get('github.oauth.key'), Config::get('github.oauth.secret'), Config::get('github.oauth.redirecturl'));
    $serviceFactory = new \OAuth\ServiceFactory();
    $gitHub = $serviceFactory->createService('GitHub', $credentials, new \OAuth\Common\Storage\Session(), array('user:email', 'public_repo', 'repo:status', 'admin:repo_hook'));
    $queryParams = $request->getQueryParams();
    if (isset($queryParams['code'])) {
        try {
            $token = $gitHub->requestAccessToken($queryParams['code']);
            $result = json_decode($gitHub->request('user'), true);
            /* TODO: register new user at master if it does not exist yet */
            $session->login($result['login']);
            $_SESSION['name'] = $result['name'];
            $_SESSION['profile_url'] = $result['html_url'];
            $_SESSION['token'] = $token->getAccessToken();
            return $response->withRedirect('/repositories');
        } catch (\OAuth\Common\Http\Exception\TokenResponseException $e) {
            return $response->withStatus(500)->write($e->getMessage());
        }
<?php

$consumerKey = 'getthisfromdiscogs';
$consumerSecret = 'getthisfromdiscogs';
require '../vendor/autoload.php';
use OAuth\OAuth1\Service\BitBucket;
use OAuth\Common\Storage\Session;
use OAuth\Common\Consumer\Credentials;
ini_set('date.timezone', 'Europe/Amsterdam');
$uriFactory = new \OAuth\Common\Http\Uri\UriFactory();
$currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER);
$currentUri->setQuery('');
$serviceFactory = new \OAuth\ServiceFactory();
// We need to use a persistent storage to save the token, because oauth1 requires the token secret received before'
// the redirect (request token request) in the access token request.
$storage = new Session();
// Setup the credentials for the requests
$credentials = new Credentials($consumerKey, $consumerSecret, $currentUri->getAbsoluteUri());
// Instantiate the BitBucket service using the credentials, http client and storage mechanism for the token
/** @var $bbService BitBucket */
$bbService = $serviceFactory->createService('Discogs', $credentials, $storage);
if (isset($_GET['oauth_token'])) {
    $token = $storage->retrieveAccessToken('Discogs');
    $bbService->requestAccessToken($_GET['oauth_token'], $_GET['oauth_verifier'], $token->getRequestTokenSecret());
    header("Location: /");
    exit;
}
$isAuthorized = true;
try {
    $token = $storage->retrieveAccessToken('Discogs');
} catch (\OAuth\Common\Storage\Exception\TokenNotFoundException $e) {
Example #22
0
    die('Please copy facebook-settings.php.dist to facebook-settings.php');
}
//requiring social app configuration
require_once __DIR__ . '/facebook-settings.php';
// token storage
$storage = new OAuth\Common\Storage\Session();
// current uri
$uriFactory = new OAuth\Common\Http\Uri\UriFactory();
$currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER);
$currentUri->setQuery('');
// Setup the credentials for the requests
$credentials = new OAuth\Common\Consumer\Credentials($facebook['key'], $facebook['secret'], $currentUri->getAbsoluteUri());
// Facebook's Data Access Scopes
$scopes = array('public_profile', 'email', 'user_birthday', 'user_education_history', 'user_friends', 'user_hometown', 'user_location', 'user_posts', 'user_relationships', 'user_work_history');
// Instantiate the Facebook service using the credentials, http client and storage mechanism for the token
$serviceFactory = new OAuth\ServiceFactory();
$facebookService = $serviceFactory->createService('facebook', $credentials, $storage, $scopes);
if (!empty($_GET['code'])) {
    // This was a callback request from facebook, get the token
    $token = $facebookService->requestAccessToken($_GET['code']);
    //Session SDK instantiation
    //more info: https://github.com/veridu/veridu-php
    $session = new Veridu\SDK\Session(new Veridu\SDK\API(new Veridu\Common\Config($veridu['client'], $veridu['secret'], $veridu['version']), new Veridu\HTTPClient\CurlClient(), new Veridu\Signature\HMAC()));
    //creates new a read/write Veridu session
    //more info: https://veridu.com/wiki/Session_Resource
    $session->create(false);
    //retrieve API SDK instance from Session SDK instance
    $api = $session->getAPI();
    //sends the access token
    //more info: https://veridu.com/wiki/SSO_Resource
    $response = $api->signedFetch('POST', 'sso/facebook', array('token' => $token->getAccessToken()));
Example #23
0
 function homeUserProfile($picture = false, $viewer = false, $intest = false)
 {
     $this->loadUserData($this->getViewer());
     $acl_man =& Docebo::user()->getAclManager();
     list($class_picture, $this->max_dim_avatar) = $this->getPhotoLimit($picture);
     $html = '<div class="up_dashboard"><div class="content">';
     $html .= '<p class="logo">' . ($this->user_info[ACL_INFO_AVATAR] != "" ? $this->getPASrc($this->user_info[ACL_INFO_AVATAR], $this->_lang->def('_AVATAR'), 'boxed') : '<img class="boxed" src="' . getPathImage() . 'standard/user.png" alt="' . $this->_lang->def('_NOAVATAR') . '" />') . '</p>';
     $html .= '' . '<p class="userinfo">' . '<b>' . $this->_lang->def('_USERNAME') . '</b><br/> ' . $this->acl_man->relativeId($this->user_info[ACL_INFO_USERID]) . '</p>' . '<p class="userinfo">' . '<b>' . $this->_lang->def('_LASTNAME') . '</b><br/> ' . $this->acl_man->relativeId($this->user_info[ACL_INFO_LASTNAME]) . '</p>' . '<p class="userinfo">' . '<b>' . $this->_lang->def('_FIRSTNAME') . '</b><br/> ' . $this->acl_man->relativeId($this->user_info[ACL_INFO_FIRSTNAME]) . '</p>' . '<p class="userinfo">' . '<b>' . $this->_lang->def('_EMAIL') . '</b><br/> ' . ($this->user_info[ACL_INFO_EMAIL] !== false ? '<a href="mailto:' . $this->user_info[ACL_INFO_EMAIL] . '">' . $this->user_info[ACL_INFO_EMAIL] . '</a>' : $this->_lang->def('_HIDDEN')) . '</p>' . '<div class="nofloat"></div>';
     $social = new Social();
     if ($social->enabled()) {
         if (!$social->allConnected()) {
             $html .= '<b class="social-accounts-title">' . Lang::t('_CONNECT_YOUR_ACCOUNT_WITH', 'social') . '</b>';
             $html .= '<ul class="social-accounts">';
             if ($social->isActive('facebook') && !$social->connectedToUser('facebook')) {
                 $social = new Social();
                 $social->includeFacebookLib();
                 $client_id = Get::sett('social_fb_api');
                 $client_secret = Get::sett('social_fb_secret');
                 $redirect_uri = Get::sett('url') . 'index.php?modname=login&op=facebook_login';
                 $serviceFactory = new \OAuth\ServiceFactory();
                 $storage = new Session();
                 $credentials = new Credentials($client_id, $client_secret, $redirect_uri);
                 $facebookService = $serviceFactory->createService('facebook', $credentials, $storage, array());
                 //, 'userinfo_profile'
                 $loginUrl = $facebookService->getAuthorizationUri();
                 $html .= '<li><a href="' . $loginUrl . '" ' . 'title="' . Lang::t('_CONNECT', 'social') . ': ' . Lang::t('_FACEBOOK', 'social') . '"><span>' . Get::img('social/facebook.png', Lang::t('_FACEBOOK', 'social')) . '</span></a></li>';
             }
             if ($social->isActive('twitter') && !$social->connectedToUser('twitter')) {
                 $html .= '<li><a href="' . Get::sett('url') . 'index.php?modname=login&amp;op=twitter_login&amp;connect=1" ' . 'title="' . Lang::t('_CONNECT', 'social') . ': ' . Lang::t('_TWITTER', 'social') . '"><span>' . Get::img('social/twitter.png', Lang::t('_TWITTER', 'social')) . '</span></a></li>';
             }
             if ($social->isActive('linkedin') && !$social->connectedToUser('linkedin')) {
                 $html .= '<li><a href="' . Get::sett('url') . 'index.php?modname=login&amp;op=linkedin_login&amp;connect=1" ' . 'title="' . Lang::t('_CONNECT', 'social') . ': ' . Lang::t('_LINKEDIN', 'social') . '"><span>' . Get::img('social/linkedin.png', Lang::t('_LINKEDIN', 'social')) . '</span></a></li>';
             }
             if ($social->isActive('google') && !$social->connectedToUser('google')) {
                 $html .= '<li><a href="' . Get::sett('url') . 'index.php?modname=login&amp;op=google_login&amp;connect=1" ' . 'title="' . Lang::t('_CONNECT', 'social') . ': ' . Lang::t('_GOOGLE', 'social') . '"><span>' . Get::img('social/google.png', $this->user_info[ACL_INFO_GOOGLE_ID]) . '</span></a></li>';
             }
             $html .= '</ul><br/>';
         }
         if ($social->someConnected()) {
             $html .= '<b class="social-accounts-title">' . Lang::t('_CONNECTED_ACCOUNTS', 'social') . '</b>';
             $html .= '<ul class="social-accounts">';
             if ($social->connectedToUser('facebook')) {
                 $html .= '<li><a id="disconnect_facebook" href="index.php?r=SocialConnect/disconnect&amp;network=facebook" ' . 'title="' . Lang::t('_DISCONNECT', 'social') . ': ' . Lang::t('_FACEBOOK', 'social') . '"><span>' . Get::img('social/facebook.png', Lang::t('_FACEBOOK', 'social')) . '</span></a></li>';
             }
             if ($social->connectedToUser('twitter')) {
                 $html .= '<li><a id="disconnect_twitter" href="index.php?r=SocialConnect/disconnect&amp;network=twitter" ' . 'title="' . Lang::t('_DISCONNECT', 'social') . ': ' . Lang::t('_TWITTER', 'social') . '"><span>' . Get::img('social/twitter.png', Lang::t('_TWITTER', 'social')) . '</span></a></li>';
             }
             if ($social->connectedToUser('linkedin')) {
                 $html .= '<li><a id="disconnect_linkedin" href="index.php?r=SocialConnect/disconnect&amp;network=linkedin" ' . 'title="' . Lang::t('_DISCONNECT', 'social') . ': ' . Lang::t('_LINKEDIN', 'social') . '"><span>' . Get::img('social/linkedin.png', Lang::t('_LINKEDIN', 'social')) . '</span></a></li>';
             }
             if ($social->connectedToUser('google')) {
                 $html .= '<li><a id="disconnect_google" href="index.php?r=SocialConnect/disconnect&amp;network=google" ' . 'title="' . Lang::t('_DISCONNECT', 'social') . ': ' . Lang::t('_GOOGLE', 'social') . '"><span>' . Get::img('social/google.png', $this->user_info[ACL_INFO_GOOGLE_ID]) . '</span></a></li>';
             }
             $html .= '</ul>';
         }
         /* $html.=Util::widget('dialog', array(
         				'id' => 'confirm_disconnect',
         				'dynamicContent' => false,
         				'body'=>'mm',
         				'directSubmit'=>true,
         				'ajaxUrl' => '"ajax.adm_server.php?r=alms/enrollrules/add"',
         				'dynamicAjaxUrl' => true,
         				'callback' => 'function() {
         					this.destroy();
         				}',
         				'callEvents' => array(
         					array('caller' => 'disconnect_facebook', 'event' => 'click'),
         					array('caller' => 'disconnect_twitter', 'event' => 'click'),
         					array('caller' => 'disconnect_linkedin', 'event' => 'click'),
         					array('caller' => 'disconnect_google', 'event' => 'click'),
         				)
         			), true); */
     }
     $html .= '</div></div>';
     // box carriera
     require_once $GLOBALS['where_lms'] . '/lib/lib.middlearea.php';
     require_once $GLOBALS['where_lms'] . '/modules/course/course.php';
     $ma = new Man_MiddleArea();
     $access_career = $ma->currentCanAccessObj('career');
     //if($this->acl_man->relativeId($this->user_info[ACL_INFO_USERID]) == 'alberto' && $access_career) {
     if ($access_career) {
         $url = $this->_url_man;
         $course_stats = userCourseList($url, false, false);
         //TODO:  review this call . use course list to compute carreer
         $base_url = 'index.php?r=' . _after_login_ . '&amp;filter=';
         $end = 0;
         if (isset($course_stats['with_ustatus'][_CUS_END]) && $course_stats['with_ustatus'][_CUS_END] != 0) {
             $end = $course_stats['with_ustatus'][_CUS_END];
         }
         $html .= '<div class="inline_block">' . '<h2 class="heading">' . $this->_lang->def('_CAREER') . '</h2>' . '<div class="content">' . '<div class="course_stat">' . '<table summary="">' . '<tr><th scope="row">' . $this->_lang->def('_TOTAL_COURSE') . ' :</th><td>' . ($course_stats['total'] - $end) . '</td></tr>' . (isset($course_stats['with_ustatus'][_CUS_END]) && $course_stats['with_ustatus'][_CUS_END] != 0 ? '<tr><th scope="row">' . $this->_lang->def('_COURSE_END') . ' :</th><td>' . $course_stats['with_ustatus'][_CUS_END] . '</td></tr>' : '') . (isset($course_stats['expiring']) && $course_stats['expiring'] != 0 ? '<tr><th scope="row">' . $this->_lang->def('_COURSE_EXPIRING') . ' :</th><td>' . $course_stats['expiring'] . '</td></tr>' : '');
         if (count($course_stats['with_ulevel']) > 1) {
             require_once $GLOBALS['where_lms'] . '/lib/lib.levels.php';
             $lvl = CourseLevel::getLevels();
             foreach ($course_stats['with_ulevel'] as $lvl_num => $quantity) {
                 $html .= '' . '<tr><th scope="row">' . str_replace('[level]', $lvl[$lvl_num], $this->_lang->def('_COURSE_AS')) . ' :</th><td>' . $quantity . '</td></tr>';
             }
             //end foreach
         }
         $query = "SELECT c.idMetaCertificate, m.idCertificate" . " FROM " . $GLOBALS['prefix_lms'] . "_certificate_meta_course as c" . " JOIN " . $GLOBALS['prefix_lms'] . "_certificate_meta as m ON c.idMetaCertificate = m.idMetaCertificate" . " WHERE c.idUser = '******'" . " GROUP BY c.idMetaCertificate" . " ORDER BY m.title, m.description";
         $result = sql_query($query);
         $num_meta_cert = mysql_num_rows($result);
         while (list($id_meta, $id_certificate) = sql_fetch_row($result)) {
             $query_released = "SELECT on_date" . " FROM " . $GLOBALS['prefix_lms'] . "_certificate_meta_assign" . " WHERE idUser = '******'" . " AND idMetaCertificate = '" . $id_meta . "'";
             $result_released = sql_query($query_released);
             $query = "SELECT user_release" . " FROM " . $GLOBALS['prefix_lms'] . "_certificate" . " WHERE id_certificate = '" . $id_certificate . "'";
             list($user_release) = sql_fetch_row(sql_query($query));
             if (mysql_num_rows($result_released)) {
             } elseif ($user_release == 0) {
                 $num_meta_cert--;
             } else {
                 $query = "SELECT idCourse" . " FROM " . $GLOBALS['prefix_lms'] . "_certificate_meta_course" . " WHERE idUser = '******'" . " AND idMetaCertificate = '" . $id_meta . "'";
                 $result_int = sql_query($query);
                 $control = true;
                 while (list($id_course) = sql_fetch_row($result_int)) {
                     $query = "SELECT COUNT(*)" . " FROM " . $GLOBALS['prefix_lms'] . "_courseuser" . " WHERE idCourse = '" . $id_course . "'" . " AND idUser = '******'" . " AND status = '" . _CUS_END . "'";
                     list($number) = sql_fetch_row(sql_query($query));
                     if (!$number) {
                         $control = false;
                     }
                 }
                 if (!$control) {
                     $num_meta_cert--;
                 }
             }
         }
         $tot_cert = $num_meta_cert + $course_stats['cert_relesable'];
         $html .= '' . (isset($course_stats['cert_relesable']) && $tot_cert != 0 ? '<tr><th scope="row">' . $this->_lang->def('_CERT_RELESABLE') . ' :</th><td><a href="index.php?modname=mycertificate&amp;op=mycertificate">' . $tot_cert . '</a></td></tr>' : '') . ($pendent != 0 ? '<tr><th scope="row">' . $this->_lang->def('_FRIEND_PENDENT') . ' :</th><td><a href="index.php?modname=myfriends&amp;op=myfriends">' . $pendent . '</a></td></tr>' : '') . '</table>' . '</div>' . '</div>' . '</div>';
     }
     /*
     		$html = '<div class="user_presentation">'."\n"
     
     			.( $intest
     				? '<div class="mini_block">'."\n\t"
     						.'<h1>'."\n\t\t"
     							.$this->_lang->def('_WELCOME').'<br/>'."\n\t\t"
     							.'<span>'.$this->resolveUsername().'</span>'."\n\t"
     						.'</h1>'."\n\t"
     						.'<div class="spacer"></div>'."\n\t"
     					.'</div>'."\n"
     
     				: '' );
     
     		if($this->_user_profile->useAvatar()) {
     			$html .= '<div class="mini_block avatar_photo">'."\n\t";
     		}
     		if($this->_user_profile->useAvatar()) {
     
     			$html .= '<p>'."\n\t"
     						.( ($this->user_info[ACL_INFO_AVATAR] != "")
     							? $this->getPASrc($this->user_info[ACL_INFO_AVATAR], $this->_lang->def('_AVATAR'), 'boxed')
     							: '<img class="boxed" src="'.getPathImage().'standard/user.png" alt="'.$this->_lang->def('_NOAVATAR').'" />' )."\n\t\t"
     						.'<br />'."\n\t\t"
     						.$this->_lang->def('_AVATAR')."\n\t\t"
     					.'</p>'."\n\t";
     		}
     		if($this->_user_profile->useAvatar()) {
     
     			$html .= '<div class="nofloat"></div>'."\n\t"
     					.'<div class="spacer"></div>'."\n"
     					.'</div>'."\n";
     		}
     
     		$html .= '<div class="mini_block">'."\n\t"
     				.'<p class="userinfo">'."\n\t\t"
     					.'<b>'.$this->_lang->def('_USERNAME').':</b> '.$this->acl_man->relativeId($this->user_info[ACL_INFO_USERID])
     				.'</p>'."\n\t"
     				.'<p class="userinfo">'."\n\t\t"
     					.'<b>'.$this->_lang->def('_EMAIL').':</b> '
     					.( $this->user_info[ACL_INFO_EMAIL] !== false
     						? '<a href="mailto:'.$this->user_info[ACL_INFO_EMAIL].'">'.$this->user_info[ACL_INFO_EMAIL].'</a>'
     						: $this->_lang->def('_HIDDEN')
     					)."\n\t"
     				.'</p>'."\n\t"
     			.'</div>'."\n"
     
     		.'</div>'."\n";
     */
     return $html;
 }
Example #24
0
$provider = isset($_GET['provider']) ? strtolower($_GET['provider']) : '';
$providers = Config::get('auth.providers', array());
unset($providers['yahoo']);
if (array_key_exists($provider, $providers) && !isset($_GET['error']) && !isset($_GET['denied'])) {
    if (Auth::check() && isset($_GET['disconnect'])) {
        Usermeta::delete(Auth::user()->id, "{$provider}_id");
        Usermeta::delete(Auth::user()->id, "{$provider}_avatar");
        Usermeta::delete(Auth::user()->id, 'avatar_type', $provider);
        Usermeta::delete(Auth::user()->id, "{$provider}_profile");
        redirect_to($settingsPage);
    }
    Session::delete('oauth_user');
    $credentials = new OAuth\Common\Consumer\Credentials(Config::get("services.{$provider}.id"), Config::get("services.{$provider}.secret"), App::url("oauth.php?provider={$provider}"));
    $scope = isset($scopes[$provider]) ? $scopes[$provider] : array();
    $storage = new OAuth\Common\Storage\Session();
    $factory = new OAuth\ServiceFactory();
    // Use cURL
    // $factory->setHttpClient(new OAuth\Common\Http\Client\CurlClient);
    $service = $factory->createService($provider, $credentials, $storage, $scope);
    if ($provider == 'twitter') {
        if (empty($_GET['oauth_token'])) {
            $oauth_token = $service->requestRequestToken()->getRequestToken();
            $authUrl = $service->getAuthorizationUri(compact('oauth_token'));
        } else {
            try {
                $token = $storage->retrieveAccessToken(ucfirst($provider));
                $service->requestAccessToken(@$_GET['oauth_token'], @$_GET['oauth_verifier'], $token->getRequestTokenSecret());
            } catch (Exception $e) {
            }
        }
    } else {
Example #25
0
require_once __DIR__ . '/../../settings.php';
if (!is_file(__DIR__ . '/twitter-settings.php')) {
    die('Please copy twitter-settings.php.dist to twitter-settings.php');
}
//requiring social app configuration
require_once __DIR__ . '/twitter-settings.php';
// token storage
$storage = new OAuth\Common\Storage\Session();
// current uri
$uriFactory = new OAuth\Common\Http\Uri\UriFactory();
$currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER);
$currentUri->setQuery('');
// Setup the credentials for the requests
$credentials = new OAuth\Common\Consumer\Credentials($twitter['key'], $twitter['secret'], $currentUri->getAbsoluteUri());
// Instantiate the Twitter service using the credentials, http client and storage mechanism for the token
$serviceFactory = new OAuth\ServiceFactory();
$client = new OAuth\Common\Http\Client\CurlClient();
$client->setCurlParameters(array(CURLOPT_ENCODING => ''));
$serviceFactory->setHttpClient($client);
$twitterService = $serviceFactory->createService('twitter', $credentials, $storage);
if (!empty($_GET['oauth_token'])) {
    $twitterToken = $storage->retrieveAccessToken('Twitter');
    // This was a callback request from twitter, get the token
    $token = $twitterService->requestAccessToken($_GET['oauth_token'], $_GET['oauth_verifier'], $twitterToken->getRequestTokenSecret());
    //Instantiates the API object
    $api = Veridu\API::factory($veridu['client'], $veridu['secret'], $veridu['version']);
    /*
     * Creates new a read/write Veridu session
     * More info: https://veridu.com/wiki/SSO_Resource#How_to_do_a_social_single_sign_on
     */
    $api->session->create(false);
Example #26
0
// This is to use external domain name found into config file
//$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
$action = GETPOST('action', 'alpha');
$backtourl = GETPOST('backtourl', 'alpha');
/**
 * Create a new instance of the URI class with the current URI, stripping the query string
 */
$uriFactory = new \OAuth\Common\Http\Uri\UriFactory();
//$currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER);
//$currentUri->setQuery('');
$currentUri = $uriFactory->createFromAbsolute($urlwithroot . '/core/modules/oauth/google_oauthcallback.php');
/**
 * Load the credential for the service
 */
/** @var $serviceFactory \OAuth\ServiceFactory An OAuth service factory. */
$serviceFactory = new \OAuth\ServiceFactory();
$httpClient = new \OAuth\Common\Http\Client\CurlClient();
// TODO Set options for proxy and timeout
// $params=array('CURLXXX'=>value, ...)
//$httpClient->setCurlParameters($params);
$serviceFactory->setHttpClient($httpClient);
// Dolibarr storage
$storage = new DoliStorage($db, $conf);
// Setup the credentials for the requests
$credentials = new Credentials($conf->global->OAUTH_GOOGLE_ID, $conf->global->OAUTH_GOOGLE_SECRET, $currentUri->getAbsoluteUri());
$requestedpermissionsarray = array();
if (GETPOST('state')) {
    $requestedpermissionsarray = explode(',', GETPOST('state'));
}
// Example: 'userinfo_email,userinfo_profile,cloud_print'. 'state' parameter is standard to retrieve some parameters back
if ($action != 'delete' && empty($requestedpermissionsarray)) {
Example #27
0
/**
 * @Project NUKEVIET 4.x
 * @Author VINADES.,JSC (contact@vinades.vn)
 * @Copyright (C) 2014 VINADES.,JSC. All rights reserved
 * @License GNU/GPL version 2 or any later version
 * @Createdate Sun, 26 Oct 2014 08:34:25 GMT
 */
if (!defined('NV_IS_MOD_USER')) {
    die('Stop!!!');
}
use OAuth\OAuth2\Service\Facebook;
use OAuth\Common\Storage\Session;
use OAuth\Common\Consumer\Credentials;
// Session storage
$storage = new Session();
$serviceFactory = new \OAuth\ServiceFactory();
// Setup the credentials for the requests
$credentials = new Credentials($global_config['facebook_client_id'], $global_config['facebook_client_secret'], NV_MAIN_DOMAIN . NV_BASE_SITEURL . 'index.php?' . NV_LANG_VARIABLE . '=' . NV_LANG_DATA . '&' . NV_NAME_VARIABLE . '=' . $module_name . '&' . NV_OP_VARIABLE . '=oauth&server=facebook');
// Instantiate the Facebook service using the credentials, http client and storage mechanism for the token
/** @var $facebookService Facebook */
$facebookService = $serviceFactory->createService('facebook', $credentials, $storage, array('email', 'user_photos'));
if (!empty($_GET['code'])) {
    // This was a callback request from facebook, get the token
    $token = $facebookService->requestAccessToken($_GET['code']);
    // Send a request with it
    $result = json_decode($facebookService->request('/me?fields=id,name,email'), true);
    if (isset($result['email'])) {
        $attribs = array('identity' => $result['link'], 'result' => 'is_res', 'id' => $result['id'], 'contact/email' => $result['email'], 'namePerson/first' => $result['first_name'], 'namePerson/last' => $result['last_name'], 'namePerson' => $result['name'], 'person/gender' => $result['gender'], 'server' => $server, 'picture_url' => 'https://graph.facebook.com/' . $result['id'] . '/picture?width=' . $global_config['avatar_width'] . '&height=' . $global_config['avatar_height'] . '&access_token=' . $token, 'picture_mode' => 0, 'current_mode' => 3);
    } else {
        $attribs = array('result' => 'notlogin');
    }
/**
 * @Project NUKEVIET 4.x
 * @Author VINADES.,JSC (contact@vinades.vn)
 * @Copyright (C) 2014 VINADES.,JSC. All rights reserved
 * @License GNU/GPL version 2 or any later version
 * @Createdate Sun, 26 Oct 2014 08:34:25 GMT
 */
if (!defined('NV_IS_MOD_USER')) {
    die('Stop!!!');
}
use OAuth\OAuth2\Service\NukeViet;
use OAuth\Common\Storage\Session;
use OAuth\Common\Consumer\Credentials;
// Session storage
$storage = new Session();
$serviceFactory = new \OAuth\ServiceFactory();
// Setup the credentials for the requests
$credentials = new Credentials('145770550207935', 'gqzwvrhc9oqqkvyzeqrk1tiph3ldqhn3', NV_MAIN_DOMAIN . NV_BASE_SITEURL . 'index.php?' . NV_LANG_VARIABLE . '=' . NV_LANG_DATA . '&' . NV_NAME_VARIABLE . '=' . $module_name . '&' . NV_OP_VARIABLE . '=oauth&server=oauthnkv');
// Instantiate the NukeViet service using the credentials, http client and storage mechanism for the token
$NukeVietService = $serviceFactory->createService('nukeviet', $credentials, $storage, array(), NULL);
// Error
if ($nv_Request->isset_request('error', 'get')) {
    $error = $nv_Request->get_title('error', 'get', '');
    $error_description = $nv_Request->get_title('error_description', 'get', '');
    if (!empty($error_description)) {
        $error .= ': ' . $error_description;
    }
    $nv_redirect = nv_url_rewrite(NV_BASE_SITEURL . 'index.php?' . NV_LANG_VARIABLE . '=' . NV_LANG_DATA . '&amp;' . NV_NAME_VARIABLE . '=' . $module_name, true);
    user_info_exit_redirect($error, $nv_redirect);
}
if (!empty($_GET['code'])) {
Example #29
0
 /**
  * Returns a new service object
  *
  * @param	string	$service_name			The name of the service
  * @param	\phpbb\auth\provider\oauth\token_storage $storage
  * @param	array	$service_credentials	{@see \phpbb\auth\provider\oauth\oauth::get_service_credentials}
  * @param	string	$query					The query string of the
  *											current_uri used in redirection
  * @param	array	$scopes					The scope of the request against
  *											the api.
  * @return	\OAuth\Common\Service\ServiceInterface
  * @throws	\Exception
  */
 protected function get_service($service_name, \phpbb\auth\provider\oauth\token_storage $storage, array $service_credentials, $query, array $scopes = array())
 {
     $current_uri = $this->get_current_uri($service_name, $query);
     // Setup the credentials for the requests
     $credentials = new Credentials($service_credentials['key'], $service_credentials['secret'], $current_uri->getAbsoluteUri());
     $service_factory = new \OAuth\ServiceFactory();
     $service = $service_factory->createService($service_name, $credentials, $storage, $scopes);
     if (!$service) {
         throw new \Exception('AUTH_PROVIDER_OAUTH_ERROR_SERVICE_NOT_CREATED');
     }
     return $service;
 }
Example #30
0
 /**
  * Initializes the OAuth service
  * The service is created by \OAuth\ServiceFactory upon service name returned from getServiceName() method
  *
  * @return $this
  */
 public function init()
 {
     $serviceFactory = new \OAuth\ServiceFactory();
     $serviceFactory->setHttpClient(new CurlClient());
     $this->service = $serviceFactory->createService($this->getServiceName(), $this->credentials, $this->sessionStorage, $this->scopes);
     return $this;
 }