Example #1
5
 function google()
 {
     $client = new Google_Client();
     $client->setApplicationName("snmmaurya");
     $client->setClientId(CLIENT_ID);
     $client->setClientSecret(CLIENT_SECRET);
     $client->setRedirectUri(REDIRECT_URI);
     $client->setApprovalPrompt(APPROVAL_PROMPT);
     $client->setAccessType(ACCESS_TYPE);
     $oauth2 = new Google_Oauth2Service($client);
     if (isset($_GET['code'])) {
         $client->authenticate($_GET['code']);
         $_SESSION['token'] = $client->getAccessToken();
     }
     if (isset($_SESSION['token'])) {
         $client->setAccessToken($_SESSION['token']);
     }
     if (isset($_REQUEST['error'])) {
         echo '<script type="text/javascript">window.close();</script>';
         exit;
     }
     if ($client->getAccessToken()) {
         $user = $oauth2->userinfo->get();
         $_SESSION['User'] = $user;
         $_SESSION['token'] = $client->getAccessToken();
     } else {
         $authUrl = $client->createAuthUrl();
         header('Location: ' . $authUrl);
     }
 }
Example #2
3
 public function actionToken()
 {
     //$this->checkAccess("token");
     $client = new \Google_Client();
     $client->setClientId(Yii::$app->params['OAUTH2_CLIENT_ID']);
     $client->setClientSecret(Yii::$app->params['OAUTH2_CLIENT_SECRET']);
     $client->setScopes('https://www.googleapis.com/auth/youtube');
     //$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'], FILTER_SANITIZE_URL);
     $client->setRedirectUri(Yii::$app->params['redirectVideo']);
     if (Yii::$app->request->get('code')) {
         if (strval(Yii::$app->session->get('state')) !== strval(Yii::$app->request->get('state'))) {
             die('The session state did not match.');
         }
         $client->authenticate(Yii::$app->request->get('code'));
         if ($client->getAccessToken()) {
             $token = $this->getToken();
             $token->load(json_decode($client->getAccessToken(), true), "");
             $token->save();
             return ["token_saved" => $token];
         }
         return ["token_not_saved_code" => Yii::$app->request->get('code')];
     }
     if (!$client->getAccessToken()) {
         // If the user hasn't authorized the app, initiate the OAuth flow
         //$state = mt_rand();
         $client->setState(Yii::$app->params['stateVideo']);
         $client->setAccessType("offline");
         $client->setApprovalPrompt("force");
         Yii::$app->session->set('state', Yii::$app->params['stateVideo']);
         $authUrl = $client->createAuthUrl();
         return ["link" => $authUrl];
     }
 }
 /**
  * Returns an authorized API client.
  * @return Google_Client the authorized client object
  */
 private function getGoogleApiClient()
 {
     $client = new Google_Client();
     $client->setApplicationName($this->CFG['GOOGLE_API_APPLICATION_NAME']);
     $client->setScopes(Google_Service_Calendar::CALENDAR);
     $client->setAuthConfigFile($this->CFG['GOOGLE_API_CLIENT_SECRET_PATH']);
     $client->setAccessType('offline');
     // Load previously authorized credentials from a file.
     $credentialsPath = $this->CFG['GOOGLE_API_CREDENTIALS_PATH'];
     if (file_exists($credentialsPath)) {
         $accessToken = file_get_contents($credentialsPath);
     } else {
         // Request authorization from the user.
         $authUrl = $client->createAuthUrl();
         printf("Open the following link in your browser:\n%s\n", $authUrl);
         print 'Enter verification code: ';
         $authCode = trim(fgets(STDIN));
         // Exchange authorization code for an access token.
         $accessToken = $client->authenticate($authCode);
         // Store the credentials to disk.
         if (!file_exists(dirname($credentialsPath))) {
             mkdir(dirname($credentialsPath), 0700, true);
         }
         file_put_contents($credentialsPath, $accessToken);
         printf("Credentials saved to %s\n", $credentialsPath);
     }
     $client->setAccessToken($accessToken);
     // Refresh the token if it's expired.
     if ($client->isAccessTokenExpired()) {
         $client->refreshToken($client->getRefreshToken());
         file_put_contents($credentialsPath, $client->getAccessToken());
     }
     return $client;
 }
