Example #1
0
 /**
  * Log in using a Google account.
  */
 public function actionGoogleLogin()
 {
     $this->layout = '//layouts/login';
     $model = new LoginForm();
     $model->useCaptcha = false;
     // echo var_dump(Session::getOnlineUsers());
     if (Yii::app()->user->isInitialized && !Yii::app()->user->isGuest) {
         $this->redirect(Yii::app()->homeUrl);
         return;
     }
     require_once 'protected/components/GoogleAuthenticator.php';
     $auth = new GoogleAuthenticator();
     if (Yii::app()->settings->googleIntegration && ($token = $auth->getAccessToken())) {
         try {
             $user = $auth->getUserInfo($token);
             $email = filter_var($user->email, FILTER_SANITIZE_EMAIL);
             $profileRecord = X2Model::model('Profile')->findByAttributes(array('googleId' => $email));
             if (!isset($profileRecord)) {
                 $userRecord = X2Model::model('User')->findByAttributes(array('emailAddress' => $email));
                 $profileRecord = X2Model::model('Profile')->findByAttributes(array(), "emailAddress=:email OR googleId=:email", array(':email' => $email));
             }
             if (isset($userRecord) || isset($profileRecord)) {
                 if (!isset($profileRecord)) {
                     $profileRecord = X2Model::model('Profile')->findByPk($userRecord->id);
                 }
                 $auth->storeCredentials($profileRecord->id, $_SESSION['access_token']);
             }
             if (isset($userRecord) || isset($profileRecord)) {
                 if (!isset($userRecord)) {
                     $userRecord = User::model()->findByPk($profileRecord->id);
                 }
                 $username = $userRecord->username;
                 $password = $userRecord->password;
                 $model->username = $username;
                 $model->password = $password;
                 if ($model->login(true)) {
                     $ip = $this->getRealIp();
                     Session::cleanUpSessions();
                     if (isset($_SESSION['sessionId'])) {
                         $sessionId = $_SESSION['sessionId'];
                     } else {
                         $sessionId = $_SESSION['sessionId'] = session_id();
                     }
                     $session = X2Model::model('Session')->findByPk($sessionId);
                     // if this client has already tried to log in, increment their attempt count
                     if ($session === null) {
                         $session = new Session();
                         $session->id = $sessionId;
                         $session->user = $model->getSessionUsername();
                         $session->lastUpdated = time();
                         $session->status = 1;
                         $session->IP = $ip;
                     } else {
                         $session->lastUpdated = time();
                     }
                     // x2base::cleanUpSessions();
                     // $session = X2Model::model('Session')->findByAttributes(array('user'=>$userRecord->username,'IP'=>$ip));
                     // if(isset($session)) {
                     // $session->lastUpdated = time();
                     // } else {
                     // $session = new Session;
                     // $session->user = $model->username;
                     // $session->lastUpdated = time();
                     // $session->status = 1;
                     // $session->IP = $ip;
                     // }
                     $session->save();
                     SessionLog::logSession($userRecord->username, $sessionId, 'googleLogin');
                     $userRecord->login = time();
                     $userRecord->save();
                     Yii::app()->session['versionCheck'] = true;
                     Yii::app()->session['loginTime'] = time();
                     $session->status = 1;
                     if (Yii::app()->user->returnUrl == 'site/index') {
                         $this->redirect(array('/site/index'));
                     } else {
                         $this->redirect(Yii::app()->user->returnUrl);
                     }
                 }
             } else {
                 $this->render('googleLogin', array('failure' => 'email', 'email' => $email));
             }
         } catch (Google_AuthException $e) {
             $auth->flushCredentials();
             $auth->setErrors($e->getMessage());
             $this->render('googleLogin', array('failure' => $auth->getErrors()));
         } catch (NoUserIdException $e) {
             $auth->flushCredentials();
             $auth->setErrors($e->getMessage());
             $this->render('googleLogin', array('failure' => $auth->getErrors()));
         }
     } else {
         $this->render('googleLogin');
     }
 }
