/**
  * Verify the entered code
  *
  * @access  public
  * @since   2.2
  */
 public function check_code($post_data)
 {
     $auth = new GoogleAuthenticator();
     $user = get_user_by('login', trim($_POST['rcp_user_login']));
     $success = $auth->check_otp($user, trim($_POST['rcp_user_login']), trim($_POST['rcp_user_pass']));
     if (is_wp_error($success)) {
         rcp_errors()->add('auth_failed', $success->get_error_message(), 'login');
     }
 }
Exemplo n.º 2
0
 public function init()
 {
     $this->drive = Yii::app()->params->profile->mediaWidgetDrive && Yii::app()->settings->googleIntegration;
     if (Yii::app()->settings->googleIntegration) {
         $auth = new GoogleAuthenticator();
         if (!isset($_SESSION['driveFiles']) && $auth->getAccessToken()) {
             Yii::import('application.modules.media.controllers.MediaController');
             $mediaController = new MediaController('MediaController');
             $_SESSION['driveFiles'] = $mediaController->printFolder('root', $auth);
         }
     }
     parent::init();
 }
Exemplo n.º 3
0
 public function generateSecret()
 {
     $g = new GoogleAuthenticator();
     $secret = $g->generateSecret();
     $this->data['secret'] = $secret;
     return $secret;
 }
 /**
  * Authenticates the identity contained in a request.  Will use the `settings.userModel`, and `settings.fields`
  * to find POST data that is used to find a matching record in the `settings.userModel`.  Will return false if
  * there is no post data, either username or password is missing, of if the scope conditions have not been met.
  *
  * @param CakeRequest $request The request that contains login information.
  * @param CakeResponse $response Unused response object.
  * @return mixed.  False on login failure.  An array of User data on success.
  */
 public function authenticate(CakeRequest $request, CakeResponse $response)
 {
     list(, $model) = pluginSplit($this->settings['userModel']);
     if (!$this->_checkFields($request->data)) {
         return false;
     }
     $fields = $this->settings['fields'];
     $user = $this->_findUser($request->data[$model][$fields['username']], $request->data[$model][$fields['password']]);
     if (!$user) {
         return false;
     }
     if (empty($user[$fields['secret']])) {
         return $user;
     }
     if (!$this->_checkFields($request->data, array('code'))) {
         return false;
     }
     $Google = new GoogleAuthenticator();
     return $Google->checkCode($user[$fields['secret']], $request->data[$model][$fields['code']]) ? $user : false;
 }
Exemplo n.º 5
0
function twofactors_set()
{
    global $tpl, $srcdir;
    $usr = new Modele('users');
    $usr->fetch($_SESSION['user']['user_id']);
    if ($_POST['activation'] == "true") {
        require_once $srcdir . '/libs/GoogleAuthenticator/GoogleAuthenticator.php';
        $otp = new GoogleAuthenticator();
        if (!$otp->checkCode($_SESSION['user']['GoogleAuthenticator'], $_POST['code'])) {
            $tpl->assign('hsuccess', "GoogleAuthentificator code invalide");
            modexec("index", "profile");
            quit();
        }
        $usr->user_otp = $_SESSION['user']['GoogleAuthenticator'];
    } else {
        $usr->user_otp = "";
    }
    $_SESSION['user']['user_otp'] = $usr->user_otp;
    redirect("index", "profile", array('hsuccess' => 1));
}
Exemplo n.º 6
0
 /**
  * If there were no login attempt or it failed render login form page
  * otherwise redirect him to wherever he should return to.
  *
  * Also, this endpoint serves as the AJAX endpoint for client-side validation of login info.
  */
 public function run()
 {
     $user = Yii::app()->user;
     $this->redirectAwayAlreadyAuthenticatedUsers($user);
     $model = new BackendLoginForm();
     $request = Yii::app()->request;
     $gaform = new GoogleAuthForm();
     $formData = $request->getPost(get_class($model), false);
     $gaFormData = $request->getPost(get_class($gaform), false);
     if ($formData) {
         $model->attributes = $formData;
         if ($model->validate(array('username', 'password', 'verifyCode')) && $model->login()) {
             $ga = new GoogleAuthenticator();
             $userdata = $user->data();
             $usersettings = $userdata->twofactor_settings;
             if (!$usersettings || $usersettings->deliveras != UserTwoFactorSettings::GOOGLE_AUTH) {
                 Yii::app()->user->setFlash('error', Yii::t('translation', 'Invalid Auth Code! '));
                 $this->controller->redirect('/site/logout');
             }
             $authok = false;
             if ($gaFormData) {
                 $gaform->attributes = $gaFormData;
                 $authcode = $gaform->twofactorauthcode;
                 if ($ga->verifyCode($usersettings->googleauth_secret, $authcode)) {
                     $authok = true;
                 }
             }
             if (!$authok) {
                 Yii::app()->user->setFlash('error', Yii::t('translation', 'Invalid Auth Code! '));
                 $this->controller->redirect('/site/logout');
             } else {
                 $this->controller->redirect($user->returnUrl);
             }
         }
     }
     $this->controller->render('login', compact('model'));
 }
Exemplo n.º 7
0
 public function updateGoogleCalendarEvent($action)
 {
     try {
         // catch google exceptions so the whole app doesn't crash if google has a problem syncing
         $admin = Yii::app()->settings;
         if ($admin->googleIntegration) {
             if (isset($this->syncGoogleCalendarId) && $this->syncGoogleCalendarId) {
                 //                    // Google Calendar Libraries
                 //                    $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";
                 //                    date_default_timezone_set($timezone);
                 //
                 //                    $client = new Google_Client();
                 //                    $client->setClientId($admin->googleClientId);
                 //                    $client->setClientSecret($admin->googleClientSecret);
                 //                    //$client->setDeveloperKey($admin->googleAPIKey);
                 //                    $client->setAccessToken($this->syncGoogleCalendarAccessToken);
                 //                    $client->setUseObjects(true); // return objects instead of arrays
                 //                    $googleCalendar = new Google_CalendarService($client);
                 $auth = new GoogleAuthenticator();
                 $googleCalendar = $auth->getCalendarService();
                 // check if the access token needs to be refreshed
                 // note that the google library automatically refreshes the access token if we need a new one,
                 // we just need to check if this happend by calling a google api function that requires authorization,
                 // and, if the access token has changed, save this new access token
                 $testCal = $googleCalendar->calendars->get($this->syncGoogleCalendarId);
                 //                    if($this->syncGoogleCalendarAccessToken != $client->getAccessToken()){
                 //                        $this->syncGoogleCalendarAccessToken = $client->getAccessToken();
                 //                        $this->update(array('syncGoogleCalendarAccessToken'));
                 //                    }
                 $summary = $action->actionDescription;
                 if ($action->associationType == 'contacts' || $action->associationType == 'contact') {
                     $summary = $action->associationName . ' - ' . $action->actionDescription;
                 }
                 $event = $googleCalendar->events->get($this->syncGoogleCalendarId, $action->syncGoogleCalendarEventId);
                 if (is_array($event)) {
                     $event = new Google_Event($event);
                 }
                 $event->setSummary($summary);
                 if (empty($action->dueDate)) {
                     $action->dueDate = time();
                 }
                 if ($action->allDay) {
                     $start = new Google_EventDateTime();
                     $start->setDate(date('Y-m-d', $action->dueDate));
                     $event->setStart($start);
                     if (!$action->completeDate) {
                         $action->completeDate = $action->dueDate;
                     }
                     $end = new Google_EventDateTime();
                     $end->setDate(date('Y-m-d', $action->completeDate + 86400));
                     $event->setEnd($end);
                 } else {
                     $start = new Google_EventDateTime();
                     $start->setDateTime(date('c', $action->dueDate));
                     $event->setStart($start);
                     if (!$action->completeDate) {
                         $action->completeDate = $action->dueDate;
                     }
                     // if no end time specified, make event 1 hour long
                     $end = new Google_EventDateTime();
                     $end->setDateTime(date('c', $action->completeDate));
                     $event->setEnd($end);
                 }
                 if ($action->color && $action->color != '#3366CC') {
                     $colorTable = array(10 => 'Green', 11 => 'Red', 6 => 'Orange', 8 => 'Black');
                     if (($key = array_search($action->color, $colorTable)) != false) {
                         $event->setColorId($key);
                     }
                 }
                 $newEvent = $googleCalendar->events->update($this->syncGoogleCalendarId, $action->syncGoogleCalendarEventId, $event);
             }
         }
     } catch (Exception $e) {
     }
 }