Example #4
1
 public function googleCallbackAction()
 {
     $response = array("status" => 0, "message" => "Thao tác không thành công");
     $code = $this->request->getPost("code", null, false);
     if ($code) {
         $google = new \Google_Client();
         $google->setApplicationName($this->config["GOOGLE_NAME"]);
         $google->setClientId($this->config["GOOGLE_ID"]);
         $google->setClientSecret($this->config["GOOGLE_SECRET"]);
         $google->setRedirectUri('postmessage');
         $scopes = array("https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email");
         $google->setScopes($scopes);
         $google->authenticate($code);
         $request = new \Google_Http_Request("https://www.googleapis.com/oauth2/v2/userinfo?alt=json");
         $userinfo = $google->getAuth()->authenticatedRequest($request);
         $response = $userinfo->getResponseBody();
         $userinfo = json_decode($response, true);
         $id = $userinfo["id"];
         $username = explode("@", $userinfo["email"]);
         $username = $username[0] . "_gg_" . $id;
         $data_user = array("email" => $userinfo["email"], "nickname" => $userinfo["name"], "username" => $username, "id" => $id);
         $response = $this->doSocialLogin($data_user);
     }
     echo json_encode($response);
     exit;
 }
 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;
 }
Example #6
0
 /**
  * @param $code
  * @return string
  */
 public function login($code)
 {
     $this->client->authenticate($code);
     $token = $this->client->getAccessToken();
     \Session::put('token', $token);
     return $token;
 }
Example #7
0
 /**
  * Auth over command line
  */
 public function cmdLineAuth()
 {
     $authUrl = $this->client->createAuthUrl();
     //Request authorization
     print "Please visit:\n{$authUrl}\n\n";
     print "Please enter the auth code:\n";
     $authCode = trim(fgets(STDIN));
     // Exchange authorization code for access token
     $accessToken = $this->client->authenticate($authCode);
     $this->client->setAccessToken($accessToken);
     $this->accessToken = $accessToken;
     $this->refreshToken = $this->client->getRefreshToken();
 }
Example #8
0
 /**
  * Goes through the client authorization routine. This routine both
  * redirects a user to the Google Accounts authorization screen as well as
  * handle the response from the authorization service to retrieve the
  * authorization code then exchange it for an access token. This method
  * also removes the authorization code from the URL to keep things pretty.
  * Details on how the apiClient implements authorization can be found here:
  * http://code.google.com/p/google-api-php-client/source/browse/trunk/src/auth/apiOAuth2.php#84
  * If an authorization error occurs, the exception is caught and the error
  * message is saved in $error.
  */
 public function authenticate()
 {
     try {
         $accessToken = $this->client->authenticate();
         $this->storage->set($accessToken);
         // Keep things pretty. Removes the auth code from the URL.
         if ($_GET['code']) {
             header("Location: {$this->controllerUrl}");
         }
     } catch (Google_AuthException $e) {
         $this->errorMsg = $e->getMessage();
     }
 }
 /**
  * {@inheritDoc}
  */
 public function authenticateUser(Request $request)
 {
     if (!$request->query->has('code')) {
         throw new NotAuthorizedException("There's missing authorization code");
     }
     $fosUserBuilder = new FOSUserBuilder($this->userManager);
     $oauth2 = new \Google_Service_Oauth2($this->client);
     try {
         $this->client->authenticate($request->query->get('code'));
     } catch (\Google_Auth_Exception $e) {
         throw new NotAuthorizedException(401, "XSolve Google Auth couldn't authorize user", $e);
     }
     return $fosUserBuilder->build((array) $oauth2->userinfo->get()->toSimpleObject());
 }
Example #10
0
 public function callback()
 {
     $client = new Google_Client();
     $client->setApplicationName($this->__app_name);
     $client->setClientId($this->__client_id);
     $client->setClientSecret($this->__client_secret);
     $client->setRedirectUri($this->__redirect_uri);
     $client->setDeveloperKey($this->__develop_key);
     $client->setScopes('https://www.googleapis.com/auth/calendar');
     $client->setAccessType('offline');
     if (isset($_GET['code'])) {
         $client->authenticate($_GET['code']);
         $_SESSION['token'] = $client->getAccessToken();
         $this->Session->delete('HTTP_REFERER');
         header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
     }
     // 呼び出し先
     if (isset($_SESSION['oauth_referer'])) {
         $url = $_SESSION['oauth_referer'];
         $this->Session->delete('oauth_referer');
     } else {
         $url = 'index';
     }
     $this->redirect('/');
 }
