public function signin() { $client = new \Google_Client(); $client->setClientId(Config::get('ntentan:social.google.client_id')); $client->setClientSecret(Config::get('ntentan:social.google.client_secret')); $client->setRedirectUri(Config::get('ntentan:social.google.redirect_uri')); $client->addScope(array('profile', 'email')); $oauth2 = new \Google_Service_Oauth2($client); if (isset($_REQUEST['logout'])) { Session::set('access_token', ''); $client->revokeToken(); } if (isset($_GET['code'])) { $client->authenticate($_GET['code']); Session::set('access_token', $client->getAccessToken()); Redirect::path(\ntentan\Router::getRoute()); } if (isset($_SESSION['access_token'])) { $client->setAccessToken($_SESSION['access_token']); } if ($client->isAccessTokenExpired()) { $authUrl = $client->createAuthUrl(); header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL)); } if ($client->getAccessToken()) { $user = $oauth2->userinfo->get(); $_SESSION['token'] = $client->getAccessToken(); return array('firstname' => $user['given_name'], 'lastname' => $user['family_name'], 'key' => "google_{$user['id']}", 'avatar' => $user['picture'], 'email' => $user['email'], 'email_confirmed' => $user['verified_email']); } else { header("Location: {$client->createAuthUrl()}"); die; } return false; }
public function revokeToken() { $this->client->revokeToken(); $this->accessToken = ''; $this->refreshToken = ''; $this->settings['googledrive_app_current_token'] = ''; $this->settings['googledrive_app_refresh_token'] = ''; update_option('use_your_drive_lists', array()); update_option('use_your_drive_cache', array('last_update' => null, 'last_cache_id' => '', 'locked' => false, 'cache' => '')); update_option('use_your_drive_settings', $this->settings); return true; }
public function logout($token) { $client = new Google_Client(); $token = base64_decode($token); $client->setAccessToken($token); return $client->revokeToken(); }
/** * Permet de déconnecter la personne de son compte Google * @param User $user * @return bool */ public function disconnect(User $user) { if (null != $this->client->getAccessToken()) { $tokenObject = json_decode($this->client->getAccessToken()); $token = $tokenObject->access_token; $response = $this->client->revokeToken($token); if (true !== $response) { return false; } } $session = new Session(); $session->remove('access_token'); $user->setGoogleRefreshToken(null); // $this->googleCalendarManager->removeAllGoogleCalendar($user); $this->em->flush(); return true; }
public function GoogleUser() { $client = new \Google_Client(); $client->setApplicationName(\SKT_GOOGLEOAUTH2_SETAPPLICATIONNAME); // Visit https://code.google.com/apis/console?api=plus to generate your // oauth2_client_id, oauth2_client_secret, and to register your oauth2_redirect_uri. $client->setClientId(\SKT_GOOGLEOAUTH2_SETCLIENTID); $client->setClientSecret(\SKT_GOOGLEOAUTH2_SETCLIENTSECRET); $client->setRedirectUri(\SKT_GOOGLEOAUTH2_SETREDIRECTURI); $client->setDeveloperKey(\SKT_GOOGLEOAUTH2_SETDEVELOPERKEY); $oauth2 = new \Google_Oauth2Service($client); if (isset($_GET['code'])) { $client->authenticate($_GET['code']); $_SESSION['token'] = $client->getAccessToken(); $redirect = \SITE_SERVER; \CmsDev\Header\refresh::refreshNow(\filter_var($redirect, FILTER_SANITIZE_URL)); return; } if (isset($_SESSION['token'])) { $client->setAccessToken($_SESSION['token']); } if (isset($_REQUEST['logout']) or \THIS_URL_REAL === 'UserLogout') { unset($_SESSION['token']); $client->revokeToken(); } if ($client->getAccessToken()) { $user = $oauth2->userinfo->get(); // These fields are currently filtered through the PHP sanitize filters. // See http://www.php.net/manual/en/filter.filters.sanitize.php $this->family_name = filter_var($user['family_name'], \FILTER_SANITIZE_STRING); $this->name = filter_var($user['name'], \FILTER_SANITIZE_STRING); $this->locale = filter_var($user['locale'], \FILTER_SANITIZE_STRING); $this->gender = filter_var($user['gender'], \FILTER_SANITIZE_STRING); $this->email = filter_var($user['email'], \FILTER_SANITIZE_EMAIL); $this->link = filter_var($user['link'], \FILTER_SANITIZE_URL); $this->given_name = filter_var($user['given_name'], \FILTER_SANITIZE_STRING); $this->id = filter_var($user['id'], \FILTER_SANITIZE_STRING); $this->verified_email = filter_var($user['verified_email'], \FILTER_SANITIZE_STRING); if (isset($user['picture']) && $user['picture'] != '') { $this->picture = filter_var($user['picture'], \FILTER_VALIDATE_URL); } else { $this->picture = \SKT_ACCESS_AVATAR; } $this->ClientAuth = 'Google'; $_SESSION['token'] = $client->getAccessToken(); $this->createAuthUrl = $client->createAuthUrl(); $this->Info = array('family_name' => HtmlSpecialChars($this->family_name), 'name' => HtmlSpecialChars($this->name), 'locale' => $this->locale, 'gender' => $this->gender, 'email' => $this->email, 'link' => $this->link, 'given_name' => HtmlSpecialChars($this->given_name), 'id' => $this->id, 'verified_email' => $this->verified_email, 'picture' => $this->picture, 'ClientAuth' => $this->ClientAuth, 'createAuthUrl' => $this->createAuthUrl); \CmsDev\Security\UserRegister::checkAction($this->Info); return true; } else { $this->createAuthUrl = $client->createAuthUrl(); new \CmsDev\Url\refer(); return false; } }
/** * @param $staff_id * @return mixed */ public function logoutByStaffId($staff_id) { $staff = new AB_Staff(); $staff->load($staff_id); try { $this->loadByStaff($staff); $this->client->revokeToken(); } catch (Exception $e) { $this->errors[] = $e->getMessage(); } $staff->set('google_data', null); $staff->set('google_calendar_id', null); $staff->save(); return $staff->get('id'); }
/** * Revokes an authorization token. This both revokes the token by making a * Google Accounts API request to revoke the token as well as deleting the * token from the storage mechanism. If any errors occur, the authorization * exception is caught and the message is stored in error. */ public function revokeToken() { $accessToken = $this->storage->get(); if ($accessToken) { $tokenObj = json_decode($accessToken); try { $this->client->revokeToken($tokenObj->refresh_token); $this->storage->delete(); } catch (Google_AuthException $e) { $this->errorMsg = $e->getMessage(); } } // Keep things pretty. Removes the auth code from the URL. header("Location: {$this->controllerUrl}"); }
function cw_googleplus_on_logout() { $googleplus_login_info =& cw_session_register('googleplus_login_info'); unset($googleplus_login_info['token']); $google_client_id = '376787991969-2c127o3n2vollhqfla26q1mfu1qi7n8s.apps.googleusercontent.com'; $google_client_secret = '25mdbO_DAlPE_aST_hErSzDN'; $google_redirect_url = 'http://dev.cartworks.com/product_stages/index.php'; //path to your script $google_developer_key = 'AIzaSyAOCvjaVfFFiL4OnlI8du8pHHNZGPsY3iU'; cw_include('addons/googleplus_login/include/src/Google_Client.php'); cw_include('addons/googleplus_login/include/src/contrib/Google_Oauth2Service.php'); $gClient = new Google_Client(); $gClient->setApplicationName('Test Google+ Login CW'); $gClient->setClientId($google_client_id); $gClient->setClientSecret($google_client_secret); $gClient->setRedirectUri($google_redirect_url); $gClient->setDeveloperKey($google_developer_key); $gClient->revokeToken(); }
/** * Function to revoke the application access to google account. Dumn revoke process - revokes all your account access. * @param array ['user_id'=> user id, 'media_id'=> social media id] * @return boolean true|false * @throws \Google_Exception if user id or media id are missed */ public function RevokeAccess($params) { $USER_ID = isset($params[self::USER_ID]) ? $params[self::USER_ID] : null; $GOOGLE_MEDIA_ID = isset($params[self::MEDIA_ID]) ? $params[self::MEDIA_ID] : null; if (!isset($USER_ID) || !isset($GOOGLE_MEDIA_ID)) { throw new \Google_Exception('User ID and / or Google Media ID are invalid'); } $oMediaUserMapper = new \Av\MediaUserModel(); $params_user_credentials = array(\Av\MediaUserModel::MEDIA_ID => $GOOGLE_MEDIA_ID, \Av\MediaUserModel::USER_ID => $USER_ID); $arrUserCredentials = $oMediaUserMapper->GetCredentials($params_user_credentials); if (empty($arrUserCredentials[\Av\MediaUserModel::REFRESH_TOKEN])) { throw new \Google_Exception("Refresh token is not set for user id {$USER_ID} media id {$GOOGLE_MEDIA_ID} "); } if (empty($arrUserCredentials[\Av\MediaUserModel::ACCESS_TOKEN])) { throw new \Google_Exception("Access token is not set for user id {$USER_ID} media id {$GOOGLE_MEDIA_ID} "); } // 3. Extract access token // $ACCESS_TOKEN = $arrUserCredentials[\Av\MediaUserModel::ACCESS_TOKEN]; $REFRESH_TOKEN = $arrUserCredentials[\Av\MediaUserModel::REFRESH_TOKEN]; $client = new \Google_Client(); return $client->revokeToken($REFRESH_TOKEN); }
public function authenticate($sl) { $response = null; $config = $sl->get('config'); $googleApi = $config['google-api']; $gClient = new \Google_Client(); $gClient->setApplicationName('ginosi'); $gClient->setClientId($googleApi['clientId']); $gClient->setClientSecret($googleApi['clientSecret']); $gClient->setRedirectUri($googleApi['redirectUri']); $gClient->setDeveloperKey($googleApi['developerKey']); $gClient->setScopes($googleApi['scopes']); $google_oauthV2 = new \Google_Service_Oauth2($gClient); if (isset($_REQUEST['reset'])) { unset($_SESSION['token']); $gClient->revokeToken(); header('Location: ' . filter_var($google_redirect_url, FILTER_SANITIZE_URL)); } if (isset($_GET['code'])) { $session = new Container('accesstoken'); $gClient->authenticate($_GET['code']); $accessToken = $gClient->getAccessToken(); $data = \Zend\Json\Json::decode($accessToken, \Zend\Json\Json::TYPE_ARRAY); $session->token = $data['access_token']; } if (isset($accessToken)) { $gClient->setAccessToken($gClient->getAccessToken()); } if ($gClient->getAccessToken()) { $user = $google_oauthV2->userinfo->get(); $email = filter_var($user['email'], FILTER_SANITIZE_EMAIL); $result = ['verified', $email]; return $result; } else { return $gClient->createAuthUrl(); } }
function gmail() { $google_client_id = '268142142707-blppmfbga75qrdlv2r706k4tae91oo4h.apps.googleusercontent.com'; $google_client_secret = '0RXg84sxNKSPOfriAfXvMZcG'; $google_redirect_url = 'http://www.stylior.com/home/gmail/'; //path to your script $google_developer_key = ''; //include google api files require_once 'site/views/src/Google_Client.php'; require_once 'site/views/src/contrib/Google_Oauth2Service.php'; $this->load->library('session'); $gClient = new Google_Client(); $gClient->setApplicationName('Login to stylior.com'); $gClient->setClientId($google_client_id); $gClient->setClientSecret($google_client_secret); $gClient->setRedirectUri($google_redirect_url); $gClient->setDeveloperKey($google_developer_key); $google_oauthV2 = new Google_Oauth2Service($gClient); //If user wish to log out, we just unset Session variable if (isset($_REQUEST['reset'])) { unset($_SESSION['token']); $gClient->revokeToken(); header('Location: ' . filter_var($google_redirect_url, FILTER_SANITIZE_URL)); //redirect user back to page } if (isset($_REQUEST['code'])) { $gClient->authenticate($_REQUEST['code']); $_SESSION['token'] = $gClient->getAccessToken(); } if (isset($_SESSION['token'])) { $gClient->setAccessToken($_SESSION['token']); } if ($gClient->getAccessToken()) { //For logged in user, get details from google using access token $user = $google_oauthV2->userinfo->get(); $user_id = $user['id']; $user_name = filter_var($user['name'], FILTER_SANITIZE_SPECIAL_CHARS); $email = filter_var($user['email'], FILTER_SANITIZE_EMAIL); $profile_url = filter_var($user['link'], FILTER_VALIDATE_URL); $profile_image_url = filter_var($user['picture'], FILTER_VALIDATE_URL); $personMarkup = "{$email}<div><img src='{$profile_image_url}?sz=50'></div>"; $_SESSION['token'] = $gClient->getAccessToken(); } else { //For Guest user, get google login url $authUrl = $gClient->createAuthUrl(); } if (isset($authUrl)) { //echo '<a class="login" href="'.$authUrl.'"><img src="images/google-login-button.png" /></a>'; } else { // print_r($email);die; $userdata = $this->user_model->facebooklogin($email); if ($userdata != '') { $newuserdata = array('username' => $userdata->username, 'userid' => $userdata->id, 'email' => $userdata->email, 'insider' => $userdata->insider, 'logged_in' => true); $check = $this->session->set_userdata($newuserdata); $_SESSION['username'] = $userdata->username; $_SESSION['userid'] = $userdata->id; $_SESSION['email'] = $userdata->email; $_SESSION['insider'] = $userdata->insider; $_SESSION['logged_in'] = true; $customize = $this->session->userdata('customize'); /* code added by MSYS009 */ $cartdata = $this->user_model->cartdata($_SESSION['userid']); if ($cartdata != '' && count($cartdata) > 0) { foreach ($cartdata as $cd) { $optionarr = json_decode($cd->options); foreach ($optionarr as $key => $value) { $optionarr1[$key] = $value; } $data['cartprod'] = array('id' => $cd->pid, 'qty' => $cd->qty, 'price' => $cd->price, 'name' => $cd->pname, 'options' => $optionarr1); $this->cart->insert($data['cartprod']); } } // redirecting to add cart functio based on 3d data selection -- MSYS009 if (isset($_SESSION['selected3dInfo']) && !empty($_SESSION['selected3dInfo'])) { // echo "hihi".$this->config->item('base_url');exit; redirect($this->config->item('base_url') . 'cart/addcart3d', 'location'); } // redirecting to save cart function based on 3d data selection -- MSYS009 if (isset($_SESSION['save3dInfo']) && !empty($_SESSION['save3dInfo'])) { //echo "hihi".$this->config->item('base_url');exit; redirect($this->config->item('base_url') . 'cart/save3d/', 'location'); } /* code added by MSYS009(END) */ if ($customize != '' && $_SESSION['cust_fab_id'] == '') { redirect($this->config->item('http_host') . '/3dshirt?id=' . $customize, 'location'); } if ($_SESSION['customize'] == '1' && $_SESSION['cust_fab_id'] != '') { redirect($this->config->item('http_host') . '3dshirt/index.php?fab_id=' . $_SESSION['cust_fab_id'], 'location'); } if ($_SESSION['customize'] == '1') { redirect($this->config->item('http_host') . '/3dshirt', 'location'); } if ($this->session->userdata('cstyleid') != '' && $this->session->userdata('prodid') != '') { redirect($this->config->item('base_url') . 'home/measurement/' . $this->session->userdata('cstyleid') . '/' . $this->session->userdata('prodid') . '', 'location'); } else { redirect($this->config->item('base_url') . '', 'location'); } } else { $content['email'] = $email; $content['name'] = $user_name; //$content['mobile'] = $user->mobile; $this->user_model->userfacebook($content); $userdata = $this->user_model->facebooklogin($email); $newuserdata = array('username' => $userdata->username, 'userid' => $userdata->id, 'email' => $userdata->email, 'insider' => $userdata->insider, 'logged_in' => true); $check = $this->session->set_userdata($newuserdata); $_SESSION['username'] = $userdata->username; $_SESSION['userid'] = $userdata->id; $_SESSION['email'] = $userdata->email; $_SESSION['insider'] = $userdata->insider; $_SESSION['logged_in'] = true; $format = $this->user_model->getusermail(); $message = $format[0]->regemail; $mysub = $format[0]->regemailsub; $sub = str_replace('{FirstName}', $user->name, $mysub); $message = str_replace('/ckfinder', 'http://www.stylior.com/ckfinder', $message); $subject = $sub; $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; $headers .= 'From: stylior.com <*****@*****.**>' . "\r\n" . 'Reply-To: info@stylior.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); //mail('*****@*****.**', $subject, $message, $headers); mail($format[0]->regemail, $subject, $message, $headers); $customize = $this->session->userdata('customize'); /* code added by MSYS009 */ $cartdata = $this->user_model->cartdata($_SESSION['userid']); if ($cartdata != '' && count($cartdata) > 0) { foreach ($cartdata as $cd) { $optionarr = json_decode($cd->options); foreach ($optionarr as $key => $value) { $optionarr1[$key] = $value; } $data['cartprod'] = array('id' => $cd->pid, 'qty' => $cd->qty, 'price' => $cd->price, 'name' => $cd->pname, 'options' => $optionarr1); $this->cart->insert($data['cartprod']); } } // redirecting to add cart functio based on 3d data selection -- MSYS009 if (isset($_SESSION['selected3dInfo']) && !empty($_SESSION['selected3dInfo'])) { // echo "hihi".$this->config->item('base_url');exit; redirect($this->config->item('base_url') . 'cart/addcart3d', 'location'); } // redirecting to save cart function based on 3d data selection -- MSYS009 if (isset($_SESSION['save3dInfo']) && !empty($_SESSION['save3dInfo'])) { //echo "hihi".$this->config->item('base_url');exit; redirect($this->config->item('base_url') . 'cart/save3d/', 'location'); } /* code added by MSYS009(END) */ if ($customize != '' && $_SESSION['customize'] != '1') { redirect($this->config->item('http_host') . '/3dshirt?id=' . $customize, 'location'); } if ($_SESSION['customize'] == '1') { redirect($this->config->item('http_host') . '/3dshirt', 'location'); } if ($this->session->userdata('cstyleid') != '' && $this->session->userdata('prodid') != '') { redirect($this->config->item('base_url') . 'home/measurement/' . $this->session->userdata('cstyleid') . '/' . $this->session->userdata('prodid') . '', 'location'); } else { redirect($this->config->item('base_url') . '', 'location'); } } } }
if (!file_exists($page_to_load . ".file")) { $page_to_load = "404"; } $_SESSION["page_to_load"] = $page_to_load; $gClient = new Google_Client(); $gClient->setApplicationName('TLV TimeBank'); //Login to Sanwebe.com $gClient->setClientId($google_client_id); $gClient->setClientSecret($google_client_secret); $gClient->setRedirectUri($google_redirect_url); $gClient->setDeveloperKey($google_developer_key); $google_oauthV2 = new Google_Oauth2Service($gClient); //If user wish to log out, we just unset Session variable if (isset($_REQUEST['reset'])) { unset($_SESSION['token']); $gClient->revokeToken(); header('Location: ' . filter_var($google_redirect_url, FILTER_SANITIZE_URL)); //redirect user back to page } //If code is empty, redirect user to google authentication page for code. //Code is required to aquire Access Token from google //Once we have access token, assign token to session variable //and we can redirect user back to page and login. if (isset($_GET['code'])) { $gClient->authenticate($_GET['code']); $_SESSION['token'] = $gClient->getAccessToken(); header('Location: ' . filter_var($google_redirect_url, FILTER_SANITIZE_URL)); return; } if (isset($_SESSION['token'])) { $gClient->setAccessToken($_SESSION['token']);
function K_google() { $ci =& get_instance(); $ci->load->config('google'); $google_client_id = $ci->config->item('google_client_id'); $google_client_secret = $ci->config->item('google_client_secret'); $google_redirect_url = $ci->config->item('google_redirect_url'); //path to your script $google_developer_key = $ci->config->item('google_developer_key'); require_once 'src/Google_Client.php'; require_once 'src/contrib/Google_Oauth2Service.php'; $gClient = new Google_Client(); $gClient->setClientId($google_client_id); $gClient->setClientSecret($google_client_secret); $gClient->setRedirectUri($google_redirect_url); $gClient->setDeveloperKey($google_developer_key); $google_oauthV2 = new Google_Oauth2Service($gClient); //If user wish to log out, we just unset Session variable if (isset($_REQUEST['reset'])) { unset($_SESSION['token']); $gClient->revokeToken(); header('Location: ' . filter_var($google_redirect_url, FILTER_SANITIZE_URL)); //redirect user back to page } if (!isset($_GET['code']) && empty($_REQUEST['state'])) { unset($_SESSION['token']); } //If code is empty, redirect user to google authentication page for code. //Code is required to aquire Access Token from google //Once we have access token, assign token to session variable //and we can redirect user back to page and login. if (isset($_GET['code']) && empty($_REQUEST['state'])) { $gClient->authenticate($_GET['code']); $_SESSION['token'] = $gClient->getAccessToken(); //echo $_SESSION['token'];die; //header('Location: ' . filter_var($google_redirect_url, FILTER_SANITIZE_URL)); //return; } if (isset($_SESSION['token'])) { //echo "tokent->".$_SESSION['token']; $gClient->setAccessToken($_SESSION['token']); } //echo "aceec->". $gClient->getAccessToken(); die; if ($gClient->getAccessToken()) { //For logged in user, get details from google using access token $data['guser'] = $google_oauthV2->userinfo->get(); $data['guser_id'] = $data['guser']['id']; $data['guser_name'] = filter_var($data['guser']['name'], FILTER_SANITIZE_SPECIAL_CHARS); $data['gemail'] = filter_var($data['guser']['email'], FILTER_SANITIZE_EMAIL); //$data['gprofile_url'] = filter_var($data['guser']['link'], FILTER_VALIDATE_URL); $data['gprofile_image_url'] = filter_var($data['guser']['picture'], FILTER_VALIDATE_URL); $gprofile_image_url = $data['gprofile_image_url']; $email = $data['gemail']; $data['gpersonMarkup'] = "{$email}<div><img src='{$gprofile_image_url}?sz=50'></div>"; $user = $data['guser']; // echo "<pre>"; // print_r($user); // exit; //exit; if (!empty($user)) { $get_users = $ci->user_model->get_user_by_filed('primary_email', $user['email']); $chek_email_id_exist = $ci->user_model->check_duplicate_email_by_filed('primary_email', $user['email']); if (count($get_users) == 0 && $chek_email_id_exist == True) { $random_string = generate_password(); $username = $user['given_name'] . $random_string; $user_rand_id = get_user_rand_id(); $data_to_store = array('user_rand_id' => $user_rand_id, 'firstname' => $user['given_name'], 'google_id' => $user['id'], 'username' => $username, 'lastname' => $user['family_name'], 'primary_email' => $user['email'], 'avatar' => $user['picture'], 'type_of_membership' => 'FREE', 'date_of_registration' => date("Y-m-d H:i:s"), 'last_login' => date("Y-m-d H:i:s"), 'status' => 'Active'); $ci->user_model->store_user($data_to_store); $last_id = $ci->db->insert_id(); $get_member = 'FREE'; $session = array('username' => $username, 'user_id' => $last_id, 'type_of_membership' => $get_member, 'login_google' => 1, 'is_logged_in' => true); $ci->session->set_userdata($session); if (isset($_GET['code'])) { echo "<script>\n window.close();\n window.opener.location.reload();\n </script>"; } } else { $username_details = $ci->user_model->get_username_by_email_id($user['email']); if (!empty($username_details)) { $username1 = $username_details[0]['username']; } $data_to_store = array('firstname' => $user['given_name'], 'google_id' => $user['id'], 'lastname' => $user['family_name'], 'gender' => $user['gender'], 'avatar' => $user['picture'], 'last_login' => date("Y-m-d H:i:s")); $ci->user_model->update_user_by_field('primary_email', $get_users[0]['primary_email'], $data_to_store); $last_id1 = $get_users[0]['user_id']; $get_member = 'FREE'; $session = array('username' => $username1, 'user_id' => $last_id1, 'type_of_membership' => $get_member, 'login_google' => 1, 'is_logged_in' => true); $ci->session->set_userdata($session); if (isset($_GET['code'])) { echo "<script>\n window.close();\n window.opener.location.reload();\n </script>"; } } } } else { $data['authUrl'] = $gClient->createAuthUrl(); } return $data; }
$_SESSION['canVote'] = checkVotingRights($_SESSION["token_data"]["payload"]["email"]); $oAuth2 = new \Google_Service_Oauth2($client); $oAttr = $oAuth2->userinfo->get(); } catch (Exception $e) { unset($_SESSION['access_token']); $redirect_uri = $_SERVER["REQUEST_SCHEME"] . '://' . $_SERVER['HTTP_HOST']; header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL)); } } if (isset($_GET['logout'])) { // Need to proxy if needed. if (function_exists('setProxy')) { setProxy(); $client->getIo()->setOptions(array(CURLOPT_PROXY => 'localhost', CURLOPT_PROXYPORT => 8888)); } $client->revokeToken($_SESSION['access_token']); unset($_SESSION['access_token']); $_SESSION = array(); $redirect_uri = $_SERVER["REQUEST_SCHEME"] . '://' . $_SERVER['HTTP_HOST']; header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL)); die; } /** Send the user for authentication with Google * will call us again with ?code set.*/ if (isset($_GET['login'])) { $client->setRedirectUri($_SERVER["REQUEST_SCHEME"] . '://' . $_SERVER['HTTP_HOST']); $client->addScope("https://www.googleapis.com/auth/userinfo.profile"); $client->addScope("https://www.googleapis.com/auth/userinfo.email"); // Need to proxy if needed. if (function_exists('setProxy')) { $client->getIo()->setOptions(array(CURLOPT_PROXY => 'localhost', CURLOPT_PROXYPORT => 8888));
/** * Clear auth token */ public function clearToken() { $this->googleApiClient->revokeToken(); }
/** * displayRevokeGoogleAccess * * @return void */ function displayRevokeGoogleAccess() { $config = getGoogleConfigData(); if (isset($_SESSION['googleSessionToken'])) { $googleClient = new Google_Client(); $googleClient->setClientId($config['google_client_id']); $googleClient->setClientSecret($config['google_client_secret']); $googleClient->setAccessType('offline'); $googleClient->setScopes(array('https://www.googleapis.com/auth/youtube.force-ssl', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', 'https://picasaweb.google.com/data/')); $googleClient->setRedirectUri($_SESSION['callback_url']); $googleClient->setAccessToken($_SESSION['googleSessionToken']); $googleClient->revokeToken(); unset($_SESSION['googleSessionToken']); } $sql = "UPDATE `fcms_user_settings`\n SET `google_session_token` = NULL\n WHERE `user` = ?"; if (!$this->fcmsDatabase->update($sql, $this->fcmsUser->id)) { $this->displayHeader(); $this->fcmsError->displayError(); $this->displayFooter(); return; } header("Location: settings.php?view=google"); }
} else { $response = 'Already connected'; } return new Response($response, 200); }); // Get list of people user has shared with this app. $app->get('/people', function () use($app, $client, $plus) { $token = $app['session']->get('token'); if (empty($token)) { return new Response('Unauthorized request', 401); } $client->setAccessToken($token); $people = $plus->people->listPeople('me', 'visible', array()); /* * Note (Gerwin Sturm): * $app->json($people) ignores the $people->items not returning this array * Probably needs to be fixed in the Client Library * items isn't listed as public property in Google_Service_Plus_Person * Using ->toSimpleObject for now to get a JSON-convertible object */ return $app->json($people->toSimpleObject()); }); // Revoke current user's token and reset their session. $app->post('/disconnect', function () use($app, $client) { $token = json_decode($app['session']->get('token'))->access_token; $client->revokeToken($token); // Remove the credentials from the user's session. $app['session']->set('token', ''); return new Response('Successfully disconnected', 200); }); $app->run();
public function indexAction(Request $request) { /****Check language session*******/ $session = $request->getSession(); $this->langsession($session); $lan = $session->get('language'); $request->setLocale($lan); $username = $session->get('user'); $em = $this->getDoctrine()->getManager(); $appkey = $this->container->get('mytrip_admin.helper.google')->getOption('apikey'); $appsecretkey = $this->container->get('mytrip_admin.helper.google')->getOption('apisecretkey'); $developerkey = $this->container->get('mytrip_admin.helper.google')->getOption('developerkey'); $product = $this->container->get('mytrip_admin.helper.google')->getOption('productname'); $redirect_url = $this->getRequest()->getSchemeAndHttpHost() . $this->generateUrl('mytrip_user_google'); $gClient = new \Google_Client(); $gClient->setApplicationName($product); $gClient->setClientId($appkey); $gClient->setClientSecret($appsecretkey); $gClient->setRedirectUri($redirect_url); $gClient->setDeveloperKey($developerkey); $google_oauthV2 = new \Google_Oauth2Service($gClient); if (isset($_REQUEST['reset'])) { $session->remove('token'); //unset($_SESSION['token']); $gClient->revokeToken(); return $this->redirect(filter_var($redirect_url, FILTER_SANITIZE_URL)); //header('Location: ' . filter_var($google_redirect_url, FILTER_SANITIZE_URL)); //redirect user back to page } if (isset($_GET['code'])) { $gClient->authenticate($_GET['code']); $session->set('token', $gClient->getAccessToken()); return $this->redirect(filter_var($redirect_url, FILTER_SANITIZE_URL)); } if ($session->get('token')) { $gClient->setAccessToken($session->get('token')); } if ($gClient->getAccessToken()) { //For logged in user, get details from google using access token $user = $google_oauthV2->userinfo->get(); $user_id = $user['id']; $user_name = filter_var($user['name'], FILTER_SANITIZE_SPECIAL_CHARS); $email = filter_var($user['email'], FILTER_SANITIZE_EMAIL); $profile_url = filter_var($user['link'], FILTER_VALIDATE_URL); $profile_image_url = filter_var($user['picture'], FILTER_VALIDATE_URL); $personMarkup = "{$email}<div><img src='{$profile_image_url}?sz=50'></div>"; $session->set('token', $gClient->getAccessToken()); if (empty($username)) { $emailcheck = $em->createQuery("SELECT p FROM MytripAdminBundle:User p WHERE p.email='" . $email . "' AND p.status NOT IN ('Trash')")->getArrayResult(); if (empty($emailcheck)) { $randno = sha1($this->str_rand() . date('Y-m-d H:i:s')); $password = $this->str_rand(6); $member = new \Mytrip\AdminBundle\Entity\User(); $member->setFirstname($user_name); $member->setLastname(' '); $member->setEmail($email); $member->setPassword(sha1($password)); $member->setLan($lan); $member->setUserKey($randno); $member->setStatus('Active'); $member->setCreatedDate(new \DateTime(date('Y-m-d H:i:s'))); $member->setModifyDate(new \DateTime(date('Y-m-d H:i:s'))); $em->persist($member); $em->flush(); $uid = $member->getUserId(); $social_links = new \Mytrip\AdminBundle\Entity\UserSocialLink(); $social_links->setUser($this->getDoctrine()->getRepository('MytripAdminBundle:User')->find($uid)); $social_links->setSocialLink('Google'); $social_links->setId($user_id); $social_links->setImage($profile_image_url); $social_links->setCreatedDate(new \DateTime(date('Y-m-d H:i:s'))); $em->persist($social_links); $em->flush(); $user = $em->createQuery("SELECT p FROM MytripAdminBundle:User p WHERE p.userId='" . $uid . "'")->getArrayResult(); $session->set('user', $user[0]); $session->set('UserLogin', "True"); $emaillist = $em->getRepository('MytripAdminBundle:EmailList')->findOneBy(array('emailListId' => '14')); $emailcontent = $em->getRepository('MytripAdminBundle:EmailContent')->findOneBy(array('emailList' => '14', 'lan' => $lan)); if (!empty($emailcontent)) { $emailcontent = $em->getRepository('MytripAdminBundle:EmailContent')->findOneBy(array('emailList' => '14', 'lan' => 'en')); } $link = $this->getRequest()->getSchemeAndHttpHost() . $this->generateUrl('mytrip_user_confirm') . "?u_my_code=" . $randno . "_" . sha1($uid); $message = str_replace(array('{name}', '{link}'), array($user[0]['firstname'] . ' ' . $user[0]['lastname'], $link), $emailcontent->getEmailContent()); //$message=str_replace(array('{name}','{username}','{password}','{link}'),array($user_name,$email,$password,$link),$emailcontent->getEmailContent()); $subject = str_replace(array('{name}', '{link}'), array($user[0]['firstname'] . ' ' . $user[0]['lastname'], $link), $emailcontent->getSubject()); /*******Contact mail send to admin***********/ $this->mailsend($emaillist->getFromname(), $emaillist->getFromemail(), $user[0]['email'], $subject, $message, $emaillist->getCcmail()); $this->get('session')->getFlashBag()->add('success', $this->get('translator')->trans('Successfully Registered. Confirmation link sent to your mail id.')); return $this->redirect($this->generateUrl('mytrip_user_profile')); } else { $uid = $emailcheck[0]['userId']; $check_social_link = $em->createQuery("SELECT p FROM MytripAdminBundle:UserSocialLink p WHERE p.user='******' AND p.socialLink='Google' AND p.id='" . $user_id . "'")->getArrayResult(); if (empty($check_social_link)) { $social_links = new \Mytrip\AdminBundle\Entity\UserSocialLink(); $social_links->setUser($this->getDoctrine()->getRepository('MytripAdminBundle:User')->find($uid)); $social_links->setSocialLink('Google'); $social_links->setId($user_id); $social_links->setImage($profile_image_url); $social_links->setCreatedDate(new \DateTime(date('Y-m-d H:i:s'))); $em->persist($social_links); $em->flush(); } $user = $em->createQuery("SELECT p FROM MytripAdminBundle:User p WHERE p.userId='" . $uid . "'")->getArrayResult(); $session->set('user', $user[0]); $session->set('UserLogin', "True"); return $this->redirect($this->generateUrl('mytrip_user_profile')); } } else { $uid = $username['userId']; $check_social_link = $em->createQuery("SELECT p FROM MytripAdminBundle:UserSocialLink p WHERE p.user='******' AND p.socialLink='Google' AND p.id='" . $user_profile['id'] . "'")->getArrayResult(); if (empty($check_social_link)) { $social_links = new \Mytrip\AdminBundle\Entity\UserSocialLink(); $social_links->setUser($this->getDoctrine()->getRepository('MytripAdminBundle:User')->find($uid)); $social_links->setSocialLink('Google'); $social_links->setId($user_id); $social_links->setImage($profile_image_url); $social_links->setCreatedDate(new \DateTime(date('Y-m-d H:i:s'))); $em->persist($social_links); $em->flush(); } return $this->redirect($this->generateUrl('mytrip_user_profile')); } } else { //For Guest user, get google login url $authUrl = $gClient->createAuthUrl(); return $this->redirect($authUrl); } }
/** * Log out of the attached external service. * * @return void */ public function custom_logout() { // Grab plugin settings. $auth_settings = $this->get_plugin_options('single admin', 'allow override'); // Reset option containing old error messages. delete_option('auth_settings_advanced_login_error'); if (session_id() == '') { session_start(); } $current_user_authenticated_by = get_user_meta(get_current_user_id(), 'authenticated_by', true); // If logged in to CAS, Log out of CAS. if ($current_user_authenticated_by === 'cas' && $auth_settings['cas'] === '1') { if (!array_key_exists('PHPCAS_CLIENT', $GLOBALS) || !array_key_exists('phpCAS', $_SESSION)) { // Set the CAS client configuration if it hasn't been set already. phpCAS::client(SAML_VERSION_1_1, $auth_settings['cas_host'], intval($auth_settings['cas_port']), $auth_settings['cas_path']); // Restrict logout request origin to the CAS server only (prevent DDOS). phpCAS::handleLogoutRequests(true, array($auth_settings['cas_host'])); } if (phpCAS::isAuthenticated()) { phpCAS::logoutWithRedirectService(get_option('siteurl')); } } // If session token set, log out of Google. if ($current_user_authenticated_by === 'google' && array_key_exists('token', $_SESSION)) { $token = json_decode($_SESSION['token'])->access_token; // Build the Google Client. $client = new Google_Client(); $client->setApplicationName('WordPress'); $client->setClientId($auth_settings['google_clientid']); $client->setClientSecret($auth_settings['google_clientsecret']); $client->setRedirectUri('postmessage'); // Revoke the token $client->revokeToken($token); // Remove the credentials from the user's session. $_SESSION['token'] = ''; } }
function google_oauth() { ########## Google Settings.. Client ID, Client Secret from https://cloud.google.com/console ############# $google_client_id = GOOGLE_CLIENT_ID; $google_client_secret = GOOGLE_CLIENT_SECRET; $google_redirect_url = base_url() . 'social/google_oauth'; //path to your script $google_developer_key = GOOGLE_DEVELOPER_KEY; //include google api files require_once APPPATH . 'libraries/google-plus/Google_Client.php'; require_once APPPATH . 'libraries/google-plus/contrib/Google_Oauth2Service.php'; //start session //session_start(); $gClient = new Google_Client(); $gClient->setApplicationName('liilt_beta'); $gClient->setClientId($google_client_id); $gClient->setClientSecret($google_client_secret); $gClient->setRedirectUri($google_redirect_url); $gClient->setDeveloperKey($google_developer_key); // $google_oauthV2 = new Google_Oauth2Service($gClient); // $authUrl = $gClient->createAuthUrl(); // echo $authUrl; exit; $google_oauthV2 = new Google_Oauth2Service($gClient); //If user wish to log out, we just unset Session variable if (isset($_REQUEST['reset'])) { unset($_SESSION['token']); $gClient->revokeToken(); header('Location: ' . filter_var($google_redirect_url, FILTER_SANITIZE_URL)); //redirect user back to page } //If code is empty, redirect user to google authentication page for code. //Code is required to aquire Access Token from google //Once we have access token, assign token to session variable //and we can redirect user back to page and login. if (isset($_GET['code'])) { $gClient->authenticate($_GET['code']); //$_SESSION['token'] = $gClient->getAccessToken(); $this->session->set_userdata('google_token', $gClient->getAccessToken()); header('Location: ' . filter_var($google_redirect_url, FILTER_SANITIZE_URL)); return; } if (isset($_GET['error'])) { redirect("register"); } if ($this->session->userdata('google_token')) { $gClient->setAccessToken($this->session->userdata('google_token')); } if ($gClient->getAccessToken()) { //For logged in user, get details from google using access token $googleuser = $google_oauthV2->userinfo->get(); $exists = $this->User_model->check_email($googleuser['email']); if ($exists['rc']) { // user exists and login him/her to the system $user_id = $exists['data']['id']; $dir = FCPATH . "uploads/profile_images/" . $user_id . "/"; if ($exists['data']['profile_image'] == "" || !file_exists($dir . $exists['data']['profile_image'])) { $url = $googleuser['picture']; $this->add_picture($user_id, $url, 'google.jpg'); } $user_data = array('user_id' => $user_id, 'email' => $exists['data']['email']); $result = $this->set_login_session_data($user_data); if ($this->session->userdata("user_id")) { redirect("user/dashboard"); exit; } } else { // register the user in the system and log him/her in // facebook image = https://graph.facebook.com/$user['id']/picture?width=*** $hash = md5(microtime() . rand()); if (isset($googleuser['picture'])) { $default = base_url() . "resources/images/avatar.jpg"; $size = 40; $email = trim($googleuser['email']); // "*****@*****.**" $email = strtolower($email); // "*****@*****.**" $email = md5($email); $grav_url = "http://www.gravatar.com/avatar/" . $email . ""; } $user_data = array('name' => $googleuser['given_name'] . " " . $googleuser['family_name'], 'email' => $googleuser['email'], 'created_on' => time(), 'gravatar_url' => isset($grav_url) ? $grav_url : "", 'account_type' => GOOGLE_ACCOUNT, "password" => $hash); $response = $this->User_model->add_user_from_social_login($user_data); $session_data["user_id"] = $response["data"]; $session_data["email"] = $user_data["email"]; $url = $googleuser['picture']; $result_add_pic = $this->add_picture($response["data"], $url, 'google.jpg'); $result = $this->set_login_session_data($session_data); if ($this->session->userdata("user_id")) { redirect("user/dashboard"); exit; } } } else { //For Guest user, get google login url $authUrl = $gClient->createAuthUrl(); } exit; }
private function process_google() { include 'include/google/Google_Client.php'; include 'include/google/contrib/Google_Oauth2Service.php'; session_start(); $gClient = new Google_Client(); $gClient->setApplicationName('Login for christian starter.'); $gClient->setClientId(Config::get("google.client_id")); $gClient->setClientSecret(Config::get("google.client_secret")); $gClient->setRedirectUri(Config::get("google.redirect_url")); $gClient->setDeveloperKey(Config::get("google.developer_key")); $google_oauthV2 = new Google_Oauth2Service($gClient); if (isset($_REQUEST['reset'])) { unset($_SESSION['token']); $gClient->revokeToken(); header('Location: ' . filter_var(Config::get("google.redirect_url"), FILTER_SANITIZE_URL)); //redirect user back to page } //If code is empty, redirect user to google authentication page for code. //Code is required to aquire Access Token from google //Once we have access token, assign token to session variable //and we can redirect user back to page and login. if (isset($_GET['code'])) { $gClient->authenticate($_GET['code']); $_SESSION['token'] = $gClient->getAccessToken(); header('Location: ' . filter_var(Config::get("google.redirect_url"), FILTER_SANITIZE_URL)); return; } if (isset($_SESSION['token'])) { $gClient->setAccessToken($_SESSION['token']); } if ($gClient->getAccessToken()) { //For logged in user, get details from google using access token $user = $google_oauthV2->userinfo->get(); $email = $user["email"]; $first_name = $user["given_name"]; $last_name = $user["family_name"]; $picture = $user["picture"]; $gender = strtolower($user["gender"]) == "male" ? 1 : 2; $id = $user["id"]; $password = Hash::make($id); $check = DB::table("users")->where("email", $email)->first(); if (!empty($check)) { // already exist DB::table("users")->where("email", $email)->update(array("first_name" => $first_name, "last_name" => $last_name, "gender" => $gender, "picture" => $picture)); if (Auth::attempt(array('email' => $email, 'password' => $id), true)) { Auth::login(Auth::user(), true); DB::table("users")->where("email", $email)->update(array("last_login_date" => date("Y-m-d H:i:s"))); return Redirect::to("/dashboard"); } else { return Redirect::to("/"); } } else { // first login $newid = DB::table("users")->insertGetId(array("id" => null, "first_name" => $first_name, "last_name" => $last_name, "gender" => $gender, "email" => $email, "username" => $id, "password" => $password, "picture" => $picture, "permission" => 100, "token" => null, "created_date" => date("Y-m-d H:i:s"), "last_login_date" => null, "status" => 1)); DB::table("user_profile")->insert(array("user_id" => $newid)); if (Auth::attempt(array('email' => $email, 'password' => $id), true)) { Auth::login(Auth::user(), true); DB::table("users")->where("email", $email)->update(array("last_login_date" => date("Y-m-d H:i:s"))); return Redirect::to("/dashboard"); } else { return Redirect::to("/"); } } } else { //For Guest user, get google login url $authUrl = $gClient->createAuthUrl(); } if (isset($authUrl)) { echo "<script>location.href = '{$authUrl}'</script>"; } else { $email = $user["email"]; $first_name = $user["given_name"]; $last_name = $user["family_name"]; $picture = $user["picture"]; $gender = strtolower($user["gender"]) == "male" ? 1 : 2; $id = $user["id"]; $password = Hash::make($id); $check = DB::table("users")->where("email", $email)->first(); if (!empty($check)) { // already exist DB::table("users")->where("email", $email)->update(array("first_name" => $first_name, "last_name" => $last_name, "gender" => $gender, "picture" => $picture)); if (Auth::attempt(array('email' => $email, 'password' => $id), true)) { Auth::login(Auth::user(), true); return Redirect::to("/dashboard"); } else { return Redirect::to("/"); } } else { // first login $newid = DB::table("users")->insertGetId(array("id" => null, "first_name" => $first_name, "last_name" => $last_name, "gender" => $gender, "email" => $email, "username" => $id, "password" => $password, "picture" => $picture, "permission" => 100, "status" => 1)); DB::table("user_profile")->insert(array("user_id" => $newid)); if (Auth::attempt(array('email' => $email, 'password' => $id), true)) { Auth::login(Auth::user(), true); return Redirect::to("/dashboard"); } else { return Redirect::to("/"); } } } }
/** * Test for revoking token when none is opened */ public function testRevokeWhenNoTokenExists() { $client = new Google_Client(); $this->assertFalse($client->revokeToken()); }
public function google() { $this->load->helper('url'); $ci =& get_instance(); $ci->load->config('google'); $google_client_id = $ci->config->item('google_client_id'); $google_client_secret = $ci->config->item('google_client_secret'); $google_redirect_url = $ci->config->item('google_redirect_url'); //path to your script $google_developer_key = $ci->config->item('google_developer_key'); require_once 'src/Google_Client.php'; require_once 'src/contrib/Google_Oauth2Service.php'; //$this->load->library('Google_Oauth2Service'); $gClient = new Google_Client(); $gClient->setClientId($google_client_id); $gClient->setClientSecret($google_client_secret); $gClient->setRedirectUri($google_redirect_url); $gClient->setDeveloperKey($google_developer_key); $google_oauthV2 = new Google_Oauth2Service($gClient); //If user wish to log out, we just unset Session variable if (isset($_REQUEST['reset'])) { unset($_SESSION['token']); $gClient->revokeToken(); header('Location: ' . filter_var($google_redirect_url, FILTER_SANITIZE_URL)); //redirect user back to page } //If code is empty, redirect user to google authentication page for code. //Code is required to aquire Access Token from google //Once we have access token, assign token to session variable //and we can redirect user back to page and login. if (isset($_GET['code'])) { $gClient->authenticate($_GET['code']); $_SESSION['token'] = $gClient->getAccessToken(); //echo $_SESSION['token']; //redirect($google_redirect_url); //return; } if (isset($_SESSION['token'])) { $_SESSION['token']; $gClient->setAccessToken($_SESSION['token']); } if ($gClient->getAccessToken()) { //For logged in user, get details from google using access token $data['guser'] = $google_oauthV2->userinfo->get(); $data['guser_id'] = $data['guser']['id']; $data['guser_name'] = filter_var($data['guser']['name'], FILTER_SANITIZE_SPECIAL_CHARS); $data['gemail'] = filter_var($data['guser']['email'], FILTER_SANITIZE_EMAIL); $data['gprofile_url'] = filter_var($data['guser']['link'], FILTER_VALIDATE_URL); $data['gprofile_image_url'] = filter_var($data['guser']['picture'], FILTER_VALIDATE_URL); $data['gpersonMarkup'] = "{$email}<div><img alt='profile image' src='{$gprofile_image_url}?sz=50'></div>"; $this->session->set_userdata(array('token' => $gClient->getAccessToken())); //print_r($data['guser']); die; //$_SESSION['token'] } else { //For Guest user, get google login url $data['authUrl'] = $gClient->createAuthUrl(); } $data['main_content'] = 'home_view'; $this->load->view('includes/template', $data); }
public function actionGmailSignup() { require_once Yii::app()->basePath . '/modules/user/views/src/Google_Client.php'; //require_once 'src/Google_Client.php'; // include the required calss files for google login require_once Yii::app()->basePath . '/modules/user/views/src/contrib/Google_PlusService.php'; require_once Yii::app()->basePath . '/modules/user/views/src/contrib/Google_Oauth2Service.php'; $client = new Google_Client(); $client->setApplicationName("Asig 18 Sign in with GPlus"); // Set your applicatio name $client->setScopes('https://www.googleapis.com/auth/analytics'); //$client->setScopes// set scope during user login $client->setClientId('33563737111-gtuhtrm5f7cd4t66023fao39k5u55ol7.apps.googleusercontent.com'); // paste the client id which you get from google API Console $client->setClientSecret('O6IEQPCZw71vDSYVkZ-yKkRF'); // set the client secret $client->setRedirectUri('http://instanttop.com/index.php/user/user/GmailSignup/oauth2callback/'); // paste the redirect URI where you given in APi Console. You will get the Access Token here during login success $client->setDeveloperKey('AIzaSyBKvfFpG2RUNIFgKDM-fe_6dja9LpJoXRA'); // Developer key $plus = new Google_PlusService($client); $oauth2 = new Google_Oauth2Service($client); // Call the OAuth2 class for get email address $google_client_id = '402738627423-lsvdi7fvl9bf7j8ai96lc6sri1evsq9b.apps.googleusercontent.com'; $google_client_secret = 'TfvlOFg9eevgL_muiOaxiTeL'; $google_redirect_url = 'https://instanttop.com/index.php/user/user/GmailSignup/oauth2callback/'; //path to your script $google_developer_key = 'AIzaSyCXtRDlIE1GzcZ5UC9AdE17ib53Gnnx8Qk'; $gClient = new Google_Client(); $gClient->setApplicationName('Login to Sanwebe.com'); $gClient->setClientId($google_client_id); $gClient->setClientSecret($google_client_secret); $gClient->setRedirectUri($google_redirect_url); $gClient->setDeveloperKey($google_developer_key); $google_oauthV2 = new Google_Oauth2Service($gClient); //If user wish to log out, we just unset Session variable if (isset($_REQUEST['reset'])) { unset($_SESSION['token']); $gClient->revokeToken(); header('Location: ' . filter_var($google_redirect_url, FILTER_SANITIZE_URL)); //redirect user back to page } if (isset($_GET['code'])) { $gClient->authenticate($_GET['code']); $_SESSION['token'] = $gClient->getAccessToken(); header('Location: ' . filter_var($google_redirect_url, FILTER_SANITIZE_URL)); return; } if (isset($_SESSION['token'])) { $gClient->setAccessToken($_SESSION['token']); } if ($gClient->getAccessToken()) { //For logged in user, get details from google using access token $user = $google_oauthV2->userinfo->get(); $user_id = $user['id']; $user_name = filter_var($user['name'], FILTER_SANITIZE_SPECIAL_CHARS); $email = filter_var($user['email'], FILTER_SANITIZE_EMAIL); $profile_url = filter_var($user['link'], FILTER_VALIDATE_URL); $profile_image_url = filter_var($user['picture'], FILTER_VALIDATE_URL); $personMarkup = "{$email}<div><img src='{$profile_image_url}?sz=50'></div>"; $_SESSION['token'] = $gClient->getAccessToken(); $username = $user_name; $lastname = $user['family_name']; $userData = User::model()->find('username="******" or email="' . $email . '"'); echo "heredf"; if ($userData) { echo "here"; $model = new UserLoginFB(); if (User::model()->find('username="******"')) { $model->username = $userData->username; } else { $model->email = $userData->email; } $model->password = $userData->password; if ($model->validate()) { Yii::app()->user->returnUrl = Yii::app()->request->urlReferrer; $this->redirect(Yii::app()->user->returnUrl); } } else { echo "string"; $model = new User(); $model->email = $email; $model->username = $username; $password = rand(0, 999999999); $pass = md5($password); $model->password = $pass; $model->status = 1; $model->create_at = date('Y-m-d H:i:s'); /* if(!$model->save()) { var_dump($model->getErrors());die("error"); } */ if ($model->save()) { $modelprofile = new Profile(); $modelprofile->user_id = $model->id; $modelprofile->lastname = $lastname; $modelprofile->firstname = $username; $modelprofile->save(); $model1 = new UserLogin(); $model1->username = $username; $model1->password = $password; if ($model1->validate()) { $Url = Yii::app()->request->urlReferrer; $this->redirect(Yii::app()->user->returnUrl); } //$this->redirect(Yii::app()->user->returnUrl); } $this->render('login', array('model' => $model)); } } else { //For Guest user, get google login url $authUrl = $gClient->createAuthUrl(); } }
public function googlelogin() { ########## Google Settings.. Client ID, Client Secret ############# $google_client_id = '655713364128-b4ul4nhvrbss589scr42g3r0pqg9vkk1.apps.googleusercontent.com'; $google_client_secret = 'NY_yyjQn8uRFYe1-k769SbnU'; $google_redirect_url = 'http://myhouse.alpha-soluciones.com/users/'; $google_developer_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; //include google api files //App::import('Lib', 'Google/src/Google_Client.php'); //App::import('Lib', 'Google/src/contrib/Google_Oauth2Service.php'); //require_once 'Lib/Google/src/Google_Client.php'; //require_once 'Lib/Google/src/contrib/Google_Oauth2Service.php'; App::import('Vendor', 'GoogleGoogle_Client', array('file' => 'Google' . DS . 'src' . DS . 'Google_Client.php')); App::import('Vendor', 'GoogleGoogle_Oauth2Service', array('file' => 'Google' . DS . 'src' . DS . 'contrib' . DS . 'Google_Oauth2Service.php')); $gClient = new Google_Client(); $gClient->setApplicationName('MyHouse'); $gClient->setClientId($google_client_id); $gClient->setClientSecret($google_client_secret); $gClient->setRedirectUri($google_redirect_url); $gClient->setDeveloperKey($google_developer_key); $google_oauthV2 = new Google_Oauth2Service($gClient); //If user wish to log out, we just unset Session variable if (isset($_REQUEST['reset'])) { $this->set('msg', 'Logout'); //unset($_SESSION['token']); $this->Session->delete('Google.token'); $gClient->revokeToken(); header('Location: ' . filter_var($google_redirect_url, FILTER_SANITIZE_URL)); } //Redirect user to google authentication page for code, if code is empty. //Code is required to aquire Access Token from google //Once we have access token, assign token to session variable //and we can redirect user back to page and login. if (isset($_REQUEST['code'])) { $gClient->authenticate($_REQUEST['code']); $this->Session->write('Google.token', $gClient->getAccessToken()); //$this->redirect(filter_var($google_redirect_url, FILTER_SANITIZE_URL), null, false); //header('Location: ' . filter_var($google_redirect_url, FILTER_SANITIZE_URL)); $this->redirect($this->Auth->redirect()); return; } if ($this->Session->read('Google.token')) { $gClient->setAccessToken($this->Session->read('Google.token')); } $user = array(); $authUrl = ''; if ($gClient->getAccessToken()) { //Get user details if user is logged in $user = $google_oauthV2->userinfo->get(); $user_id = $user['id']; $user['name'] = filter_var($user['name'], FILTER_SANITIZE_SPECIAL_CHARS); $user['email'] = filter_var($user['email'], FILTER_SANITIZE_EMAIL); //$profile_url = filter_var($user['link'], FILTER_VALIDATE_URL); //$profile_image_url = filter_var($user['picture'], FILTER_VALIDATE_URL); //$personMarkup = "$email<div><img src='$profile_image_url?sz=50'></div>"; //$this->Session->destroy(); $this->Session->write('Google.token', $gClient->getAccessToken()); $this->forceLogin($user['email'], 'Google'); $this->networking_login('Google'); } else { //get google login url $authUrl = $gClient->createAuthUrl(); } return array('AuthUrl' => $authUrl, 'User' => $user); }
/** * @Google login action * * Connect Google Using oAuth coonection. * * @return string redirect URL either customer save and loggedin or an error if any occurs */ public function googlepostAction() { /** * Include @Google library files for oAuth connection */ require_once 'sociallogin/src/Google_Client.php'; require_once 'sociallogin/src/contrib/Google_Oauth2Service.php'; /** * Retrieves the @google_client_id, @google_client_secret */ $google_client_id = Mage::getStoreConfig('sociallogin/google/google_id'); $google_client_secret = Mage::getStoreConfig('sociallogin/google/google_secret'); $google_developer_key = Mage::getStoreConfig('sociallogin/google/google_develop'); $google_redirect_url = Mage::getUrl() . 'sociallogin/index/googlepost/'; /** * Create the object @var $gClient from google client */ $gClient = new Google_Client(); $gClient->setApplicationName('login'); $gClient->setClientId($google_client_id); $gClient->setClientSecret($google_client_secret); $gClient->setRedirectUri($google_redirect_url); $gClient->setDeveloperKey($google_developer_key); /** * Create the object @var $google_oauthV2 from Google_Oauth2Service */ $google_oauthV2 = new Google_Oauth2Service($gClient); $token = Mage::getSingleton('core/session')->getGoogleToken(); $reset = $this->getRequest()->getParam('reset'); if ($reset) { unset($token); $gClient->revokeToken(); $this->_redirectUrl(filter_var($google_redirect_url, FILTER_SANITIZE_URL)); } /** * If retrieve the param in request array * * @param string code */ $code = $this->getRequest()->getParam('code'); if (isset($code)) { $gClient->authenticate($code); Mage::getSingleton('core/session')->setGoogleToken($gClient->getAccessToken()); $this->_redirectUrl(filter_var($google_redirect_url, FILTER_SANITIZE_URL)); $this->_redirectUrl($google_redirect_url); return; } /** * If $token is non-empty set the access token * */ if (isset($token)) { $gClient->setAccessToken($token); } if ($gClient->getAccessToken()) { /** * Retrieve user details If user succesfully in Google */ $user = $google_oauthV2->userinfo->get(); $user_id = $user['id']; $user_name = filter_var($user['name'], FILTER_SANITIZE_SPECIAL_CHARS); $email = filter_var($user['email'], FILTER_SANITIZE_EMAIL); $profile_url = filter_var($user['link'], FILTER_VALIDATE_URL); $token = $gClient->getAccessToken(); Mage::getSingleton('core/session')->setGoogleToken($token); } else { /** * get google Authendication URL */ $authUrl = $gClient->createAuthUrl(); } /** * If user doesn't logged-in redirects the login URL */ if (isset($authUrl)) { $this->_redirectUrl($authUrl); } else { /** * Fetching user infor from google array $user * * @var string $firstname, , general info for users from @google account. * @var string $familyname * @var string $email * @var string $id */ $firstname = $user['given_name']; $lastname = $user['family_name']; $email = $user['email']; $google_user_id = $user['id']; /** * If @var $email is empty throws failure message. */ if ($email == '') { Mage::getSingleton('customer/session')->addError($this->__('Google Login connection failed')); $url = Mage::helper('customer')->getAccountUrl(); return $this->_redirectUrl($url); } else { /** * Do the customer account action with the login provider as Google */ $this->customerAction($firstname, $lastname, $email, 'Google'); } } }
/** * @Google login action * * Connect Google Using oAuth coonection. * * @return string redirect URL either customer save and loggedin or an error if any occurs */ public function googlepostAction() { /** * Include @Google library files for oAuth connection */ require_once 'sociallogin/src/Google_Client.php'; require_once 'sociallogin/src/contrib/Google_Oauth2Service.php'; /** * Retrieves the @google_client_id, @google_client_secret */ $googleClientId = Mage::getStoreConfig('sociallogin/google/google_id'); $googleClientSecret = Mage::getStoreConfig('sociallogin/google/google_secret'); $googleDeveloperKey = Mage::getStoreConfig('sociallogin/google/google_develop'); $googleRedirectUrl = Mage::getUrl() . 'sociallogin/index/googlepost/'; $gClient = new Google_Client(); $gClient->setApplicationName('login'); $gClient->setClientId($googleClientId); $gClient->setClientSecret($googleClientSecret); $gClient->setRedirectUri($googleRedirectUrl); $gClient->setDeveloperKey($googleDeveloperKey); $googleOauthV2 = new Google_Oauth2Service($gClient); $token = Mage::getSingleton('core/session')->getGoogleToken(); $reset = $this->getRequest()->getParam('reset'); $data = $this->getRequest()->getParam('fb'); if ($reset) { unset($token); $gClient->revokeToken(); $this->_redirectUrl(filter_var($googleRedirectUrl, FILTER_SANITIZE_URL)); } $code = $this->getRequest()->getParam('code'); if (isset($code)) { $gClient->authenticate($code); Mage::getSingleton('core/session')->setGoogleToken($gClient->getAccessToken()); $this->_redirectUrl(filter_var($googleRedirectUrl, FILTER_SANITIZE_URL)); $this->_redirectUrl($googleRedirectUrl); return; } if (isset($token)) { $gClient->setAccessToken($token); } if ($gClient->getAccessToken()) { /** * Retrieve user details If user succesfully in Google */ $user = $googleOauthV2->userinfo->get(); $user['id']; filter_var($user['name'], FILTER_SANITIZE_SPECIAL_CHARS); $email = filter_var($user['email'], FILTER_SANITIZE_EMAIL); filter_var($user['link'], FILTER_VALIDATE_URL); $token = $gClient->getAccessToken(); Mage::getSingleton('core/session')->setGoogleToken($token); } else { /** * get google google Authendication URL */ $authUrl = $gClient->createAuthUrl(); } /** * If user doesn't logged-in redirects the login URL */ if (isset($authUrl)) { $this->_redirectUrl($authUrl); } else { /** * Fetching user infor from an array, @param array $user * * @param string $given_name, * $familyname, $email general info for users from @google account. */ $firstName = $user['given_name']; $lastName = $user['family_name']; $email = $user['email']; $user['id']; if ($email == '') { Mage::getSingleton('customer/session')->addError($this->__('Google Login connection failed')); $url = Mage::helper('customer')->getAccountUrl(); return $this->_redirectUrl($url); } else { $this->customerAction($firstName, $lastName, $email, 'Google', $data); } } }
$client1 = new Google_Client(); $client1->setApplicationName("Google UserInfo PHP Starter Application"); $oauth2 = new Google_Oauth2Service($client1); if (isset($_GET['code'])) { $client1->authenticate($_GET['code']); $_SESSION['token'] = $client1->getAccessToken(); $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL)); return; } if (isset($_SESSION['token'])) { $client1->setAccessToken($_SESSION['token']); } if (isset($_REQUEST['logout'])) { unset($_SESSION['token']); $client1->revokeToken(); } if ($client1->getAccessToken()) { $user = $oauth2->userinfo->get(); // echo $user; exit; // These fields are currently filtered through the PHP sanitize filters. // See http://www.php.net/manual/en/filter.filters.sanitize.php $email = filter_var($user['email'], FILTER_SANITIZE_EMAIL); $img = filter_var($user['picture'], FILTER_VALIDATE_URL); $personMarkup = "{$email}<div><img src='{$img}?sz=50'></div>"; // The access token may have been updated lazily. $_SESSION['token'] = $client1->getAccessToken(); } else { $authUrl = $client1->createAuthUrl(); } //if(isset($personMarkup)):
// $client->setRedirectUri('insert_your_redirect_uri'); // $client->setDeveloperKey('insert_your_developer_key'); $oauth2 = new Google_Oauth2Service($client); if (isset($_GET['code'])) { $client->authenticate($_GET['code']); $_SESSION['token'] = $client->getAccessToken(); $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL)); return; } if (isset($_SESSION['token'])) { $client->setAccessToken($_SESSION['token']); } if (isset($_REQUEST['logout'])) { unset($_SESSION['token']); $client->revokeToken(); } if ($client->getAccessToken()) { $user = $oauth2->userinfo->get(); // These fields are currently filtered through the PHP sanitize filters. // See http://www.php.net/manual/en/filter.filters.sanitize.php $email = filter_var($user['email'], FILTER_SANITIZE_EMAIL); $img = filter_var($user['picture'], FILTER_VALIDATE_URL); $personMarkup = "{$email}<div><img src='{$img}?sz=50'></div>"; // The access token may have been updated lazily. $_SESSION['token'] = $client->getAccessToken(); } else { $authUrl = $client->createAuthUrl(); } ?> <!doctype html>
public static function revokeAccessToken() { $xmpData = erLhcoreClassModelChatConfig::fetch('xmp_data'); $data = (array) $xmpData->data; try { if (isset($data['gtalk_client_token']) && $data['gtalk_client_token'] != '') { require_once 'lib/core/lhxmp/google/Google_Client.php'; $client = new Google_Client(); $client->setApplicationName('Live Helper Chat'); $client->setScopes(array("https://www.googleapis.com/auth/googletalk", "https://www.googleapis.com/auth/userinfo.email")); $client->setClientId($data['gtalk_client_id']); $client->setClientSecret($data['gtalk_client_secret']); $client->setAccessType('offline'); $client->setApprovalPrompt('force'); $token = $data['gtalk_client_token']; $client->setAccessToken($data['gtalk_client_token']); // Refresh token if it's if ($client->isAccessTokenExpired()) { $tokenData = json_decode($token); $client->refreshToken($tokenData->refresh_token); $accessToken = $client->getAccessToken(); } if ($accessToken = $client->getAccessToken()) { $client->revokeToken(); } unset($data['gtalk_client_token']); $xmpData->value = serialize($data); $xmpData->saveThis(); } return true; } catch (Exception $e) { throw $e; } }