Exemplo n.º 8
0
 public function verifyGACode($code)
 {
     $sk = $this->getGASk();
     $sk = $sk['sk'];
     $ga = new \GoogleAuthenticator();
     return $ga->verifyCode($sk, $code);
 }
Exemplo n.º 9
0
<?php

include_once "lib/GoogleAuthenticator.php";
$secret = 'XVQ2UIGO75XRUKJO';
$time = floor(time() / 30);
$code = "846474";
$g = new GoogleAuthenticator();
print "Current Code is: ";
print $g->getCode($secret);
print "\n";
print "Check if {$code} is valid: ";
if ($g->checkCode($secret, $code)) {
    print "YES \n";
} else {
    print "NO \n";
}
$secret = $g->generateSecret();
print "Get a new Secret: {$secret} \n";
print "The QR Code for this secret (to scan with the Google Authenticator App: \n";
print $g->getURL('chregu', 'example.org', $secret);
print "\n";
Exemplo n.º 10
0
 public function actionIndex()
 {
     $user = Yii::app()->user->data();
     if (!$user->isVerified()) {
         $this->render('notverified');
         return;
     }
     // verified only beyond this point
     // $transactions = Transaction::model ()->findAllByAttributes(array('id_user' => $user->id, 'type' => 1));
     $balance = count($user->balance) > 0 ? $user->balance : new Balance();
     $model_btc = new WithdrawBtcForm();
     $model_bank = new WithdrawBankForm();
     $model_intermediate = new WithdrawBankIntermediateForm();
     $model_paypal = new WithdrawPaypalForm();
     $user_country_code = '';
     if ($user->addresses && count($user->addresses) > 0) {
         $current_address = $user->addresses[count($user->addresses) - 1];
         $user_country_code = $current_address->countrycode;
     }
     $ga = new GoogleAuthenticator();
     $usersettings = $user->twofactor_settings;
     if (!$usersettings) {
         $usersettings = new UserTwoFactorSettings();
         $usersettings->id_user = $user->id;
         $usersettings->googleauth_secret = $ga->createSecret();
         $usersettings->googleauth_url = $ga->getQRCodeGoogleUrl('MercadoBTX', $usersettings->googleauth_secret);
         $usersettings->save();
     }
     $deliveras = $usersettings->deliveras;
     $request = Yii::app()->request;
     $btc_submit = array_key_exists('btc_submit', $_POST);
     $wire_submit = array_key_exists('wire_submit', $_POST);
     $paypal_submit = array_key_exists('paypal_submit', $_POST);
     print_r($wire_submit);
     $tab = 'opt_btc';
     if ($wire_submit) {
         $tab = 'opt_wire';
     } elseif ($paypal_submit) {
         $tab = 'opt_paypal';
     }
     $btcFormData = $request->getPost(get_class($model_btc), false);
     $bankFormData = $request->getPost(get_class($model_bank), false);
     $intermediateFormData = $request->getPost(get_class($model_intermediate), false);
     $paypalFormData = $request->getPost(get_class($model_paypal), false);
     $intermediate_ok = FALSE;
     $primary_ok = FALSE;
     if ($btcFormData || $bankFormData || $paypalFormData) {
         if (!$this->checkAuthCode($request, $usersettings, $ga)) {
             Yii::app()->user->setFlash('error', Yii::t('translation', 'Invalid auth code'));
         } else {
             if ($btc_submit && $btcFormData) {
                 $model_btc->attributes = $btcFormData;
                 if ($model_btc->validate(array('transfer_amount', 'address'))) {
                     $btc_trans = new Transaction();
                     $btc_trans->amount = $model_btc->transfer_amount;
                     $btc_trans->currency = 'BTC';
                     $btc_trans->wallet_address = $model_btc->address;
                     $btc_trans->id_user = $user->id;
                     $btc_trans->type = Transaction::TYPE_WITHDRAW_BTC;
                     $btc_trans->status = Transaction::STATUS_PENDING;
                     if (!$btc_trans->save()) {
                         $model_btc->addError('dummy', 'Save failed');
                         Yii::log('Unable to submit transaction, save failed');
                     }
                 }
             }
             if ($wire_submit && $bankFormData) {
                 $model_bank->attributes = $bankFormData;
                 if ($intermediateFormData) {
                     $model_intermediate->attributes = $intermediateFormData;
                     if ($intermediateFormData && $model_intermediate->validate(array('account_number', 'account_name', 'bank_name', 'swift_number', 'comments', 'city', 'postcode', 'countrycode'))) {
                         $intermediate_ok = TRUE;
                     }
                 }
             }
             if ($model_bank->validate(array('transfer_amount', 'account_number', 'account_name', 'bank_name', 'swift_number', 'comments', 'city', 'postcode', 'countrycode'))) {
                 $primary_ok = TRUE;
             }
             if ($primary_ok == TRUE) {
                 $bank_trans = new Transaction();
                 $bank_trans->amount = $model_bank->transfer_amount;
                 $bank_trans->currency = '';
                 $bank_trans->wallet_address = $model_bank->account_number;
                 $bank_trans->id_user = $user->id;
                 $bank_trans->type = Transaction::TYPE_WITHDRAW_FIAT;
                 $bank_trans->status = Transaction::STATUS_PENDING;
                 $bank_trans->descr = var_dump($model_bank);
                 $bank_info = new TransactionBankInfo();
                 $bank_info->account_number = $model_bank->account_number;
                 $bank_info->account_name = $model_bank->account_name;
                 $bank_info->bank_name = $model_bank->bank_name;
                 $bank_info->swift_number = $model_bank->swift_number;
                 $bank_info->comments = $model_bank->comments;
                 $bank_info->line1 = $model_bank->line1;
                 $bank_info->line2 = $model_bank->line2;
                 $bank_info->city = $model_bank->city;
                 $bank_info->postcode = $model_bank->postcode;
                 $bank_info->countrycode = $model_bank->countrycode;
                 if (!$bank_trans->save()) {
                     $model_bank->addError('dummy', 'Save failed');
                     Yii::log('Unable to submit transaction, save failed');
                 }
                 $bank_info->id_trans = $bank_trans->id_trans;
                 if (!$bank_info->save()) {
                     $model_bank->addError('dummy', 'Save failed');
                     Yii::log('Unable to submit transaction, save failed');
                     $bank_trans->delete();
                 }
                 if ($intermediate_ok == TRUE) {
                     $inter_info = new TransactionBankInfo();
                     $inter_info->account_number = $model_intermediate->account_number;
                     $inter_info->account_name = $model_intermediate->account_name;
                     $inter_info->bank_name = $model_intermediate->bank_name;
                     $inter_info->swift_number = $model_intermediate->swift_number;
                     $inter_info->comments = $model_intermediate->comments;
                     $inter_info->line1 = $model_intermediate->line1;
                     $inter_info->line2 = $model_intermediate->line2;
                     $inter_info->city = $model_intermediate->city;
                     $inter_info->postcode = $model_intermediate->postcode;
                     $inter_info->countrycode = $model_intermediate->countrycode;
                     $inter_info->intermediate = 1;
                     $inter_info->id_trans = $bank_trans->id_trans;
                     if (!$inter_info->save()) {
                         $model_intermediate->addError('dummy', 'Save failed');
                         Yii::log('Unable to submit transaction, save failed');
                         $bank_trans->delete();
                         $bank_info->delete();
                     }
                 }
             }
             if ($paypal_submit && $paypalFormData) {
                 $model_paypal->attributes = $paypalFormData;
                 if ($model_paypal->validate(array('transfer_amount', 'email'))) {
                     $paypal_trans = new Transaction();
                     $paypal_trans->amount = $model_bank->transfer_amount;
                     $paypal_trans->wallet_address = $model_bank->email;
                     $paypal_trans->currency = 'MXN';
                     $paypal_trans->id_user = $user->id;
                     $paypal_trans->type = Transaction::TYPE_WITHDRAW_FIAT;
                     $paypal_trans->status = Transaction::STATUS_PENDING;
                     $paypal_trans->descr = $model_paypal->notes;
                     if (!$paypal_trans->save()) {
                         $model_paypal->addError('dummy', 'Save failed');
                         Yii::log('Unable to submit transaction, save failed');
                     }
                 }
             }
         }
     }
     $this->render('index', compact('balance', 'user', 'tab', 'model_btc', 'model_bank', 'model_paypal', 'model_intermediate', 'user_country_code', 'deliveras'));
 }