Example #11
0
 /**
  * Login to facebook and get the associated cloudrexx user.
  */
 public function login()
 {
     $client = new \Google_Client();
     $client->setApplicationName('Contrexx Login');
     $client->setClientId($this->applicationData[0]);
     $client->setClientSecret($this->applicationData[1]);
     $client->setRedirectUri(\Cx\Lib\SocialLogin::getLoginUrl(self::OAUTH_PROVIDER));
     $client->setDeveloperKey($this->applicationData[2]);
     $client->setUseObjects(true);
     $client->setApprovalPrompt('auto');
     $client->setScopes(self::$scopes);
     self::$google = new \Google_Oauth2Service($client);
     self::$googleplus = new \Google_PlusService($client);
     if (isset($_GET['code'])) {
         try {
             $client->authenticate();
         } catch (\Google_AuthException $e) {
         }
     }
     if (!$client->getAccessToken()) {
         \Cx\Core\Csrf\Controller\Csrf::header('Location: ' . $client->createAuthUrl());
         exit;
     }
     self::$userdata = $this->getUserData();
     $this->getContrexxUser(self::$userdata['oauth_id']);
 }
function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName(APPLICATION_NAME);
    $client->setScopes(SCOPES);
    $client->setAuthConfigFile(CLIENT_SECRET_PATH);
    $client->setAccessType('offline');
    $credentialsPath = CREDENTIALS_PATH;
    if (file_exists($credentialsPath)) {
        $accessToken = file_get_contents($credentialsPath);
    } else {
        $authUrl = $client->createAuthUrl();
        printf("Open the following link in your browser:\n%s\n", $authUrl);
        print 'Enter verification code: ';
        $authCode = trim(fgets(STDIN));
        $accessToken = $client->authenticate($authCode);
        if (!file_exists(dirname($credentialsPath))) {
            mkdir(dirname($credentialsPath), 0700, true);
        }
        file_put_contents($credentialsPath, $accessToken);
        printf("Credentials saved to %s\n", $credentialsPath);
    }
    $client->setAccessToken($accessToken);
    if ($client->isAccessTokenExpired()) {
        $client->refreshToken($client->getRefreshToken());
        file_put_contents($credentialsPath, $client->getAccessToken());
    }
    return $client;
}
Example #13
0
 public function get()
 {
     $callback = 'http://api.soundeavor.com/User/Auth/Login/Google/index.php';
     $config = new \Google_Config();
     $config->setApplicationName('Soundeavor');
     $config->setClientId(Config::getConfig('GoogleClientId'));
     $config->setClientSecret(Config::getConfig('GoogleClientSecret'));
     $config->setRedirectUri($callback);
     $client = new \Google_Client($config);
     /*
      * Add scopes (permissions) for the client https://developers.google.com/oauthplayground/
      */
     $client->addScope('https://www.googleapis.com/auth/plus.me');
     if (!isset($_GET['code'])) {
         $loginUrl = $client->createAuthUrl();
         header('Location: ' . $loginUrl);
     }
     $code = $_GET['code'];
     $client->authenticate($code);
     $accessToken = $client->getAccessToken();
     $accessToken = $accessToken['access_token'];
     $service = new \Google_Service_Plus($client);
     $scopes = $service->availableScopes;
     print_r($scopes);
     die;
 }
