/** * @param array $params * @throws Exception */ public function authenticate(array $params) { if (!isset($params['code']) || empty($params['code'])) { throw new Exception('Authentication failed, invalid or empty code.'); } $oAuthConf = Config::$a['oauth']['providers'][$this->authProvider]; $client = new \OAuth2\Client($oAuthConf['clientId'], $oAuthConf['clientSecret'], \OAuth2\Client::AUTH_TYPE_AUTHORIZATION_BASIC); $client->setAccessTokenType(\OAuth2\Client::ACCESS_TOKEN_BEARER); $response = $client->getAccessToken('https://ssl.reddit.com/api/v1/access_token', 'authorization_code', array('redirect_uri' => sprintf(Config::$a['oauth']['callback'], $this->authProvider), 'code' => $params['code'])); if (empty($response) || isset($response['error'])) { throw new Exception('Invalid access_token response'); } if (!isset($response['result']) || empty($response['result']) || !isset($response['result']['access_token'])) { throw new Exception('Failed request for access token'); } $client->setAccessToken($response['result']['access_token']); // Reddit requires a User-Agent $info = $client->fetch("https://oauth.reddit.com/api/v1/me.json", array(), 'GET', array('User-Agent' => 'destiny.gg/' . Config::version())); if (empty($info['result']) || !is_array($info['result']) || isset($info['error'])) { throw new Exception('Invalid user details response'); } $authCreds = $this->getAuthCredentials($params['code'], $info['result']); $authCredHandler = new AuthenticationRedirectionFilter(); return $authCredHandler->execute($authCreds); }
/** * @param array $params * @throws Exception */ public function authenticate(array $params, ViewModel $model) { if (!isset($params['code']) || empty($params['code'])) { throw new Exception('Authentication failed, invalid or empty code.'); } $oAuthConf = Config::$a['oauth']['providers'][$this->authProvider]; $client = new \OAuth2\Client($oAuthConf['clientId'], $oAuthConf['clientSecret']); $client->setAccessTokenType(\OAuth2\Client::ACCESS_TOKEN_OAUTH); $response = $client->getAccessToken('https://api.twitch.tv/kraken/oauth2/token', 'authorization_code', array('redirect_uri' => sprintf(Config::$a['oauth']['callback'], $this->authProvider), 'code' => $params['code'])); if (empty($response) || isset($response['error'])) { throw new Exception('Invalid access_token response'); } if (!isset($response['result']) || empty($response['result']) || !isset($response['result']['access_token'])) { throw new Exception('Failed request for access token'); } $client->setAccessToken($response['result']['access_token']); $response = $client->fetch('https://api.twitch.tv/kraken/user'); if (empty($response['result']) || isset($response['error'])) { throw new Exception('Invalid user details response'); } if (is_string($response['result'])) { throw new Exception(sprintf('Invalid auth result %s', $response['result'])); } $authCreds = $this->getAuthCredentials($params['code'], $response['result']); $authCredHandler = new AuthenticationRedirectionFilter(); return $authCredHandler->execute($authCreds); }
public function callbackAction() { $callback_url = Mage::getUrl('gomage_social/reddit/callback', array('_secure' => true)); $client = new OAuth2\Client(Mage::getStoreConfig('gomage_social/reddit/id'), Mage::getStoreConfig('gomage_social/reddit/secret'), OAuth2\Client::AUTH_TYPE_AUTHORIZATION_BASIC); $params = array("code" => $this->getRequest()->getParam('code'), "redirect_uri" => $callback_url); if ($params['code']) { $response = $client->getAccessToken($this->accessTokenUrl, "authorization_code", $params); $accessTokenResult = $response["result"]; $client->setAccessToken($accessTokenResult["access_token"]); $client->setAccessTokenType(OAuth2\Client::ACCESS_TOKEN_BEARER); $response = (object) $client->fetch("https://oauth.reddit.com/api/v1/me.json"); $profile = null; switch ($response->code) { case 200: $profile = (object) $response->result; break; default: $this->getSession()->addError($this->__('Could not connect to Reddit. Refresh the page or try again later.')); return $this->_redirectUrl(); } if ($profile) { if ($profile->id) { $social_collection = Mage::getModel('gomage_social/entity')->getCollection()->addFieldToFilter('social_id', $profile->id)->addFieldToFilter('type_id', GoMage_Social_Model_Type::REDDIT); if (Mage::getSingleton('customer/config_share')->isWebsiteScope()) { $social_collection->addFieldToFilter('website_id', Mage::app()->getWebsite()->getId()); } $social = $social_collection->getFirstItem(); if ($social && $social->getId()) { if ($social->social_id == $profile->id) { $customer = Mage::getModel('customer/customer'); if (Mage::getSingleton('customer/config_share')->isWebsiteScope()) { $customer->setWebsiteId(Mage::app()->getWebsite()->getId()); } $customer->load($social->getData('customer_id')); if ($customer && $customer->getId()) { if (!$customer->getConfirmation()) { $this->getSession()->loginById($customer->getId()); } else { $this->getSession()->addError($this->__('This account is not confirmed.')); } } } } else { $profile->url = Mage::getUrl('gomage_social/reddit/checkEmail', array('_secure' => true)); $profile->urlEmailClose = Mage::getUrl('gomage_social/twitter/emailClose', array('_secure' => true)); $profile->type_id = GoMage_Social_Model_Type::REDDIT; Mage::getSingleton('core/session')->setGsProfile($profile); } } } } return $this->_redirectUrl(); }
/** * index method * * This is target method after user confirms and approves google API access * * @return void */ public function index() { $this->autoRender = false; if (empty($this->request->query['code'])) { die('No code!'); } $params = array('code' => $this->request->query['code'], 'redirect_uri' => Router::url(array('prefix' => false, 'plugin' => 'lil_crm', 'controller' => 'oauth', 'action' => 'index'), true)); $client = new OAuth2\Client(Configure::read('LilCrm.googleApiClientId'), Configure::read('LilCrm.googleApiClientSecret')); $response = $client->getAccessToken('https://accounts.google.com/o/oauth2/token', 'authorization_code', $params); if ($response['code'] == 200) { $Contact = ClassRegistry::init('LilCrm.Contact'); $Contact->id = $this->currentUser->get('id'); $Contact->saveField('oauth_token', $response['result']['refresh_token']); var_dump($response['result']['refresh_token']); } debug($response); }
/** * Attempts to get an access token. * * @return * TRUE if an access token was retrieved; FALSE otherwise. */ public function getAccessToken() { // Configure the OAuth2 client. $oauth2_config = array('auth_flow' => 'user-password', 'token_endpoint' => variable_get('oauth2_authentication_token_endpoint', ''), 'client_id' => variable_get('oauth2_authentication_client_id', ''), 'client_secret' => variable_get('oauth2_authentication_client_secret', ''), 'scope' => variable_get('oauth2_authentication_scope', ''), 'username' => $this->username, 'password' => $this->password); try { // Create an OAuth2 client and attempt to get an access token. If we // aren't able to, we'll end up in the catch stanza as an exception will // be thrown. $oauth2_client = new OAuth2\Client($oauth2_config); $token = $oauth2_client->getAccessToken(); $token_retrieved = isset($token); } catch (Exception $e) { // We couildn't get an access token for this user so it must not be valid. $token_retrieved = FALSE; } // Report status in the log. watchdog('oauth2_authentication', 'Access token requested for user %name: !result', array('%name' => $this->username, '!result' => $token_retrieved ? 'SUCCESS' : 'FAILURE')); // Return the result. return $token_retrieved; }
/** * @param array $params * @throws Exception */ public function authenticate(array $params) { if (!isset($params['code']) || empty($params['code'])) { throw new Exception('Authentication failed, invalid or empty code.'); } $authConf = Config::$a['oauth']['providers'][$this->authProvider]; $callback = sprintf(Config::$a['oauth']['callback'], $this->authProvider); $client = new \OAuth2\Client($authConf['clientId'], $authConf['clientSecret']); $response = $client->getAccessToken('https://accounts.google.com/o/oauth2/token', 'authorization_code', array('redirect_uri' => $callback, 'code' => $params['code'])); if (empty($response) || isset($response['error'])) { throw new Exception('Invalid access_token response'); } if (!isset($response['result']) || empty($response['result']) || !isset($response['result']['access_token'])) { throw new Exception('Failed request for access token'); } $client->setAccessToken($response['result']['access_token']); $response = $client->fetch('https://www.googleapis.com/oauth2/v2/userinfo'); if (empty($response['result']) || isset($response['error'])) { throw new Exception('Invalid user details response'); } $authCreds = $this->getAuthCredentials($params['code'], $response['result']); $authCredHandler = new AuthenticationRedirectionFilter(); return $authCredHandler->execute($authCreds); }
/** * Called by GitHub - set the access token as cookie and redirect to URL specified by client */ function github_get_auth_callback($param = array()) { if (empty($param['code'])) { // Required parameter code missing or empty // see https://developer.github.com/v3/oauth/#web-application-flow setcookie('github_access_token', NULL, -1); @header('Location: ' . (!empty($param['target']) ? $param['target'] : base_url())); die; } // ask GitHub for access token $client = new OAuth2\Client(config('github_client_id'), config('github_client_secret')); $response = $client->getAccessToken('https://github.com/login/oauth/access_token', 'authorization_code', array('code' => $param['code'], 'redirect_uri' => '')); // parse response parse_str($response['result'], $oauth_param); if (empty($oauth_param['access_token'])) { // Expected parameter access_token missing or empty // see print_r($response, true) setcookie('github_access_token', NULL, -1); } else { setcookie('github_access_token', $oauth_param['access_token']); } @header('Location: ' . (!empty($param['target']) ? $param['target'] : base_url())); die; }
die; //?state=SomeUnguessableValue&code=ki4tr-_EAXNXVrhWMcQ5a5pLm0o } $authorizeUrl = 'https://ssl.reddit.com/api/v1/authorize'; $accessTokenUrl = 'https://ssl.reddit.com/api/v1/access_token'; $clientId = 'jJgLD5ebMOT9sw'; $clientSecret = 'muldwiysWI2ok2KWNmoiDK6FMKw'; $userAgent = 'ChangeMeClient/0.1 by YourUsername'; $redirectUrl = "http://brittanyannkos.com/reddit"; require "OAuth2/Client.php"; require "OAuth2/GrantType/IGrantType.php"; require "OAuth2/GrantType/AuthorizationCode.php"; $client = new OAuth2\Client($clientId, $clientSecret, OAuth2\Client::AUTH_TYPE_AUTHORIZATION_BASIC); $client->setCurlOption(CURLOPT_USERAGENT, $userAgent); $_GET["code"] = "ki4tr-_EAXNXVrhWMcQ5a5pLm0o"; if (!isset($_GET["code"])) { $authUrl = $client->getAuthenticationUrl($authorizeUrl, $redirectUrl, array("scope" => "identity", "state" => "SomeUnguessableValue", "duration" => "permanent")); header("Location: " . $authUrl); die("Redirect"); } else { $params = array("code" => $_GET["code"], "redirect_uri" => $redirectUrl); $response = $client->getAccessToken($accessTokenUrl, "authorization_code", $params); $accessTokenResult = $response["result"]; print_r($accessTokenResult); $client->setAccessToken($accessTokenResult["access_token"]); $client->setAccessTokenType(OAuth2\Client::ACCESS_TOKEN_BEARER); $response = $client->fetch("https://oauth.reddit.com/api/v1/me.json"); echo '<strong>Response for fetch me.json:</strong><pre>'; print_r($response); echo '</pre>'; }
$url = $protocol . $_SERVER["HTTP_HOST"] . $_SERVER['REQUEST_URI']; //DECONNEXION if (isset($_GET['reset'])) { unset($_SESSION['access_token']); header('Content-type: application/json'); echo json_encode(array(DISCONNECT_PAGE)); } elseif (!empty($_SESSION['access_token'])) { $client->setAccessToken($_SESSION['access_token']); $profile = $client->fetch(PROFILE_PAGE); } elseif (empty($_GET['code'])) { $auth_url = $client->getAuthenticationUrl(AUTHORIZATION_ENDPOINT, $url); header('Location: ' . $auth_url); die('Redirect'); } else { $params = array('code' => $_GET['code'], 'redirect_uri' => $url); $response = $client->getAccessToken(TOKEN_ENDPOINT, 'authorization_code', $params); if (isset($response['result']) && isset($response['result']['access_token'])) { $client->setAccessToken($response['result']['access_token']); $_SESSION['access_token'] = $response['result']['access_token']; $client->setAccessToken($_SESSION['access_token']); $profile = $client->fetch(PROFILE_PAGE); } else { die('Une erreur est survenue lors de l’identification'); } } /******************************************************************************* * RETURNS RESULTS ******************************************************************************/ if (!empty($profile)) { $result = json_encode($profile['result']); // echo $result;
* Oauth2 Process * * 1. Ask user to authorize by redirecting them to the authorization endpoint on DA * 2. Once user authorizes DA will send back an authoirzation code ($_GET['code']) * 3. We then use the code to get an access_token * 4. We use the access_token to access an API endpoint */ try { $client = new OAuth2\Client(CLIENT_ID, CLIENT_SECRET, OAuth2\Client::AUTH_TYPE_AUTHORIZATION_BASIC); if (!isset($_REQUEST['code'])) { $auth_url = $client->getAuthenticationUrl(AUTHORIZATION_ENDPOINT, REDIRECT_URI); header('Location: ' . $auth_url); die('Redirecting ...'); } else { $params = array('code' => $_REQUEST['code'], 'redirect_uri' => REDIRECT_URI); $response = $client->getAccessToken(TOKEN_ENDPOINT, OAuth2\Client::GRANT_TYPE_AUTH_CODE, $params); $val = (object) $response['result']; if (!$val->access_token) { throw new Exception("No access token returned: " . $val->error_description); } $client->setAccessToken($val->access_token); $client->setAccessTokenType(OAuth2\Client::ACCESS_TOKEN_OAUTH); // Submit a file first $response = $client->fetch(SUBMIT_API, array('title' => 'Fella Sample Image', 'artist_comments' => 'Fella Sample Image', 'keywords' => 'fella sample image', 'folder' => APPNAME, 'file' => "@fella.png"), OAuth2\Client::HTTP_METHOD_POST); $result = (object) $response['result']; if (!$result) { throw new Exception('No valid JSON response returned'); } if ($result->status != 'success') { throw new Exception($result->error_description); }
<?php require_once __DIR__ . '/../vendor/autoload.php'; use PositionlyApi\PositionlyApi; require '_credentials.php'; $client = new OAuth2\Client($clientId, $clientSecret); $authorizationParams = array('username' => $username, 'password' => $password); $result = $client->getAccessToken(PositionlyApi::getTokenEndpoint(), 'password', $authorizationParams); $accessToken = json_decode($result['result'], true); $client->setAccessToken($accessToken['access_token']); $api = new PositionlyApi($client); // get accounts $response = $api->call('/accounts'); // get first account id $accountId = $response->getResult()[0]['id']; // get first website id $response = $api->call(sprintf('/accounts/%s/websites', $accountId)); $websiteId = $response->getResult()[0]['id']; // get first keyword id $response = $api->call(sprintf('/accounts/%s/websites/%s/keywords', $accountId, $websiteId)); $keywordId = $response->getResult()[0]['id']; $engineId = 43; // google polska $response = $api->call(sprintf('/accounts/%s/websites/%s/engines/%s/keywords/%s/positions', $accountId, $websiteId, $engineId, $keywordId)); if ($response->isSuccess()) { echo 'Success!'; } else { echo 'Failure'; } print_r($response); exit;
/** * User-Login for Facebook * * @param $strUsername * @param $strPassword * @param $boolUseHash Use Hash for comparing * @return bool/array */ public function login($strUsername, $strPassword, $boolUseHash = false) { $blnLoginResult = false; $this->init_oauth(); if ($this->in->get('norelay', 0)) { $code = $_GET['code']; } else { $encrypt = register('encrypt', array($this->eqdkp_appsecret)); $code = $encrypt->decrypt(rawurldecode($_GET['code'])); } if ($code) { $client = new OAuth2\Client($this->appid, $this->appsecret); if ($this->relay) { $time = $this->in->get('t'); $hmac = $this->in->get('h'); $s = $this->in->get('_s') ? '&_s=' . $this->in->get('_s') : ''; $redir_url = $this->RELAY_URL . '?_t=' . $time . '&_id=' . $this->eqdkp_appid . '&_hmac=' . $hmac . $s; } else { $redir_url = $this->env->buildLink() . 'index.php/Login/?login&lmethod=battlenet&norelay=1'; } $params = array('code' => $code, 'redirect_uri' => $redir_url, 'scope' => 'wow.profile'); $response = $client->getAccessToken($this->TOKEN_ENDPOINT, 'authorization_code', $params); if ($response && $response['result']) { if (isset($response['result']['accountId'])) { $userid = $this->pdh->get('user', 'userid_for_authaccount', array($response['result']['accountId'], 'battlenet')); if ($userid) { $userdata = $this->pdh->get('user', 'data', array($userid)); if ($userdata) { list($strPwdHash, $strSalt) = explode(':', $userdata['user_password']); return array('status' => 1, 'user_id' => $userdata['user_id'], 'password_hash' => $strPwdHash, 'autologin' => true, 'user_login_key' => $userdata['user_login_key']); } } } } } return false; }