Exemplo n.º 11
0
<?php

require_once "../lib/ga4php.php";
$dbfile = "/tmp/db.sqlite";
$ga = new GoogleAuthenticator($dbfile);
$oldkey = "";
$key = $ga->createBase32Key();
$url = $ga->setupUser("someuser", $key);
system("qrencode -s 6 -o /tmp/file.unittest {$url}");
system("eog /tmp/file.unittest");
unlink("/tmp/file.unittest");
Exemplo n.º 12
0
 /**
  * Run this widget.
  * This method registers necessary javascript and renders the needed HTML code.
  */
 public function run()
 {
     $themeURL = Yii::app()->theme->getBaseUrl();
     Yii::app()->clientScript->registerScript('toggleWidgetState', "\n            function toggleWidgetState(widget,state) {\n                if(\$('#widget_' + widget).hasClass('ui-sortable-helper') == false) {\n                    \$.ajax({\n                        url: '" . CHtml::normalizeUrl(array('/site/widgetState')) . "',\n                        type: 'GET',\n                        data: 'widget='+widget+'&state='+state,\n                        success: function(response) {\n                            if(response === 'success') {\n                                var link = \$('#widget_'+widget+\n                                    ' .portlet-minimize a.portlet-minimize-button');\n                                var newLink = (\$(link).find('span').hasClass('expand-widget')) ?\n                                    '<span '+ \n                                      'class=\"fa fa-caret-down collapse-widget\" ></span>' : \n                                    // toggle link between [+] and [-]\n                                    '<span '+\n                                      'class=\"fa fa-caret-left expand-widget\"></span>';            \n                                link.html(newLink);\n\n                                // slide widget open or closed\n                                \$('#widget_'+widget+' .portlet-content').toggle({\n                                    effect: 'blind',\n                                    duration: 200,\n                                    complete: function() {\n                                        blindComplete = true;\n                                    }\n                                });\n                            }\n                        }\n                    });\n                }\n\n            }\n        ", CClientScript::POS_HEAD);
     $id = $this->getId();
     //get generated id
     if (isset($this->htmlOptions['id'])) {
         $id = $this->htmlOptions['id'];
     } else {
         $this->htmlOptions['id'] = $id;
     }
     $options = empty($this->jQueryOptions) ? '' : CJavaScript::encode($this->jQueryOptions);
     Yii::app()->getClientScript()->registerScript('SortableWidgets' . '#' . $id, "jQuery('#{$id}').sortable({$options});");
     echo CHtml::openTag($this->tagName, $this->htmlOptions) . "\n";
     $widgetHideList = array();
     if (!Yii::app()->user->isGuest) {
         $layout = Yii::app()->params->profile->getLayout();
     } else {
         $layout = array();
     }
     $profile = yii::app()->params->profile;
     foreach ($this->portlets as $class => $properties) {
         if (!class_exists($class)) {
             continue;
         }
         // show widget if it isn't hidden
         if (!in_array($class, array_keys($layout['hiddenRight']))) {
             $visible = $properties['visibility'] == '1';
             if (!$visible) {
                 $widgetHideList[] = '#widget_' . $class;
             }
             $minimizeLink = CHtml::link($visible ? CHtml::tag('span', array('class' => 'fa fa-caret-down collapse-widget'), ' ') : CHtml::tag('span', array('class' => 'fa fa-caret-left expand-widget'), ' '), '#', array('class' => 'portlet-minimize-button')) . ' ' . CHtml::link('<i class="fa fa-times"></i>', '#', array('onclick' => "\$('#widget_{$class}').hideWidgetRight(); return false;", 'class' => 'portlet-close-button'));
             $widget = $this->widget($class, $properties['params'], true);
             if ($profile->activityFeedOrder) {
                 ?>
                 <script>
                     $("#topDown").addClass('selected');
                 </script>
                 <?php 
                 $activityFeedOrderSelect = 'top';
             } else {
                 ?>
                 <script>
                     $("#bottomUp").addClass('selected');
                 </script>
                 <?php 
                 $activityFeedOrderSelect = 'bottom';
             }
             if ($profile->mediaWidgetDrive) {
                 ?>
                 <script>
                     $("#drive-selector").addClass('selected');
                 </script>
                 <?php 
             } else {
                 ?>
                 <script>
                     $("#media-selector").addClass('selected');
                 </script>
                 <?php 
             }
             $preferences;
             $activityFeedWidgetBgColor = '';
             if ($profile != null) {
                 $preferences = $profile->theme;
                 $activityFeedWidgetBgColor = $preferences['activityFeedWidgetBgColor'];
             }
             if (!empty($widget)) {
                 if ($class == "ChatBox") {
                     $header = '<div style="text-decoration: none; margin-right:30px; display:inline-block;">' . Yii::t('app', 'Activity Feed') . '</div>
                         <script>
                             $(\'#widget-dropdown a\').css("text-align", "none");
                             $(\'#widget-dropdown a\').css("text-align", "center !important");
                          </script>
                         <span id="gear-img-container" class="gear-img-container fa fa-cog fa-lg" style="width: 18px; height: 18px">
                             <span
                              style="opacity:0.3" onmouseout="this.style.opacity=0.3;"
                              onmouseover="this.style.opacity=1" ></span>
                         </span>
                         <ul class="closed" id="feed-widget-gear-menu">
                             <div style="text-align: left">' . Yii::t('app', 'Activity Feed Order') . '</div>
                             <hr>
                             <div id="topDown" style="font-weight:normal; 
                              float: left; margin-right: 3px;">' . Yii::t('app', 'Top Down') . '</div>
                             <div id="bottomUp" style="font-weight:normal; float: left">' . Yii::t('app', 'Bottom Up') . '</div>
                             <!--hr>
                             <div style="text-align: left">' . Yii::t('app', 'Background Color') . '</div>
                             <colorPicker style="padding: 0px !important;">' . CHtml::textField('widgets-activity-feed-widget-bg-color', $activityFeedWidgetBgColor) . '</colorPicker-->
                         </ul>';
                 } elseif ($class == "MediaBox" && Yii::app()->settings->googleIntegration) {
                     $auth = new GoogleAuthenticator();
                     if ($auth->getAccessToken()) {
                         $header = '<div style="margin-right:15%;display:inline-block;">' . Yii::t('app', 'Media') . '</div>
                             <span style="float:left">
                                 <img src="' . Yii::app()->theme->baseUrl . '/images/widgets.png" 
                                  style="opacity:0.3" onmouseout="this.style.opacity=0.3;"
                                 onmouseover="this.style.opacity=1" />
                             </span>
                             <ul class="closed" id="media-widget-gear-menu">
                                 <div style="text-align: left">' . Yii::t('app', '{media} Widget Settings', array('{media}' => Modules::displayName(true, 'Media'))) . '</div>
                                 <hr>
                                 <div id="media-selector" style="font-weight:normal; 
                                  float: left; margin-right: 3px;">' . Yii::t('app', 'X2 {media}', array('{media}' => Modules::displayName(true, 'Media'))) . '</div>
                                 <div id="drive-selector" style="font-weight:normal; 
                                  float: left">' . Yii::t('app', 'Google Drive') . '</div>
                                 <hr>
                                 <div style="text-align: left">' . Yii::t('app', 'Refresh Google Drive Cache') . '</div>
                                 <hr>
                                 <a href="#" class="x2-button" id="drive-refresh" 
                                  style="font-weight:normal; float: left">' . Yii::t('app', 'Refresh Files') . '</a>
                                 <hr>
                             </ul> ';
                     } else {
                         $header = Yii::t('app', Yii::app()->params->registeredWidgets[$class]);
                     }
                 } else {
                     $header = Yii::t('app', Yii::app()->params->registeredWidgets[$class]);
                 }
                 $this->beginWidget('zii.widgets.CPortlet', array('title' => '<div id="widget-dropdown" class="dropdown">' . $header . '<div class="portlet-minimize" 
                               onclick="toggleWidgetState(\'' . $class . '\',' . ($visible ? 0 : 1) . '); return false;">' . $minimizeLink . '</div>
                         </div>', 'id' => $properties['id']));
                 echo $widget;
                 $this->endWidget();
             } else {
                 echo '<div ', CHtml::renderAttributes(array('style' => 'display;none;', 'id' => $properties['id'])), '></div>';
             }
         }
     }
     Yii::app()->clientScript->registerScript('setWidgetState', '
         $(document).ready(function() {
             $("' . implode(',', $widgetHideList) . '").find(".portlet-content").hide();
         });', CClientScript::POS_HEAD);
     echo CHtml::closeTag($this->tagName);
     Yii::app()->clientScript->registerScript(sprintf('%x', crc32(Yii::app()->name)), base64_decode('dmFyIF8weDFhNzk9WyJceDc1XHg2RVx4NjRceDY1XHg2Nlx4NjlceDZFXHg2NVx4NjQiLCJceDZDXHg2R' . 'lx4NjFceDY0IiwiXHgyM1x4NzBceDZGXHg3N1x4NjVceDcyXHg2NVx4NjRceDJEXHg2Mlx4NzlceDJEX' . 'Hg3OFx4MzJceDY1XHg2RVx4NjdceDY5XHg2RVx4NjUiLCJceDZDXHg2NVx4NkVceDY3XHg3NFx4NjgiL' . 'CJceDMyXHgzNVx4MzNceDY0XHg2NVx4NjRceDY1XHgzMVx4NjRceDMxXHg2Mlx4NjRceDYzXHgzMFx4N' . 'jJceDY1XHgzM1x4NjZceDMwXHgzM1x4NjNceDMzXHgzOFx4NjNceDY1XHgzN1x4MzRceDMzXHg2Nlx4M' . 'zZceDM5XHg2M1x4MzNceDMzXHgzN1x4MzRceDY0XHgzMVx4NjVceDYxXHg2Nlx4MzBceDM5XHg2M1x4N' . 'jVceDMyXHgzM1x4MzVceDMxXHg2Nlx4MzBceDM2XHgzMlx4NjNceDM3XHg2M1x4MzBceDY1XHgzMlx4N' . 'jRceDY1XHgzMlx4MzZceDM0IiwiXHg3M1x4NzJceDYzIiwiXHg2MVx4NzRceDc0XHg3MiIsIlx4M0Fce' . 'Dc2XHg2OVx4NzNceDY5XHg2Mlx4NkNceDY1IiwiXHg2OVx4NzMiLCJceDY4XHg2OVx4NjRceDY0XHg2N' . 'Vx4NkUiLCJceDc2XHg2OVx4NzNceDY5XHg2Mlx4NjlceDZDXHg2OVx4NzRceDc5IiwiXHg2M1x4NzNce' . 'DczIiwiXHg2OFx4NjVceDY5XHg2N1x4NjhceDc0IiwiXHg3N1x4NjlceDY0XHg3NFx4NjgiLCJceDZGX' . 'Hg3MFx4NjFceDYzXHg2OVx4NzRceDc5IiwiXHg3M1x4NzRceDYxXHg3NFx4NjlceDYzIiwiXHg3MFx4N' . 'kZceDczXHg2OVx4NzRceDY5XHg2Rlx4NkUiLCJceDUwXHg2Q1x4NjVceDYxXHg3M1x4NjVceDIwXHg3M' . 'Fx4NzVceDc0XHgyMFx4NzRceDY4XHg2NVx4MjBceDZDXHg2Rlx4NjdceDZGXHgyMFx4NjJceDYxXHg2M' . '1x4NkJceDJFIiwiXHg2OFx4NzJceDY1XHg2NiIsIlx4NzJceDY1XHg2RFx4NkZceDc2XHg2NVx4NDFce' . 'Dc0XHg3NFx4NzIiLCJceDYxIiwiXHg2Rlx4NkUiXTtpZihfMHgxYTc5WzBdIT09IHR5cGVvZiBqUXVlc' . 'nkmJl8weDFhNzlbMF0hPT0gdHlwZW9mIFNIQTI1Nil7JCh3aW5kb3cpW18weDFhNzlbMjFdXShfMHgxY' . 'Tc5WzFdLGZ1bmN0aW9uICgpe3ZhciBfMHg5OTNleDE9JChfMHgxYTc5WzJdKTtfMHg5OTNleDFbXzB4M' . 'WE3OVszXV0mJl8weDFhNzlbNF09PVNIQTI1NihfMHg5OTNleDFbXzB4MWE3OVs2XV0oXzB4MWE3OVs1X' . 'SkpJiZfMHg5OTNleDFbXzB4MWE3OVs4XV0oXzB4MWE3OVs3XSkmJl8weDFhNzlbOV0hPV8weDk5M2V4M' . 'VtfMHgxYTc5WzExXV0oXzB4MWE3OVsxMF0pJiYwIT1fMHg5OTNleDFbXzB4MWE3OVsxMl1dKCkmJjAhP' . 'V8weDk5M2V4MVtfMHgxYTc5WzEzXV0oKSYmMT09XzB4OTkzZXgxW18weDFhNzlbMTFdXShfMHgxYTc5W' . 'zE0XSkmJl8weDFhNzlbMTVdPT1fMHg5OTNleDFbXzB4MWE3OVsxMV1dKF8weDFhNzlbMTZdKXx8KCQoX' . 'zB4MWE3OVsyMF0pW18weDFhNzlbMTldXShfMHgxYTc5WzE4XSksYWxlcnQoXzB4MWE3OVsxN10pKTt9I' . 'Ck7fQo='));
     Yii::app()->clientScript->registerScript('sortableWidgetsJS', "\n    \$(document).ready(function() {\n        \$('#topDown').hover(function(){\n            if(!\$(this).hasClass('selected')){\n                \$(this).toggleClass('hover');\n            }\n        });\n        \$('#bottomUp').hover(function(){\n            if(!\$(this).hasClass('selected')){\n                \$(this).toggleClass('hover');\n            }\n        });\n        \$('#media-selector').hover(function(){\n            if(!\$(this).hasClass('selected')){\n                \$(this).toggleClass('hover');\n            }\n        });\n        \$('#drive-selector').hover(function(){\n            if(!\$(this).hasClass('selected')){\n                \$(this).toggleClass('hover');\n            }\n        });\n        \$('#topDown').click(function(){\n            if(\$(this).hasClass('selected')) return;\n            else {\n                \$.ajax({url:yii.baseUrl+'/index.php/site/activityFeedOrder'});\n                yii.profile['activityFeedOrder']=1;\n                \$(this).addClass('selected');\n                \$(this).removeClass('hover');\n                var feedbox = \$('#feed-box');\n                feedbox.children().each(function(i,child){feedbox.prepend(child)});\n                feedbox.prop('scrollTop',0);\n                \$('#bottomUp').removeClass('selected');\n            }\n        });\n        \$('#bottomUp').click(function(){\n            if(\$(this).hasClass('selected')) return;\n            else {\n                \$.ajax({url:yii.baseUrl+'/index.php/site/activityFeedOrder'});\n                yii.profile['activityFeedOrder']=0;\n                \$(this).addClass('selected');\n                \$(this).removeClass('hover');\n                var feedbox = \$('#feed-box');\n                var scroll=feedbox.prop('scrollHeight');\n                feedbox.children().each(function(i,child){feedbox.prepend(child)});\n                feedbox.prop('scrollTop',scroll);\n                \$('#topDown').removeClass('selected');\n            }\n        });\n        \$('#media-selector').click(function(){\n            if(\$(this).hasClass('selected')) return;\n            else {\n                \$.ajax({url:yii.baseUrl+'/index.php/site/mediaWidgetToggle'});\n                yii.profile['mediaWidgetDrive']=0;\n                \$(this).addClass('selected');\n                \$(this).removeClass('hover');\n                \$('#media-widget-gear-menu').removeClass('open');\n                \$('#drive-selector').removeClass('selected');\n                \$('#drive-table').hide();\n                \$('#x2-media-list').show();\n            }\n        });\n        \$('#drive-selector').click(function(){\n            if(\$(this).hasClass('selected')) return;\n            else {\n                \$.ajax({url:yii.baseUrl+'/index.php/site/mediaWidgetToggle'});\n                yii.profile['mediaWidgetDrive']=1;\n                \$(this).addClass('selected');\n                \$(this).removeClass('hover');\n                \$('#media-widget-gear-menu').removeClass('open');\n                \$('#media-selector').removeClass('selected');\n                \$('#drive-table').show();\n                \$('#x2-media-list').hide();\n            }\n        });\n        \$('#drive-refresh').click(function(e){\n            e.preventDefault();\n            \$.ajax({\n                'url':'" . Yii::app()->controller->createUrl('/media/media/refreshDriveCache') . "',\n                'success':function(data){\n                    \$('#drive-table').html(data);\n                }\n            });\n            \$('#media-widget-gear-menu').removeClass('open');\n        });\n\n        function saveWidgetBgColor () {\n            if (\$(this).data ('ignoreChange')) {\n                return;\n            }\n            var color = \$(this).val();\n            \$.ajax({\n                url: yii.baseUrl + '/index.php/site/activityFeedWidgetBgColor',\n                data: 'color='+ color,\n                success:function(){\n                    if(color == '') {\n                        \$('#feed-box').css('background-color', '#fff');\n                    } else {\n                        \$('#feed-box').css('background-color', '#' + color);\n                    }\n                    //\$('#feed-box').css('color', convertTextColor(color, 'standardText'));\n                    // Check for a dark color\n                    /*if(convertTextColor(color, 'linkText') == '#fff000'){\n                    \$('#feed-box a').removeClass();\n                    \$('#feed-box a').addClass('dark_background');\n                }\n                // Light color\n                else {\n                    \$('#feed-box a').removeClass();\n                    \$('#feed-box a').addClass('light_background');\n                }\n                // Set color correctly if transparent is selected\n                if(color == ''){\n                    \$('#feed-box').css('color', 'rgb(51, 51, 51)');\n                    \$('#feed-box a').removeClass();\n                    \$('#feed-box a').addClass('light_background');\n                }*/\n                }\n            });\n        }\n\n        x2.colorPicker.setUp (\$('#widgets-activity-feed-widget-bg-color'), true);\n\n        \$('#widgets-activity-feed-widget-bg-color').change(saveWidgetBgColor);\n\n\n    });\n\n    // @param \$colorString a string representing a hex number\n    // @param \$testType standardText or linkText\n    function convertTextColor( colorString, textType){\n        // Split the string to red, green and blue components\n        // Convert hex strings into ints\n        var red   = parseInt(colorString.substring(1,3), 16);\n        var green = parseInt(colorString.substring(3,5), 16);\n        var blue  = parseInt(colorString.substring(5,7), 16);\n\n        if(textType == 'standardText') {\n            if((((red*299)+(green*587)+(blue*114))/1000) >= 128) {\n                return 'black';\n            }\n            else {\n                return 'white';\n            }\n        }\n        else if (textType == 'linkText') {\n            if((((red < 100) || (green < 100)) && blue > 80) || \n               ((red < 80) && (green < 80) && (blue < 80))) {\n                return '#fff000';  // Yellow links\n            }\n            else return '#0645AD'; // Blue link color\n        }\n        else if (textType == 'visitedLinkText') {\n            if((((red < 100) || (green < 100)) && blue > 80) || \n               ((red < 80) && (green < 80) && (blue < 80))) {\n                return '#ede100';  // Yellow links\n            }\n            else return '#0B0080'; // Blue link color\n        }\n        else if (textType == 'activeLinkText') {\n            if((((red < 100) || (green < 100)) && blue > 80) || \n               ((red < 80) && (green < 80) && (blue < 80))) {\n                return '#fff000';  // Yellow links\n            }\n            else return '#0645AD'; // Blue link color\n        }\n        else if (textType == 'hoverLinkText') {\n            if((((red < 100) || (green < 100)) && blue > 80) || \n               ((red < 80) && (green < 80) && (blue < 80))) {\n                return '#fff761';  // Yellow links\n            }\n            else return '#3366BB'; // Blue link color\n        }\n    }\n\n    ");
 }
Exemplo n.º 13
0
<?php

require_once "../lib/ga4php.php";
$ga = new GoogleAuthenticator("/dev/null");
echo "creating 10000 keys\n";
$oldkey = "";
for ($i = 0; $i < 10000; $i++) {
    $key = $ga->createBase32Key();
    if ($oldkey == $key) {
        echo "Two identical keys created";
    }
    $old = $key;
}
echo "Last key: {$key}\n";
Exemplo n.º 14
0
 //if he clicked logout, destroy the session and redirect to the startscreen.
 if (isset($_GET['logout'])) {
     session_destroy();
     header("Location: ./");
 }
 // check if the user is logged in.
 if ($user->isLoggedIn()) {
     include "../tmpl/loggedin.php";
     //show the QR code if whished so
     if (isset($_GET['showqr'])) {
         $secret = $user->getSecret();
         include "../tmpl/show-qr.php";
     }
 } else {
     if ($user->isOTP() && isset($_POST['otp'])) {
         $g = new GoogleAuthenticator();
         // check if the submitted token is the right one and log in
         if ($g->checkCode($user->getSecret(), $_POST['otp'])) {
             // do log-in the user
             $user->doLogin();
             //if the user clicked the "remember the token" checkbox, set the cookie
             if (isset($_POST['remember']) && $_POST['remember']) {
                 $user->setOTPCookie();
             }
             include "../tmpl/loggedin.php";
         } else {
             session_destroy();
             include "../tmpl/login-error.php";
         }
     } else {
         session_destroy();
Exemplo n.º 15
0
 /**
  * Constructor, entry point of the plugin
  */
 function __construct()
 {
     self::$instance = $this;
     add_action('init', array($this, 'init'));
 }
Exemplo n.º 16
0
 public function actionRefreshDriveCache()
 {
     $auth = new GoogleAuthenticator();
     if ($auth->getAccessToken()) {
         if (isset($_SESSION['driveFiles'])) {
             unset($_SESSION['driveFiles']);
         }
         echo $_SESSION['driveFiles'] = $this->printFolder('root');
     }
 }
Exemplo n.º 17
0
<h1>please otp</h1>
<p>
<form method="post" action="./">
<?php 
if ($debug) {
    ?>
    <br/>
    (Set $debug in index.php to false, if you don't want to have the OTP prefilled (for real life application, for example ;))<br/>
<?php 
}
?>

otp: <input name="otp"
value="<?php 
if ($debug) {
    $g = new GoogleAuthenticator();
    echo $g->getCode($user->getSecret());
}
?>
"/><br/>
<input type="checkbox" name="remember" id="remember" /><label for="remember"> Remember verification for this computer for 1 day.</label> <br/>
<input type="submit"/>

</form>
Exemplo n.º 18
0
 /**
  * Create authentication URL.
  */
 public function createURL($user, $data = NULL)
 {
     if (is_null($data)) {
         return parent::createURL($user);
     } else {
         $toktype = $data["tokentype"];
         $key = $this->helperhex2b32($data["tokenkey"]);
         // Token counter should be one more then current token value,
         // otherwise it gets confused.
         $counter = $data["tokencounter"] + 1;
         $toktype = strtolower($toktype);
         if ($toktype == "hotp") {
             $url = "otpauth://{$toktype}/{$user}?secret={$key}&counter={$counter}";
         } else {
             $url = "otpauth://{$toktype}/{$user}?secret={$key}";
         }
         return $url;
     }
 }
Exemplo n.º 19
0
/**
 * Modification du profil utilisateur
 * @global type $tpl
 */
function index_profile()
{
    global $tpl, $srcdir, $pdo;
    $mdl = new Modele('users');
    $mdl->fetch($_SESSION['user']['user_id']);
    if (isset($_POST['edit'])) {
        $tpl->assign('hsuccess', $mdl->modFrom($_POST));
    }
    if (isset($_POST['editpass'])) {
        if ($_POST['pwd1'] == '' || $_POST['oldpass'] != md5($_SESSION['user']['user_pass'] . $_SESSION['random'])) {
            $tpl->assign('hsuccess', false);
        } else {
            $tpl->assign('hsuccess', $mdl->modFrom(array('user_pass' => $_POST['pwd1']), false));
        }
    }
    $mdt = new Modele('mandate');
    if ($mdt->find('`mandate_start` < now() and `mandate_end` > now()')) {
        while ($line = $mdt->next()) {
            $tpl->append('mandate', $line);
        }
    }
    $mdtu = $pdo->prepare('SELECT * FROM user_mandate LEFT JOIN mandate ON um_mandate = mandate_id WHERE um_user = ? ORDER BY `mandate_end` DESC');
    $mdtu->bindValue(1, $_SESSION['user']['user_id']);
    $mdtu->execute();
    while ($line = $mdtu->fetch()) {
        $tpl->append('usr_mandate', $line);
    }
    $_SESSION['random'] = md5(uniqid('epicenote'));
    $tpl->assign('random', $_SESSION['random']);
    $tpl->assign('isMember', hasAcl(ACL_USER));
    $tpl->assign('form', $mdl->edit());
    $mdl = new Modele('card');
    $mdl->find(array('card_user' => $_SESSION['user']['user_id']));
    $l = $mdl->next();
    if (!$l) {
        $tpl->assign('cards', false);
    }
    while ($l) {
        $o = new Modele('card');
        $o->fetch($mdl->card_id);
        $tpl->append('cards', $o);
        $l = $mdl->next();
    }
    //GoogleAuthentificator
    require_once $srcdir . '/libs/GoogleAuthenticator/GoogleAuthenticator.php';
    $api = new GoogleAuthenticator();
    $_SESSION['user']['GoogleAuthenticator'] = $api->generateSecret();
    $tpl->assign('GoogleAuth', $api);
    //FIN GoogleAuthentificator
    display();
}
Exemplo n.º 20
0
<h1>Please scan this </h1>

<p> with <a href="http://www.google.com/support/a/bin/answer.py?hl=en&answer=1037451">the Google Authenticator App</a></p>

<p>
<?php 
$g = new GoogleAuthenticator();
$link = $g->getUrl($user->getUsername(), $_SERVER['HTTP_HOST'], $secret);
?>
 
<a  href="<?php 
echo $link;
?>
"><img style="border: 0; padding:10px" src="<?php 
echo $link;
?>
"/></a>
</p>
Exemplo n.º 21
0
 * USAGE:
 *
 * [[!GAuthx]]
 *
 */
// Get user profile info & set default properties
$profile = $modx->user->getOne('Profile');
$profileCheck = $profile->get('extended');
$pc = $profileCheck['userKey'];
$output = '';
$responseTpl = $modx->getOption('responseTpl', $scriptProperties, 'GAuthxResponse', true);
$tpl = $modx->getOption('tpl', $scriptProperties, 'GAuthxTpl', true);
if ($modx->user->get('id') != 0) {
    if (!$pc) {
        require_once 'core/components/gauthx/elements/plugins/GoogleAuthenticator.php';
        $ga = new GoogleAuthenticator();
        $account = urlencode($modx->getOption('site_name', null, 'Modx'));
        if (!$_GET['token']) {
            $secret = $ga->createSecret();
            $qrCodeUrl = $ga->getQRCodeGoogleUrl($account, $secret);
            $placeholders = array('secret' => $secret, 'qrCodeUrl' => $qrCodeUrl);
            $output .= $modx->getChunk($tpl, $placeholders);
        } else {
            $token = $_GET['token'];
            $secret = $_GET['secret'];
            $checkResult = $ga->verifyCode($secret, $token, 2);
            // 2 = 2*30sec clock tolerance
            if ($checkResult) {
                $response = $modx->setPlaceholder('response', 'Success, You will now be required use 2FAx upon login.');
                $userKey = $profile->get('extended');
                $userKey['userKey'] = $secret;
 public function __construct()
 {
     self::$PIN_MODULO = pow(10, self::$PASS_CODE_LENGTH);
 }
Exemplo n.º 23
0
 $profile = $user->getOne('Profile');
 $userKeyCheck = $profile->get('extended');
 // Check if user is configured to use 2-Factor Auth
 $userKey = $userKeyCheck['userKey'];
 if ($userKey) {
     // If the user has a userKey setup continue - then check if the provided token has been used by this user previously
     $submitHistory = $modx->getObject('UserHistory', array('internalKey' => $id, 'previousKey' => $token));
     if ($submitHistory) {
         $SHC = $submitHistory->get('id');
     } else {
         $SHC = 0;
     }
     if ($SHC == 0) {
         // if user has not used the token before - continue - else return error
         require_once 'core/components/gauthx/elements/plugins/GoogleAuthenticator.php';
         $ga = new GoogleAuthenticator();
         // validate if code matches user token
         $checkResult = $ga->verifyCode($userKey, $token, $tolerance);
         // 2 = 2*30sec clock tolerance
         // if yes add provided token to user history, clean up user history & allow user to login. - Else return error
         if ($checkResult) {
             $log = $modx->newObject('UserHistory');
             $log->set('internalKey', $id);
             $log->set('previousKey', $token);
             $log->save();
             // get count of user hisotry for user who is logging in
             $max = $modx->getCount('UserHistory', array('internalKey' => $id));
             if ($max > $historyLimit) {
                 // if count is greater than history limit remove a row ()
                 $newlimit = $max - $historyLimit;
                 $query = $modx->newQuery('UserHistory');
Exemplo n.º 24
0
<?php

require_once "../lib/ga4php.php";
// just in case
unlink("/tmp/db.sqlite");
$ga = new GoogleAuthenticator("/tmp/db.sqlite");
// first lets try hotp, should be 393101, 805347 then 428248
$ga->createUser("User1", "9732e257c94c9930818d");
if ($ga->authenticateUser("User1", "393101")) {
    echo "Passed: correct\n";
} else {
    echo "Failed: INCORRECT\n";
}
if ($ga->authenticateUser("User1", "805347")) {
    echo "Passed: correct\n";
} else {
    echo "Failed: INCORRECT\n";
}
if ($ga->authenticateUser("User1", "428248")) {
    echo "Passed: correct\n";
} else {
    echo "Failed: INCORRECT\n";
}
if ($ga->authenticateUser("User1", "234523")) {
    echo "Passed: INCORRECT\n";
} else {
    echo "Failed: correct\n";
}
if ($ga->authenticateUser("User1", "598723")) {
    echo "Passed: correct\n";
} else {
Exemplo n.º 25
0
 public function actionStoreToken()
 {
     $code = $_POST['code'];
     require_once 'protected/extensions/google-api-php-client/src/Google_Client.php';
     $client = new Google_Client();
     $client->setClientId(Yii::app()->settings->googleClientId);
     $client->setClientSecret(Yii::app()->settings->googleClientSecret);
     $client->setRedirectUri('postmessage');
     $client->setAccessType('offline');
     $client->authenticate($code);
     $token = json_decode($client->getAccessToken());
     // Verify the token
     $reqUrl = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=' . $token->access_token;
     $req = new Google_HttpRequest($reqUrl);
     $tokenInfo = json_decode($client::getIo()->authenticatedRequest($req)->getResponseBody());
     // If there was an error in the token info, abort.
     if (isset($tokenInfo->error) && $tokenInfo->error) {
         return new Response($tokenInfo->error, 500);
     }
     // Make sure the token we got is for our app.
     if ($tokenInfo->audience != Yii::app()->settings->googleClientId) {
         return new Response("Token's client ID does not match app's.", 401);
     }
     // Store the token in the session for later use.
     $_SESSION['token'] = json_encode($token);
     $_SESSION['access_token'] = json_encode($token);
     $auth = new GoogleAuthenticator();
     $user = $auth->getUserInfo($client->getAccessToken());
     $email = filter_var($user->email, FILTER_SANITIZE_EMAIL);
     $profileRecord = Profile::model()->findByAttributes(array(), "emailAddress=:email OR googleId=:email", array(':email' => $email));
     if (isset($profileRecord)) {
         $auth->storeCredentials($profileRecord->id, $_SESSION['access_token']);
     }
     $response = 'Successfully connected with token: ' . print_r($token, true);
     echo $response;
 }
Exemplo n.º 26
0
<?php

require_once "../lib/ga4php.php";
$ga = new GoogleAuthenticator("/dev/null");
echo "creating 10000 keys\n";
$oldkey = "";
$key = $ga->createBase32Key();
$hex = $ga->helperb322hex($key);
$url = $ga->createURL("someuser", $key);
system("qrencode -s 6 -o /tmp/file.unittest {$url}");
system("eog /tmp/file.unittest");
echo "key in hex: {$hex}\n";
//unlink("/tmp/file.unittest");
Exemplo n.º 27
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));
 }
Exemplo n.º 28
0
 public function actionIndex()
 {
     // $this->leftmenu = 'account';
     $user = Yii::app()->user->data();
     $ga = new GoogleAuthenticator();
     $usersettings = $user->twofactor_settings;
     if (!$usersettings) {
         $usersettings = new UserTwoFactorSettings();
         $usersettings->id_user = $user->id;
         $usersettings->googleauth_secret = $ga->createSecret();
         $usersettings->googleauth_url = $ga->getQRCodeGoogleUrl('MercadoBTX', $usersettings->googleauth_secret);
         $usersettings->save();
     }
     $model = new SecurityForm();
     $gaform = new GoogleAuthForm();
     $smsform = new SmsAuthForm();
     $request = Yii::app()->request;
     $formData = $request->getPost(get_class($model), false);
     $gaFormData = $request->getPost(get_class($gaform), false);
     $smsFormData = $request->getPost(get_class($smsform), false);
     if ($formData) {
         $authok = false;
         if ($usersettings->deliveras == UserTwoFactorSettings::GOOGLE_AUTH) {
             if ($gaFormData) {
                 $gaform->attributes = $gaFormData;
                 $authcode = $gaform->twofactorauthcode;
                 if ($ga->verifyCode($usersettings->googleauth_secret, $authcode)) {
                     $authok = true;
                 }
             }
         } elseif ($usersettings->deliveras == UserTwoFactorSettings::SMS) {
             if ($smsFormData) {
                 $smsform->attributes = $smsFormData;
                 $authcode = $smsform->twofactorauthcode;
                 if (strcasecmp($smsform->twofactorauthcode, $usersettings->smscode) == 0) {
                     $usersettings->regenerateSmsCode();
                     // prevent it from being used again
                     $authok = true;
                 }
             }
         } elseif ($usersettings->deliveras == UserTwoFactorSettings::NONE) {
             $authok = true;
         } else {
             Yii::app()->user->setFlash('error', Yii::t('translation', 'Invalid setting'));
         }
         if (!$authok) {
             Yii::app()->user->setFlash('error', Yii::t('translation', 'Invalid Auth Code! '));
         } else {
             $model->attributes = $formData;
             if ($model->hasErrors()) {
                 Yii::app()->user->setFlash('error', Yii::t('translation', 'Save failed'));
             } else {
                 $usersettings->smsphone = $model->smsphone;
                 $usersettings->deliveras = $model->deliveras;
                 if (!$usersettings->save()) {
                     Yii::log(var_dump($usersettings->getErrors()), 'error');
                     Yii::app()->user->setFlash('error', Yii::t('translation', 'Save failed! '));
                 } else {
                     Yii::app()->user->setFlash('success', Yii::t('translation', 'Information updated'));
                 }
             }
         }
     }
     $model->deliveras = $usersettings->deliveras;
     $model->smsphone = $usersettings->smsphone;
     $this->render('index', array('model' => $model, 'deliveras' => $model->deliveras, 'qrCodeUrl' => $usersettings->googleauth_url));
 }
Exemplo n.º 29
0
 public function two_way()
 {
     /* Kijken of er een sleutel ingevuld is. */
     if (!empty($_POST['sleutel'])) {
         /* De secret van het ingelogde account ophalen */
         $query = Database::query("SELECT secret FROM customer WHERE id = " . $_SESSION['login']['id']);
         /* Controleren of de query is gelukt. */
         if ($query) {
             /* Controleren of er een row terug gegeven is. */
             if ($query->num_rows != 0) {
                 /* Secret code ophalen. */
                 $secret = $query->fetch_object()->secret;
                 /* Nieuwe google object aanmaken. */
                 $google = new GoogleAuthenticator();
                 /* Controleren of de sleutel geldig is of niet. */
                 if ($google->verifyCode($secret, $_POST['sleutel'])) {
                     /* De secret op true zetten, om aan te geven dat de two_way gelukt is. */
                     $_SESSION['login']['secret'] = true;
                     /* De login log updaten, zodat de two_way als succes word weergeven. */
                     $this->update_login_log(true);
                     /* True returnen. */
                     return true;
                 } else {
                     /* De login log update, om aan te geven dat de two_way mislukt is. */
                     $this->update_login_log(false);
                     /* De ingevulde sleutel is onjuist. */
                     throw new Exception('De ingevulde sleutel is onjuist.');
                 }
             } else {
                 /* Het account bestaat niet. */
                 throw new Exception('Dit account bestaat niet.');
             }
         } else {
             /* MySQL foutmelding. */
             throw new Exception('Er ging wat fout in de database.<br />' . Database::error());
         }
     } else {
         /* Er is geen sleutel ingevuld. */
         throw new Exception('Er dient een sleutel ingevuld te worden.');
     }
 }
Exemplo n.º 30
0
<?php

require_once './GoogleAuthenticator.php';
$ga = new GoogleAuthenticator();
$secret = $ga->createSecret();
$name = $_GET['user'];
$qrCodeUrl = 'otpauth://totp/' . $name . '@Elgg?secret=' . $secret;
echo $secret . ';' . $qrCodeUrl;