Example #14
0
 function authorizeGoogleUser($access_code)
 {
     $client = new \Google_Client();
     $google = $this->config->google;
     $client->setApplicationName('Portal da Rede');
     $client->setClientId($google->clientId);
     $client->setClientSecret($google->secret);
     $client->setRedirectUri('postmessage');
     $client->addScope('https://www.googleapis.com/auth/userinfo.profile');
     $client->addScope('https://www.googleapis.com/auth/userinfo.email');
     $client->authenticate($access_code);
     $json_token = $client->getAccessToken();
     $client->setAccessToken($json_token);
     $plus = new \Google_Service_Plus($client);
     $user = $plus->people->get('me');
     if (!$user->emails || !is_array($user->emails)) {
         return;
     }
     $email = $user->emails[0]['value'];
     $user_email = $this->db->user_email->find_one($email);
     if (!$user_email) {
         return;
     }
     $this->login($user_email->user);
 }
    /**
     * Check, if the analytics account is authenticated and has an access token.
     * Authenticate it, if it is not.
     *
     * TODO: have the access token in a transient and check if the token expired before continuing
     *
     * @return bool
     */
    function is_app_authenticated()
    {
        $access_token = WooCommerce_Grow_Helpers::get_option('access_token');
        // We have an access token already
        if (!empty($access_token)) {
            try {
                $this->client->setAccessToken($access_token);
            } catch (Exception $e) {
                echo sprintf(__('Error: Unable to set Google Analytics access token. Error Code: %s. Error Message: %s  ', 'woocommerce-grow'), $e->getCode(), $e->getMessage());
                return false;
            }
        } else {
            $settings = get_option('woocommerce_woocommerce_grow_settings', array());
            $auth_code = WooCommerce_Grow_Helpers::get_field('authorization_token', $settings);
            if (empty($auth_code)) {
                // TODO: needs behavior
                return false;
            }
            try {
                // The authenticate method gets an access token, sets the access token
                // and returns the access token all at once.
                $access_token = $this->client->authenticate($auth_code);
                $this->client->setAccessToken($access_token);
                WooCommerce_Grow_Helpers::update_option('access_token', $access_token);
            } catch (Exception $e) {
                echo sprintf(__('Google Analytics was unable to authenticate you.
						Please refresh and try again. If the problem persists, please obtain a new authorizations token.
						Error Code: %s. Error Message: %s  ', 'woocommerce-grow'), $e->getCode(), $e->getMessage());
                return false;
            }
        }
        return true;
    }
Example #16
0
function bdn_is_user_auth2()
{
    global $driveService;
    $current_user_id = get_current_user_id();
    $client = new Google_Client();
    $client->setRedirectUri(home_url('/'));
    $driveService = new Google_DriveService($client);
    $oauth2 = new Google_Oauth2Service($client);
    if (!isset($_GET['code']) && (!is_user_logged_in() || ($access_token = get_user_meta($current_user_id, '_google_access_token', true)) && $client->setAccessToken($access_token) && !$client->getAccessToken())) {
        header('Location: ' . $client->createAuthUrl());
        exit;
    }
    if (isset($_GET['code'])) {
        $client->authenticate($_GET['code']);
        $user = $oauth2->userinfo->get();
        $new_user = get_user_by('email', $user['email']);
        if (!$current_user_id) {
            wp_set_current_user($new_user->ID, $new_user->user_login);
            wp_set_auth_cookie($new_user->ID);
            do_action('wp_login', $new_user->user_login);
        } elseif ($new_user->ID == $current_user_id) {
            update_user_meta($new_user->ID, '_google_access_token', $client->getAccessToken());
        } else {
            die('Sorry, please use your BDN account');
        }
        header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
    }
    return $driveService;
}
Example #17
0
function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName(APPLICATION_NAME);
    $client->setScopes(SCOPES);
    $client->setAuthConfigFile(CLIENT_SECRET);
    $client->setAccessType('offline');
    // Load previously authorized credentials from a file.
    $credentialsPath = expandHomeDirectory(CREDENTIAL_PATH);
    if (file_exists($credentialsPath)) {
        $accessToken = file_get_contents($credentialsPath);
    } else {
        // Request authorization from the user.
        $authUrl = $client->createAuthUrl();
        printf("Open the following link in your browser:\n\n\t%s\n\n", $authUrl);
        print 'Enter verification code: ';
        $authCode = trim(fgets(STDIN));
        // Exchange authorization code for an access token.
        $accessToken = $client->authenticate($authCode);
        // Store the credentials to disk.
        if (!file_exists(dirname($credentialsPath))) {
            mkdir(dirname($credentialsPath), 0700, true);
        }
        file_put_contents($credentialsPath, $accessToken);
        printf("Credentials saved to %s\n", $credentialsPath);
    }
    $client->setAccessToken($accessToken);
    // Refresh the token if it's expired.
    if ($client->isAccessTokenExpired()) {
        $client->refreshToken($client->getRefreshToken());
        file_put_contents($credentialsPath, $client->getAccessToken());
    }
    return $client;
}
Example #18
0
 public function googlecallback()
 {
     $ret = null;
     //$google_redirect_url = site_url('user/signup');
     $google_redirect_url = 'http://localhost/punu/punu/index.php/user/signup';
     $client = new Google_Client();
     $client->setClientId($this->google_client_id);
     $client->setClientSecret($this->google_client_secret);
     $client->setDeveloperKey($this->google_api_key);
     $client->setRedirectUri($google_redirect_url);
     $client->addScope($this->google_scope);
     // Send Client Request
     $objOAuthService = new Google_Service_Oauth2($client);
     // Add Access Token to Session
     if (isset($_GET['code'])) {
         $client->authenticate($_GET['code']);
         $_SESSION['google_access_token'] = $client->getAccessToken();
         //header('Location: ' . filter_var($this->google_redirect_url, FILTER_SANITIZE_URL));
     }
     // Set Access Token to make Request
     if (isset($_SESSION['google_access_token']) && $_SESSION['google_access_token']) {
         $client->setAccessToken($_SESSION['google_access_token']);
     }
     // Get User Data from Google and store them in $data
     if ($client->getAccessToken()) {
         $userData = $objOAuthService->userinfo->get();
         //$_SESSION['userData'] = $userData;
         $_SESSION['google_access_token'] = $client->getAccessToken();
         $ret = $userData;
     }
     return $ret;
 }
Example #19
0
/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName("Study Group Finder");
    $client->setAuthConfigFile(__DIR__ . '/client_secret.json');
    $client->addScope(Google_Service_Calendar::CALENDAR);
    $client->setRedirectUri(current_url());
    if (isset($_SESSION["googleauth"])) {
        $client->setAccessToken($_SESSION["googleauth"]);
        $_SESSION["googleauth"] = NULL;
        return $client;
    }
    if (!isset($_GET['code'])) {
        // Request authorization from the user.
        $authUrl = $client->createAuthUrl();
        header("Location: {$authUrl}");
        exit(0);
    }
    $authCode = $_GET['code'];
    // Exchange authorization code for an access token.
    $accessToken = $client->authenticate($authCode);
    $_SESSION["googleauth"] = $accessToken;
    header("Location: calendar.php");
    exit(0);
}
Example #20
0
function getClient()
{
    $config = (include __DIR__ . '/ini.php');
    $client = new Google_Client();
    $client->setApplicationName("Webkameleon");
    $client->setClientId($config['oauth2_client_id']);
    $client->setClientSecret($config['oauth2_client_secret']);
    $client->setRedirectUri($config['oauth2_redirect_uri']);
    $client->setScopes($config['oauth2_scopes']);
    $client->setState('offline');
    $client->setAccessType('offline');
    $client->setApprovalPrompt('force');
    if (isset($_GET['code'])) {
        $client->authenticate($_GET['code']);
        die($client->getAccessToken());
    } elseif (!isset($config['token'])) {
        Header('Location: ' . $client->createAuthUrl());
    } else {
        $client->setAccessToken($config['token']);
        if ($client->isAccessTokenExpired()) {
            $token = json_decode($config['token'], true);
            $client->refreshToken($token['refresh_token']);
        }
    }
    return $client;
}
Example #21
0
 /**
  * Callback method during authentication.
  *
  * @return void
  */
 public function callback()
 {
     if ($code = optional_param('oauth2code', null, PARAM_RAW)) {
         $this->client->authenticate($code);
         $this->store_access_token($this->client->getAccessToken());
     }
 }