Example #2
0
 public function actionSyncActionsToGoogleCalendar()
 {
     $errors = array();
     $model = Yii::app()->params->profile;
     $client = null;
     if (isset($_POST['Profile'])) {
         foreach (array_keys($model->attributes) as $field) {
             if (isset($_POST['Profile'][$field])) {
                 $model->{$field} = $_POST['Profile'][$field];
             }
         }
         if ($model->syncGoogleCalendarId && isset($_SESSION['token'])) {
             $token = json_decode($_SESSION['token'], true);
             // used for accessing this google calendar at a later time
             //$model->syncGoogleCalendarRefreshToken = $token['refresh_token'];
             $model->syncGoogleCalendarAccessToken = $_SESSION['token'];
         }
         $model->update();
     }
     if (isset($_SESSION['calendarForceRefresh']) && $_SESSION['calendarForceRefresh']) {
         unset($_SESSION['calendarForceRefresh']);
         Yii::app()->user->setFlash('error', 'Your Refresh Token was invalid and needed to be refreshed. The last action you ' . 'attempted to Sync with Google did not successfully synchronize.');
     }
     $admin = Yii::app()->settings;
     $googleIntegration = $admin->googleIntegration;
     /* if google integration is activated let user choose if they want to link this calendar 
        to a google calendar */
     if ($googleIntegration) {
         //            $timezone = date_default_timezone_get();
         //            require_once "protected/extensions/google-api-php-client/src/Google_Client.php";
         //            require_once "protected/extensions/google-api-php-client/src/contrib/Google_CalendarService.php"; // for google calendar sync
         //            require_once 'protected/extensions/google-api-php-client/src/contrib/Google_Oauth2Service.php'; // for google oauth login
         //            date_default_timezone_set($timezone);
         $auth = new GoogleAuthenticator();
         /* name of the Google Calendar that current user's actions are being synced to if it 
            has been set */
         $syncGoogleCalendarName = null;
         try {
             if (isset($_GET['unlinkGoogleCalendar'])) {
                 // user changed their mind about linking their google calendar
                 unset($_SESSION['token']);
                 $model->syncGoogleCalendarId = null;
                 // used for accessing this google calendar at a later time
                 //$model->syncGoogleCalendarRefreshToken = null;
                 $model->syncGoogleCalendarAccessToken = null;
                 $model->update();
                 $googleCalendarList = null;
                 if ($auth->getAccessToken()) {
                     $googleCalendar = $auth->getCalendarService();
                     try {
                         $calList = $googleCalendar->calendarList->listCalendarList();
                         $googleCalendarList = array();
                         foreach ($calList['items'] as $cal) {
                             $googleCalendarList[$cal['id']] = $cal['summary'];
                         }
                     } catch (Google_ServiceException $e) {
                         if ($e->getCode() == '403') {
                             $errors[] = $e->getMessage();
                             Yii::app()->user->setFlash('error', $e->getMessage());
                             $googleCalendarList = null;
                             //$auth->flushCredentials();
                         } elseif ($e->getCode() == '401') {
                             $errors[] = 'Invalid user credentials provided. Please try again.';
                             Yii::app()->user->setFlash('error', 'Invalid user credentials. Please ensure your account is ' . 'able to use this service or delete the access permissions ' . 'and try again.');
                             $googleCalendarList = null;
                             $auth->flushCredentials();
                         }
                     }
                 } else {
                     $googleCalendarList = null;
                 }
             } else {
                 if ($auth->getAccessToken()) {
                     $googleCalendar = $auth->getCalendarService();
                     try {
                         $calList = $googleCalendar->calendarList->listCalendarList();
                         $googleCalendarList = array();
                         foreach ($calList['items'] as $cal) {
                             $googleCalendarList[$cal['id']] = $cal['summary'];
                         }
                     } catch (Google_ServiceException $e) {
                         if ($e->getCode() == '403') {
                             $errors[] = 'Google Calendar API access has not been configured.';
                             Yii::app()->user->setFlash('error', 'Google Calendar API access has not been configured.');
                             $googleCalendarList = null;
                             //$auth->flushCredentials();
                         } elseif ($e->getCode() == '401') {
                             $errors[] = 'Invalid user credentials provided. Please try again.';
                             Yii::app()->user->setFlash('error', 'Invalid user credentials. Please ensure your account is ' . 'able to use this service or delete the access permissions ' . 'and try again.');
                             $googleCalendarList = null;
                             $auth->flushCredentials();
                         }
                     }
                 } else {
                     $googleCalendarList = null;
                 }
             }
         } catch (Google_AuthException $e) {
             $auth->flushCredentials();
             $auth->setErrors($e->getMessage());
             $client = null;
             $googleCalendarList = null;
             $syncGoogleCalendarName = null;
         }
     } else {
         $client = null;
         $googleCalendarList = null;
         $syncGoogleCalendarName = null;
     }
     $syncGoogleCalendarId = Yii::app()->params->profile->syncGoogleCalendarId;
     $this->render('syncActionsToGoogleCalendar', array('errors' => $errors, 'auth' => isset($auth) ? $auth : null, 'model' => $model, 'googleIntegration' => $googleIntegration, 'client' => $client, 'googleCalendarList' => $googleCalendarList, 'syncGoogleCalendarName' => $syncGoogleCalendarId));
 }
Example #3
0
 public function printFolder($folderId, $auth = null)
 {
     if (is_null($auth)) {
         $auth = new GoogleAuthenticator();
     }
     $service = $auth->getDriveService();
     try {
         if ($service) {
             $ret = "";
             $files = $service->files;
             $fileList = $files->listFiles(array('q' => 'trashed=false and "' . $folderId . '" in parents'));
             $folderList = array();
             $fileArray = array();
             foreach ($fileList['items'] as $file) {
                 if ($file['mimeType'] == 'application/vnd.google-apps.folder') {
                     $folderList[] = $file;
                 } else {
                     $fileArray[] = $file;
                 }
             }
             $fileList = array_merge($folderList, $fileArray);
             foreach ($fileList as $file) {
                 if ($file['mimeType'] == 'application/vnd.google-apps.folder') {
                     $ret .= "<div class='drive-wrapper'><div class='drive-item'><div class='drive-icon' style='background:url(\"" . $file['iconLink'] . "\") no-repeat'></div><a href='#' class='toggle-file-system drive-link' data-id='{$file['id']}'> " . $file['title'] . "</a></div></div>";
                     $ret .= "<div class='drive' id='{$file['id']}' style='display:none;'>";
                     $ret .= "</div>";
                 } else {
                     $ret .= "<div class='drive-wrapper'><div class='drive-item'><div class='drive-icon' style='background:url(\"" . $file['iconLink'] . "\") no-repeat'></div> <a class='x2-link drive-link media' href='" . $file['alternateLink'] . "' target='_blank'>" . $file['title'] . "</a></div></div>";
                 }
             }
             return $ret;
         } else {
             return false;
         }
     } catch (Google_AuthException $e) {
         if (isset($_SESSION['access_token']) || isset($_SESSION['token'])) {
             // If these are set it's possible the token expired and there is a refresh token available
             $auth->flushCredentials(false);
             // Only flush the recently received information
             return $this->printFolder($folderId);
             // Try again, it will use a refresh token if available this time, otherwise it will fail.
         } else {
             $auth->flushCredentials();
             $auth->setErrors($e->getMessage());
             return false;
         }
     } catch (Google_ServiceException $e) {
         $auth->setErrors($e->getMessage());
         return false;
     }
 }