Example #22
0
 public function call_back()
 {
     $config = new Controllers_Api_Google_Config_App();
     $client = new Google_Client();
     $client->setClientId($config->config['client_id']);
     $client->setClientSecret($config->config['client_secret']);
     $client->setRedirectUri($config->config['redirect_uri']);
     $client->addScope("email");
     $client->addScope("profile");
     $service = new Google_Service_Oauth2($client);
     if (isset($_GET['code'])) {
         $client->authenticate($_GET['code']);
         $_SESSION['access_token'] = $client->getAccessToken();
         header('Location: ' . filter_var($config->config['redirect_uri'], FILTER_SANITIZE_URL));
         exit;
     }
     /************************************************
         If we have an access token, we can make
         requests, else we generate an authentication URL.
        ************************************************/
     if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
         $client->setAccessToken($_SESSION['access_token']);
     } else {
         $authUrl = $client->createAuthUrl();
     }
     if (isset($authUrl)) {
         //show login url
         echo json_encode(array('status' => false, 'data' => $authUrl));
     } else {
         $user = $service->userinfo->get();
         //get user info
         echo json_encode(array('status' => true, 'data' => $user));
     }
 }
 /**
  * @param string $requestCode
  * @param string $requestState
  * @param string $sessionState
  * @return array|null
  */
 public function authenticate($requestCode, $requestState, $sessionState)
 {
     if ((string) $sessionState !== (string) $requestState) {
         return null;
     }
     $this->googleApiClient->authenticate($requestCode);
     return $this->googleApiClient->getAccessToken();
 }
Example #24
0
 public function index()
 {
     //        include_once APPPATH . 'libraries/Facebook/facebook.php';
     //        $facebook = new Facebook([
     //            'appId' => '852953064822534',
     //            'secret' => '29888930212d679180731cc5232732c8'
     //        ]);
     //        $user = $facebook->getUser();
     include_once APPPATH . 'libraries/Google/autoload.php';
     $client_id = GOOGLE_CLIENT_ID;
     $client_secret = GOOGLE_CLIENT_SECRET;
     $redirect_uri = GOOGLE_REDIRECT_URL;
     // Create Client Request to access Google API
     $client = new Google_Client();
     $client->setApplicationName("PHP Google OAuth Login Example");
     $client->setClientId($client_id);
     $client->setClientSecret($client_secret);
     $client->setRedirectUri($redirect_uri);
     $client->addScope("https://www.googleapis.com/auth/userinfo.email");
     // Send Client Request
     $objOAuthService = new Google_Service_Oauth2($client);
     // Add Access Token to Session
     if (isset($_GET['code'])) {
         $client->authenticate($_GET['code']);
         $this->session->set_userdata(array('access_token' => $client->getAccessToken()));
         //            header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
     }
     // Set Access Token to make Request
     if ($this->session->userdata('access_token') != null) {
         $client->setAccessToken($this->session->userdata('access_token'));
     }
     // Get User Data from Google and store them in $data
     if ($client->getAccessToken()) {
         $userData = $objOAuthService->userinfo->get();
         $data['userData'] = $userData;
         $this->session->set_userdata(array('access_token' => $client->getAccessToken()));
         $ret = $this->User_model->addUser($data['userData']);
         if ($ret == 'SUSPENDED') {
             $unset = array('access_token');
             $this->session->unset_userdata($unset);
             $newdata = array('error' => "<font color='red'>Your account has been suspended</font>");
             $this->session->set_flashdata($newdata);
             redirect('signin');
         } else {
             if ($ret == 'FAIL') {
                 $newdata = array('error' => "<font color='red'>Something is issue with login</font>");
                 $this->session->set_flashdata($newdata);
                 redirect('signin');
             }
         }
         redirect('dashboard');
     } else {
         $authUrl = $client->createAuthUrl();
         $data['authUrl'] = $authUrl;
         //            $data['fbLoginUrl'] = $fbLoginUrl;
         loadView('signIn', $data);
     }
 }
 public function index()
 {
     if ($this->input->get("error") && $this->input->get("error") == 'access_denied') {
         redirect("login");
     }
     // Include the google api php libraries
     include_once APPPATH . "libraries/google-api-php-client/Google_Client.php";
     include_once APPPATH . "libraries/google-api-php-client/contrib/Google_Oauth2Service.php";
     // Google Project API Credentials
     $clientId = '438313202103-5ts2epm0c9b8mlj4ddf4lkis3l2qmkq0.apps.googleusercontent.com';
     $clientSecret = 'KIW-gQpaglq1dwa3gBAerJdP';
     $redirectUrl = 'http://99rightdeals.com/gmail_signup';
     // Google Client Configuration
     $gClient = new Google_Client();
     $gClient->setApplicationName('99rightdeals');
     $gClient->setClientId($clientId);
     $gClient->setClientSecret($clientSecret);
     $gClient->setRedirectUri($redirectUrl);
     $google_oauthV2 = new Google_Oauth2Service($gClient);
     if (isset($_REQUEST['code'])) {
         $gClient->authenticate();
         $this->session->set_userdata('token', $gClient->getAccessToken());
         redirect($redirectUrl);
     }
     $token = $this->session->userdata('token');
     if (!empty($token)) {
         $gClient->setAccessToken($token);
     }
     if ($gClient->getAccessToken()) {
         $userProfile = $google_oauthV2->userinfo->get();
         // Preparing data for database insertion
         $userData['oauth_provider'] = 'google';
         $userData['oauth_uid'] = $userProfile['id'];
         $userData['first_name'] = $userProfile['given_name'];
         $userData['last_name'] = $userProfile['family_name'];
         $userData['email'] = $userProfile['email'];
         $userData['locale'] = $userProfile['locale'];
         //$userData['profile_url'] = $userProfile['link'];
         //$userData['picture_url'] = $userProfile['picture'];
     }
     $already = $this->signup_model->onloadgmail_already($userData['oauth_uid']);
     if ($already == 1) {
         redirect('/');
     }
     $data = array("title" => "Classifieds", "content" => "gmailsignup", 'gmail_data' => $userData);
     if ($this->input->post("submit")) {
         $already = $this->signup_model->gmail_already();
         if ($already == 1) {
             redirect('/');
         } else {
             $this->signup_model->gmail_create();
             redirect('/');
         }
     }
     $this->load->view("classified_layout/inner_template", $data);
 }
Example #26
0
 public function index()
 {
     $this->load->helper('url');
     //For load css from config file
     $ci =& get_instance();
     $header_js = $ci->config->item('css');
     // Include two files from google-php-client library in controller
     require_once APPPATH . "libraries/google-api-php-client-master/src/Google/autoload.php";
     require_once APPPATH . "libraries/google-api-php-client-master/src/Google/Client.php";
     require_once APPPATH . "libraries/google-api-php-client-master/src/Google/Service/Oauth2.php";
     // Store values in variables from project created in Google Developer Console
     $client_id = '180391628117-hf4di0a3l0aaq10c6h933n97p4e1lb2m.apps.googleusercontent.com';
     $client_secret = 'Eg_i_sihLL5E5FMGTnyKSVXK';
     $redirect_uri = 'http://citest.local.com/index.php/login';
     $simple_api_key = 'AIzaSyCSS5nGOzy7OcuSvSMwblVRRPZ9_TFIDnM';
     // Create Client Request to access Google API
     $client = new Google_Client();
     $client->setApplicationName("PHP Google OAuth Login Example");
     $client->setClientId($client_id);
     $client->setClientSecret($client_secret);
     $client->setRedirectUri($redirect_uri);
     $client->setDeveloperKey($simple_api_key);
     $client->addScope("https://www.googleapis.com/auth/userinfo.email");
     // Send Client Request
     $objOAuthService = new Google_Service_Oauth2($client);
     // Add Access Token to Session
     if (isset($_GET['code'])) {
         $client->authenticate($_GET['code']);
         $_SESSION['access_token'] = $client->getAccessToken();
         header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
     }
     // Set Access Token to make Request
     if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
         $client->setAccessToken($_SESSION['access_token']);
     }
     // Get User Data from Google and store them in $data
     if ($client->getAccessToken()) {
         $userData = $objOAuthService->userinfo->get();
         //Save google login user data in database
         $saveData = array('name' => $userData['name'], 'email' => $userData['email'], 'gender' => $userData['gender']);
         $this->user_model->saveUserData($saveData);
         $data['userData'] = $userData;
         $_SESSION['access_token'] = $client->getAccessToken();
     } else {
         $authUrl = $client->createAuthUrl();
         $data['authUrl'] = $authUrl;
     }
     //Load css file added in config file
     $str = '';
     foreach ($header_js as $key => $val) {
         $str .= '<link rel="stylesheet" href="' . base_url() . 'css/' . $val . '" type="text/css" />' . "\n";
     }
     $data['css'] = $str;
     // Load view and send values stored in $data
     $this->load->view('google_authentication', $data);
 }
 public function code()
 {
     $client = new \Google_Client();
     $client->setClientId(Setting::get('google-identity', 'client_id'));
     $client->setClientSecret(Setting::get('google-identity', 'client_secret'));
     $client->setRedirectUri('postmessage');
     $client->authenticate($this->getParam('code'));
     Setting::set('google-identity', 'access_token', $client->getAccessToken());
     return $this->info();
 }
Example #28
0
 /**
  * @param array $credentials
  * @return Identity
  * @throws AuthenticationException
  */
 public function authenticate(array $credentials)
 {
     list($code) = $credentials;
     try {
         $this->googleClient->authenticate($code);
         $this->googleClient->setAccessToken($this->googleClient->getAccessToken());
         $oauth2 = new \Google_Oauth2Service($this->googleClient);
         $googleUser = $oauth2->userinfo->get();
         if (isset($googleUser['email'])) {
             $email = filter_var($googleUser['email'], FILTER_SANITIZE_EMAIL);
             $user = $this->users->getUser($email);
             if ($user === NULL && $this->autoRegister === FALSE || $user instanceof UserEntity && $user->getActive() == 0) {
                 throw new AuthenticationException("User '{$email}' not found.", self::IDENTITY_NOT_FOUND);
             } else {
                 if ($user === NULL && $this->autoRegister === TRUE) {
                     $result = $this->users->register(array("login" => $email, "password" => Strings::random(), "name" => isset($googleUser['name']) ? $googleUser['name'] : NULL, "firstname" => isset($googleUser['given_name']) ? $googleUser['given_name'] : NULL, "lastname" => isset($googleUser['family_name']) ? $googleUser['family_name'] : NULL, "lastLogged" => new DateTime(), "ip" => $_SERVER['REMOTE_ADDR']));
                     if ($result instanceof ContactEntity) {
                         return new Identity($result->userID, $result->getUser()->role->name, $result->getUser()->toArray());
                     } else {
                         throw new AuthenticationException("User '{$email}' cannot be registered.", self::IDENTITY_NOT_FOUND);
                     }
                 } else {
                     if ($user instanceof UserEntity) {
                         $user->setLastLogged(new DateTime());
                         $user->setIp($_SERVER['REMOTE_ADDR']);
                         $this->users->updateUser($user);
                         $data = $user->toArray();
                         unset($data['password']);
                         return new Identity($user->userID, $user->role->name, $data);
                     } else {
                         throw new AuthenticationException("User '{$email}' cannot be connected.", self::IDENTITY_NOT_FOUND);
                     }
                 }
             }
         } else {
             throw new AuthenticationException("Uživatel nenalezen.");
         }
     } catch (\Google_AuthException $e) {
         throw new AuthenticationException($e->getMessage());
     } catch (\Google_ServiceException $e) {
         throw new AuthenticationException($e->getMessage());
     }
 }
Example #29
0
 public function index()
 {
     // パスが通っていなければ設定
     $path = 'http://192.168.99.21/app/Vendor/google-api-php-client/src';
     set_include_path(get_include_path() . PATH_SEPARATOR . $path);
     App::import('Vendor', 'Google_Client', array('file' => 'google-api-php-client/src/Google/Client.php'));
     App::import('Vendor', 'Google_Service', array('file' => 'google-api-php-client/src/Google/Service.php'));
     App::import('Vendor', 'Google_Service_Model', array('file' => 'google-api-php-client/src/Google/Model.php'));
     App::import('Vendor', 'Google_Service_Collection', array('file' => 'google-api-php-client/src/Google/Collection.php'));
     App::import('Vendor', 'Google_Service_Resource', array('file' => 'google-api-php-client/src/Google/Service/Resource.php'));
     App::import('Vendor', 'Google_Service_Analytics', array('file' => 'google-api-php-client/src/Google/Service/Analytics.php'));
     // Google Developers Consoleで作成されたクライアントID
     define('CLIENT_ID', '3274760987-rec90linuevn0ahdi5ck5212gg54m3ur.apps.googleusercontent.com');
     // Google Developers Consoleで作成されたクライアントシークレット
     define('CLIENT_SECRET', 'F_aDjo5IqA2Zn4Dz7gA4sgAm');
     // Google Developers Consoleで作成されたリダイレクトURI
     define('REDIRECT_URI', 'http://' . $_SERVER['HTTP_HOST'] . '/analytics');
     $client = new Google_Client();
     $client->setClientId(CLIENT_ID);
     $client->setClientSecret(CLIENT_SECRET);
     $client->setRedirectUri(REDIRECT_URI);
     $client->addScope('https://www.googleapis.com/auth/analytics.readonly');
     $analytics = new Google_Service_Analytics($client);
     // 認証後codeを受け取ったらセッション保存
     if (isset($this->request->query['code'])) {
         $client->authenticate($this->request->query['code']);
         $this->Session->write('token', $client->getAccessToken());
         $this->redirect('http://' . $_SERVER['HTTP_HOST'] . '/analytics');
     }
     if ($this->Session->check('token')) {
         $client->setAccessToken($this->Session->read('token'));
     }
     if ($client->getAccessToken()) {
         $start_date = date('Y-m-d', strtotime('- 10 day'));
         $end_date = date('Y-m-d');
         // GoogleAnalyticsの「アナリティクス設定」>「ビュー」>「ビュー設定」の「ビューID」
         $view = '106133184';
         // データ取得
         $data = array();
         $dimensions = 'ga:date';
         $metrics = 'ga:visits';
         $sort = 'ga:date';
         $optParams = array('dimensions' => $dimensions, 'sort' => $sort);
         $results = $analytics->data_ga->get('ga:' . $view, $start_date, $end_date, $metrics, $optParams);
         if (isset($results['rows']) && !empty($results['rows'])) {
             $data['Sample']['date'] = $results['rows'][0][0];
             $data['Sample']['visits'] = $results['rows'][0][1];
         }
         pr($data);
     } else {
         $auth_url = $client->createAuthUrl();
         echo '<a href="' . $auth_url . '">認証</a>';
     }
     exit;
 }
 /**
  * Return info about login user
  * @param $code
  * @return \Google_Service_Oauth2_Userinfoplus
  * @throws Exception
  */
 public function getMe($code)
 {
     $google_oauthV2 = new \Google_Service_Oauth2($this->client);
     try {
         $this->client->authenticate($code);
         $user = $google_oauthV2->userinfo->get();
     } catch (\Google_Auth_Exception $e) {
         throw new Exception($e->getMessage());
     }
     $this->setSocialLoginCookie(self::SOCIAL_NAME);
     return $user;
 }