private function prepare() { \phpCAS::client(CAS_VERSION_2_0, $this->casUrl, $this->casPort, $this->casUri, false); //\phpCAS::setDebug('/tmp/cas.log'); \phpCAS::setNoCasServerValidation(); //\phpCAS::setSingleSignoutCallback(array($this, 'casSingleSignOut')); //\phpCAS::setPostAuthenticateCallback(array($this, 'casPostAuth')); \phpCAS::handleLogoutRequests(true, $this->casAllowedIpClients); }
public function __construct() { parent::__construct(); $this->load->database(); $this->load->library('grocery_CRUD'); include_once 'CAS.php'; phpCAS::client('2.0', 'cas.uhp-nancy.fr', 443, '/cas', false); phpCAS::setNoCasServerValidation(); phpCAS::handleLogoutRequests(false); }
function check_auth() { if (!isset($GLOBALS['PHPCAS_CLIENT'])) { phpCAS::client(CAS_VERSION_2_0, 'cas.byu.edu', 443, 'cas'); //phpCAS::setCasServerCACert("../CAS/cas_ca.pem"); phpCAS::setNoCasServerValidation(); phpCAS::setDebug("cas_error.txt"); phpCAS::handleLogoutRequests(true, array('cas.byu.edu', 'cas1.byu.edu', 'cas2.byu.edu', 'cas3.byu.edu')); } return phpCAS::isAuthenticated(); }
public static function init() { if (self::$_init) { return true; } $config = new \Yaf\Config\Ini(APPLICATION_CONFIG_PATH . '/phpcas.ini', \Yaf\ENVIRON); phpCAS::setDebug(''); phpCAS::client($config->cas_version, $config->cas_host, intval($config->cas_port), $config->cas_context); phpCAS::setNoCasServerValidation(); phpCAS::handleLogoutRequests(false); self::$_init = true; return true; }
private function setCASSettings() { if ($this->options->IsCasDebugOn()) { phpCAS::setDebug($this->options->DebugFile()); } phpCAS::client($this->options->CasVersion(), $this->options->HostName(), $this->options->Port(), $this->options->ServerUri(), $this->options->ChangeSessionId()); if ($this->options->CasHandlesLogouts()) { phpCAS::handleLogoutRequests(true, $this->options->LogoutServers()); } if ($this->options->HasCertificate()) { phpCAS::setCasServerCACert($this->options->Certificate()); } phpCAS::setNoCasServerValidation(); }
function handle($args) { parent::handle($args); if (common_is_real_login()) { // TRANS: Client error displayed when trying to log in while already logged on. $this->clientError(_m('Already logged in.')); } else { global $casSettings; phpCAS::client(CAS_VERSION_2_0, $casSettings['server'], $casSettings['port'], $casSettings['path'], false); phpCAS::setNoCasServerValidation(); phpCAS::handleLogoutRequests(); phpCAS::forceAuthentication(); global $casTempPassword; $casTempPassword = common_good_rand(16); $user = common_check_user(phpCAS::getUser(), $casTempPassword); if (!$user) { // TRANS: Server error displayed when trying to log in with incorrect username or password. $this->serverError(_m('Incorrect username or password.')); return; } // success! if (!common_set_user($user)) { // TRANS: Server error displayed when login fails in CAS authentication plugin. $this->serverError(_m('Error setting user. You are probably not authorized.')); return; } common_real_login(true); $url = common_get_returnto(); if ($url) { // We don't have to return to it again common_set_returnto(null); } else { if (common_config('site', 'private') && $casSettings['takeOverLogin']) { //SSO users expect to just go to the URL they entered //if we don't have a returnto set, the user entered the //main StatusNet url, so send them there. $url = common_local_url('public'); } else { //With normal logins (regular form-based username/password), //the user would expect to go to their home after logging in. $url = common_local_url('public', array('nickname' => $user->nickname)); } } common_redirect($url, 303); } }
public function FilterApplicationConfig(&$oConfig) { $sCasHost = \trim($this->Config()->Get('plugin', 'cas_server_host', '')); $iCasPort = $this->Config()->Get('plugin', 'cas_server_port', 8443); phpCAS::setDebug('/tmp/phpCAS-rl.log'); // Schrijft debug informatie naar een log-file // Parameters: CAS version, CAS server url, CAS server port, CAS server URI (same as host), // boolean indicating session start, communication protocol (SAML) between application and CAS server phpCAS::client(CAS_VERSION_3_0, $sCasHost, $iCasPort, '', true, 'saml'); // Server from which logout requests are sent // phpCAS::handleLogoutRequests(true, array('cas1.ugent.be','cas2.ugent.be','cas3.ugent.be','cas4.ugent.be','cas5.ugent.be','cas6.ugent.be')); phpCAS::handleLogoutRequests(true, array('http://localhost:8080/php_cas_login/home.html')); // Path to the "trusted certificate authorities" file: // phpCAS::setCasServerCACert('/etc/ssl/certs/ca-certificates.crt'); // No server verification (less safe!): phpCAS::setNoCasServerValidation(); // The actual user authentication phpCAS::forceAuthentication(); $this->oAccountManagementProvider = $this->AccountManagementProvider($oConfig); }
public static function sso($action = 'login') { include_once ROOT_PATH . 'lib/cas/CAS.php'; include_once ROOT_PATH . 'config/cas.php'; $client = ''; // error_reporting(E_ALL); // ini_set("display_errors", 1); $cas_host = CAS_HOST; $cas_port = intval(CAS_PORT); $cas_context = CAS_CONTEXT; $phpCAS = new \phpCAS(); // $phpCAS->setDebug(); $phpCAS->client(CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); $phpCAS->setNoCasServerValidation(); $phpCAS->handleLogoutRequests(); $phpCAS->forceAuthentication(); if (isset($action) && $action == 'logout') { $phpCAS->logout(); } $client = $phpCAS->getAttributes(); return $client; }
function authenticate_cas() { include_once('CAS.php'); if ($GLOBALS['mode_debug']) { phpCAS::setDebug($GLOBALS['debug_log_file']); } // config_cas.inc.php est le fichier d'informations de connexions au serveur cas $path = dirname(__FILE__)."/../secure/config_cas.inc.php"; include($path); // Le premier argument est la version du protocole CAS phpCAS::client(CAS_VERSION_2_0, $cas_host, $cas_port, $cas_root, true); phpCAS::setLang('french'); // redirige vers le serveur d'authentification si aucun utilisateur authentifié n'a // été trouvé par le client CAS. phpCAS::setNoCasServerValidation(); // Gestion du single sign-out phpCAS::handleLogoutRequests(false); // Authentification phpCAS::forceAuthentication(); $this->login = phpCAS::getUser(); // On réinitialise la session session_name("GEPI"); session_start(); $_SESSION['login'] = $this->login; $this->current_auth_mode = "sso"; return true; }
/** * Constructor * * Carry out sanity checks to ensure the object is * able to operate. Set capabilities. * * @author Fabian Bircher <*****@*****.**> */ public function __construct() { parent::__construct(); global $config_cascade; global $conf; // allow the preloading to configure other user files if (isset($config_cascade['plaincasauth.users']) && isset($config_cascade['plaincasauth.users']['default'])) { $this->casuserfile = $config_cascade['plaincasauth.users']['default']; } else { $this->casuserfile = DOKU_CONF . 'users.auth.plaincas.php'; } $this->localuserfile = $config_cascade['plainauth.users']['default']; // check the state of the file with the users and attempt to create it. if (!@is_readable($this->casuserfile)) { if (!fopen($this->casuserfile, 'w')) { msg("plainCAS: The CAS users file could not be opened.", -1); $this->success = false; } elseif (!@is_readable($this->casuserfile)) { $this->success = false; } else { $this->success = true; } // die( "bitch!" ); } if ($this->success) { // the users are not managable through the wiki $this->cando['addUser'] = false; $this->cando['delUser'] = true; $this->cando['modLogin'] = false; //keep this false as CAS name is constant $this->cando['modPass'] = false; $this->cando['modName'] = false; $this->cando['modMail'] = false; $this->cando['modGroups'] = false; $this->cando['getUsers'] = true; $this->cando['getUserCount'] = true; $this->cando['external'] = preg_match("#(bot)|(slurp)|(netvibes)#i", $_SERVER['HTTP_USER_AGENT']) ? false : true; //Disable CAS redirection for bots/crawlers/readers $this->cando['login'] = true; $this->cando['logout'] = true; $this->cando['logoff'] = true; // The default options which need to be set in the settins file. $defaults = array('logFile' => NULL, 'cert' => NULL, 'cacert' => NULL, 'debug' => false, 'settings_file' => DOKU_CONF . 'plaincas.settings.php', 'defaultgroup' => $conf['defaultgroup'], 'superuser' => $conf['superuser']); $this->_options = (array) $conf['plugin']['authplaincas'] + $defaults; // Options are set in the configuration and have a proper default value there. $this->_options['server'] = $this->getConf('server'); $this->_options['rootcas'] = $this->getConf('rootcas'); $this->_options['port'] = $this->getConf('port'); $this->_options['samlValidate'] = $this->getConf('samlValidate'); $this->_options['autologin'] = $this->getConf('autologinout'); // $this->getConf('autologin'); $this->_options['caslogout'] = $this->getConf('autologinout'); // $this->getConf('caslogout'); $this->_options['handlelogoutrequest'] = $this->getConf('handlelogoutrequest'); $this->_options['handlelogoutrequestTrustedHosts'] = $this->getConf('handlelogoutrequestTrustedHosts'); $this->_options['minimalgroups'] = $this->getConf('minimalgroups'); $this->_options['localusers'] = $this->getConf('localusers'); // $this->_options['defaultgroup'] = $this->getConf('defaultgroup'); // $this->_options['superuser'] = $this->getConf('superuser'); // no local users at the moment $this->_options['localusers'] = false; if ($this->_options['localusers'] && !@is_readable($this->localuserfile)) { msg("plainCAS: The local users file is not readable.", -1); $this->success = false; } if ($this->_getOption("logFile")) { phpCAS::setDebug($this->_getOption("logFile")); } //If $conf['auth']['cas']['logFile'] exist we start phpCAS in debug mode $server_version = CAS_VERSION_2_0; if ($this->_getOption("samlValidate")) { $server_version = SAML_VERSION_1_1; } phpCAS::client($server_version, $this->_getOption('server'), (int) $this->_getOption('port'), $this->_getOption('rootcas'), true); //Note the last argument true, to allow phpCAS to change the session_id so he will be able to destroy the session after a CAS logout request - Enable Single Sign Out // curl extension is needed if (!function_exists('curl_init')) { if ($this->_getOption('debug')) { msg("CAS err: CURL extension not found.", -1, __LINE__, __FILE__); } $this->success = false; return; } // automatically log the user when there is a cas session opened if ($this->_getOption('autologin')) { phpCAS::setCacheTimesForAuthRecheck(1); } else { phpCAS::setCacheTimesForAuthRecheck(-1); } if ($this->_getOption('cert')) { phpCAS::setCasServerCert($this->_getOption('cert')); } elseif ($this->_getOption('cacert')) { phpCAS::setCasServerCACert($this->_getOption('cacert')); } else { phpCAS::setNoCasServerValidation(); } if ($this->_getOption('handlelogoutrequest')) { phpCAS::handleLogoutRequests(true, $this->_getOption('handlelogoutrequestTrustedHosts')); } else { phpCAS::handleLogoutRequests(false); } if (@is_readable($this->_getOption('settings_file'))) { include_once $this->_getOption('settings_file'); } else { include_once DOKU_PLUGIN . 'authplaincas/plaincas.settings.php'; } } // }
private function _synlogout() { phpCAS::handleLogoutRequests(false); }
/** * Configure SSL Validation * * Having some kind of server cert validation in production * is highly recommended. */ protected function configureCasValidation($config) { if ($config['cas_validation'] == 'ca' || $config['cas_validation'] == 'self') { phpCAS::setCasServerCACert($config['cas_cert'], $config['cas_validate_cn']); } else { // Not safe (does not validate your CAS server) phpCAS::setNoCasServerValidation(); } phpCAS::handleLogoutRequests(false); }
<?php include_once 'CAS-1.3.1/CAS.php'; //phpCAS::setDebug('/tmp/phpCAS.log'); // Schrijft debug informatie naar een log-file // Parameters: CAS versie, url CAS server, poort CAS server, CAS server URI (idem als host), // boolean die aangeeft of sessie moet gestart worden, communicatieprotocol (SAML) tussen toepassing en CAS server phpCAS::client(SAML_VERSION_1_1, 'login.ugent.be', 443, '', true, 'saml'); // Geeft aan vanaf welke server logout requests mogelijk zijn phpCAS::handleLogoutRequests(true, array('cas1.ugent.be', 'cas2.ugent.be', 'cas3.ugent.be', 'cas4.ugent.be', 'cas5.ugent.be', 'cas6.ugent.be')); // Configuratie van het certificaat van de CAS server phpCAS::setExtraCurlOption(CURLOPT_SSLVERSION, 3); // Locatie van het "trusted certificate authorities" bestand: phpCAS::setCasServerCACert('/etc/ssl/certs/ca-certificates.crt'); // Geen server verificatie (minder veilig!): //phpCAS::setNoCasServerValidation(); // Hier gebeurt de authenticatie van de gebruiker phpCAS::forceAuthentication(); // Opvangen van logout requests if (isset($_REQUEST['logout'])) { phpCAS::logout(); } ?> <html> <head> <title>phpCAS simple client</title> </head> <body> <h1>Successfull Authentication!</h1> <p>the user's login is <b><?php
public function getUser(CakeRequest $request) { phpCAS::handleLogoutRequests(false); phpCAS::forceAuthentication(); return array_merge(array('username' => phpCAS::getUser()), phpCAS::getAttributes()); }
function buildsurveysession($surveyid, $preview = false) { global $hitid, $hitname; Yii::trace('start', 'survey.buildsurveysession'); global $secerror, $clienttoken; global $tokensexist; //global $surveyid; global $move, $rooturl; $sLangCode = App()->language; $languagechanger = makeLanguageChangerSurvey($sLangCode); if (!$preview) { $preview = Yii::app()->getConfig('previewmode'); } $thissurvey = getSurveyInfo($surveyid, $sLangCode); $_SESSION['survey_' . $surveyid]['templatename'] = $thissurvey['template']; // $thissurvey['template'] already fixed by model : but why put this in session ? $_SESSION['survey_' . $surveyid]['templatepath'] = getTemplatePath($thissurvey['template']) . DIRECTORY_SEPARATOR; $sTemplatePath = $_SESSION['survey_' . $surveyid]['templatepath']; $loadsecurity = returnGlobal('loadsecurity', true); // NO TOKEN REQUIRED BUT CAPTCHA ENABLED FOR SURVEY ACCESS if ($tokensexist == 0 && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha']) && !isset($_SESSION['survey_' . $surveyid]['captcha_surveyaccessscreen']) && !$preview) { //session_start(); require_once dirname(__FILE__) . "/CAS/CAS.php"; //指定log文件 phpCAS::setDebug('./log.log'); //指定cas地址,最后一个true表示是否cas服务器为https phpCAS::client(CAS_VERSION_2_0, 'ids.hit.edu.cn', 443, 'authserver', true); phpCAS::handleLogoutRequests(); //本地退出应该重定向到CAS进行退出,传递service参数可以使CAS退出后返回本应用 //demo表示退出请求为logout的请求 if (isset($_GET['logout'])) { $param = array('service' => 'http://demo.cas.wisedu.cn:3273/'); phpCAS::logout($param); exit; } //设置no ssl,即忽略证书检查.如果需要ssl,请用 phpCAS::setCasServerCACert()设置 //setCasServerCACert方法设置ssl证书, phpCAS::setNoCasServerValidation(); phpCAS::forceAuthentication(); $hitid = phpCAS::getUser(); $hitname = phpCAS::getAttributes()["cn"]; /*//默认的就是这种状况 // IF CAPTCHA ANSWER IS NOT CORRECT OR NOT SET //echo 2221; if (!isset($loadsecurity) || !isset($_SESSION['survey_'.$surveyid]['secanswer']) || $loadsecurity != $_SESSION['survey_'.$surveyid]['secanswer']) { //echo 111; sendCacheHeaders(); doHeader(); // No or bad answer to required security question $redata = compact(array_keys(get_defined_vars())); //下面一行测试注释掉,除样式没有发现其他影响 //echo templatereplace(file_get_contents($sTemplatePath."startpage.pstpl"),array(),$redata,'frontend_helper[875]'); //echo makedropdownlist(); echo templatereplace(file_get_contents($sTemplatePath."survey.pstpl"),array(),$redata,'frontend_helper[877]'); echo "我们需要对你的身份进行确认,确保你是哈尔滨工业大学师生,请点击下面的按钮进行全校统一认证登录"; if (isset($loadsecurity)) { // was a bad answer echo "<font color='#FF0000'>".gT("The answer to the security question is incorrect.")."</font><br />"; } echo "<p class='captcha'>".gT("Please confirm access to survey by answering the security question below and click continue.")."</p>" .CHtml::form(array("/survey/index","sid"=>$surveyid), 'post', array('class'=>'captcha'))." <table align='center'> <tr> <td align='right' valign='middle'> <input type='hidden' name='sid' value='".$surveyid."' id='sid' /> <input type='hidden' name='lang' value='".$sLangCode."' id='lang' />"; // In case we this is a direct Reload previous answers URL, then add hidden fields if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) { echo " <input type='hidden' name='loadall' value='".htmlspecialchars($_GET['loadall'],ENT_QUOTES, 'UTF-8')."' id='loadall' /> <input type='hidden' name='scid' value='".returnGlobal('scid',true)."' id='scid' /> <input type='hidden' name='loadname' value='".htmlspecialchars($_GET['loadname'],ENT_QUOTES, 'UTF-8')."' id='loadname' /> <input type='hidden' name='loadpass' value='".htmlspecialchars($_GET['loadpass'],ENT_QUOTES, 'UTF-8')."' id='loadpass' />"; } echo " </td> </tr>"; if (function_exists("ImageCreate") && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { echo "<tr> <td align='center' valign='middle'><label for='captcha'>".gT("Security question:")."</label></td><td align='left' valign='middle'><table><tr><td valign='middle'><img src='".Yii::app()->getController()->createUrl('/verification/image/sid/'.$surveyid)."' alt='captcha' /></td> <td valign='middle'><input id='captcha' type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table> </td> </tr>"; } echo "<tr><td colspan='2' align='center'><input class='submit' type='submit' value='".gT("Continue")."' /></td></tr> </table> </form>"; echo templatereplace(file_get_contents($sTemplatePath."endpage.pstpl"),array(),$redata,'frontend_helper[1567]'); doFooter(); exit; } else{ $_SESSION['survey_'.$surveyid]['captcha_surveyaccessscreen']=true; }*/ } //BEFORE BUILDING A NEW SESSION FOR THIS SURVEY, LET'S CHECK TO MAKE SURE THE SURVEY SHOULD PROCEED! // TOKEN REQUIRED BUT NO TOKEN PROVIDED if ($tokensexist == 1 && !$clienttoken && !$preview) { if ($thissurvey['nokeyboard'] == 'Y') { includeKeypad(); $kpclass = "text-keypad"; } else { $kpclass = ""; } // DISPLAY REGISTER-PAGE if needed // DISPLAY CAPTCHA if needed if (isset($thissurvey) && $thissurvey['allowregister'] == "Y") { // Add the event and test if done Yii::app()->runController("register/index/sid/{$surveyid}"); Yii::app()->end(); } else { sendCacheHeaders(); doHeader(); $redata = compact(array_keys(get_defined_vars())); echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1594]'); //echo makedropdownlist(); echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1596]'); // ->renderPartial('entertoken_view'); if (isset($secerror)) { echo "<span class='error'>" . $secerror . "</span><br />"; } echo '<div id="wrapper"><p id="tokenmessage">' . gT("This is a controlled survey. You need a valid token to participate.") . "<br />"; echo gT("If you have been issued a token, please enter it in the box below and click continue.") . "</p>\n <script type='text/javascript'>var focus_element='#token';</script>" . CHtml::form(array("/survey/index", "sid" => $surveyid), 'post', array('id' => 'tokenform', 'autocomplete' => 'off')) . "\n <ul>\n <li>"; ?> <label for='token'><?php eT("Token:"); ?> </label><input class='text <?php echo $kpclass; ?> ' id='token' type='password' name='token' value='' /> <?php echo "<input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n <input type='hidden' name='lang' value='" . $sLangCode . "' id='lang' />"; if (isset($_GET['newtest']) && $_GET['newtest'] == "Y") { echo " <input type='hidden' name='newtest' value='Y' id='newtest' />"; } // If this is a direct Reload previous answers URL, then add hidden fields if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) { echo "\n <input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall'], ENT_QUOTES, 'UTF-8') . "' id='loadall' />\n <input type='hidden' name='scid' value='" . returnGlobal('scid', true) . "' id='scid' />\n <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname'], ENT_QUOTES, 'UTF-8') . "' id='loadname' />\n <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass'], ENT_QUOTES, 'UTF-8') . "' id='loadpass' />"; } echo "</li>"; if (function_exists("ImageCreate") && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { echo "<li>\n <label for='captchaimage'>" . gT("Security Question") . "</label><img id='captchaimage' src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . $surveyid) . "' alt='captcha' /><input type='text' size='5' maxlength='3' name='loadsecurity' value='' />\n </li>"; } echo "<li>\n <input class='submit button' type='submit' value='" . gT("Continue") . "' />\n </li>\n </ul>\n </form></div>"; echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1645]'); doFooter(); exit; } } elseif ($tokensexist == 1 && $clienttoken && !isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { //check if token actually does exist // check also if it is allowed to change survey after completion if ($thissurvey['alloweditaftercompletion'] == 'Y') { $oTokenEntry = Token::model($surveyid)->findByAttributes(array('token' => $clienttoken)); } else { $oTokenEntry = Token::model($surveyid)->usable()->incomplete()->findByAttributes(array('token' => $clienttoken)); } if (!isset($oTokenEntry)) { //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT killSurveySession($surveyid); sendCacheHeaders(); doHeader(); $redata = compact(array_keys(get_defined_vars())); echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1676]'); echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1677]'); echo '<div id="wrapper"><p id="tokenmessage">' . gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />\n" . "\t" . gT("The token you have provided is either not valid, or has already been used.") . "<br /><br />\n" . "\t" . sprintf(gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)</p></div>\n"; echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1684]'); doFooter(); exit; } } elseif ($tokensexist == 1 && $clienttoken && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { // IF CAPTCHA ANSWER IS CORRECT if (isset($loadsecurity) && isset($_SESSION['survey_' . $surveyid]['secanswer']) && $loadsecurity == $_SESSION['survey_' . $surveyid]['secanswer']) { if ($thissurvey['alloweditaftercompletion'] == 'Y') { $oTokenEntry = Token::model($surveyid)->findByAttributes(array('token' => $clienttoken)); } else { $oTokenEntry = Token::model($surveyid)->incomplete()->findByAttributes(array('token' => $clienttoken)); } if (!isset($oTokenEntry)) { sendCacheHeaders(); doHeader(); //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT $redata = compact(array_keys(get_defined_vars())); echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1719]'); echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1720]'); echo "\t<div id='wrapper'>\n" . "\t<p id='tokenmessage'>\n" . "\t" . gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />\n" . "\t" . gT("The token you have provided is either not valid, or has already been used.") . "<br/><br />\n" . "\t" . sprintf(gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)\n" . "\t</p>\n" . "\t</div>\n"; echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1731]'); doFooter(); exit; } } else { if (!isset($move) || is_null($move)) { unset($_SESSION['survey_' . $surveyid]['srid']); $gettoken = $clienttoken; sendCacheHeaders(); doHeader(); // No or bad answer to required security question $redata = compact(array_keys(get_defined_vars())); echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1745]'); echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1746]'); // If token wasn't provided and public registration // is enabled then show registration form if (!isset($gettoken) && isset($thissurvey) && $thissurvey['allowregister'] == "Y") { echo templatereplace(file_get_contents($sTemplatePath . "register.pstpl"), array(), $redata, 'frontend_helper[1751]'); } else { // only show CAPTCHA echo '<div id="wrapper"><p id="tokenmessage">'; if (isset($loadsecurity)) { // was a bad answer echo "<span class='error'>" . gT("The answer to the security question is incorrect.") . "</span><br />"; } echo gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />"; // IF TOKEN HAS BEEN GIVEN THEN AUTOFILL IT // AND HIDE ENTRY FIELD if (!isset($gettoken)) { echo gT("If you have been issued a token, please enter it in the box below and click continue.") . "</p>\n <form id='tokenform' method='get' action='" . Yii::app()->getController()->createUrl("/survey/index") . "'>\n <ul>\n <li>\n <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n <input type='hidden' name='lang' value='" . $sLangCode . "' id='lang' />"; if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) { echo "<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall'], ENT_QUOTES, 'UTF-8') . "' id='loadall' />\n <input type='hidden' name='scid' value='" . returnGlobal('scid', true) . "' id='scid' />\n <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname'], ENT_QUOTES, 'UTF-8') . "' id='loadname' />\n <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass'], ENT_QUOTES, 'UTF-8') . "' id='loadpass' />"; } echo '<label for="token">' . gT("Token") . "</label><input class='text' type='password' id='token' name='token'></li>"; } else { echo gT("Please confirm the token by answering the security question below and click continue.") . "</p>\n <form id='tokenform' method='get' action='" . Yii::app()->getController()->createUrl("/survey/index") . "'>\n <ul>\n <li>\n <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n <input type='hidden' name='lang' value='" . $sLangCode . "' id='lang' />"; if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) { echo "<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall'], ENT_QUOTES, 'UTF-8') . "' id='loadall' />\n <input type='hidden' name='scid' value='" . returnGlobal('scid', true) . "' id='scid' />\n <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname'], ENT_QUOTES, 'UTF-8') . "' id='loadname' />\n <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass'], ENT_QUOTES, 'UTF-8') . "' id='loadpass' />"; } echo '<label for="token">' . gT("Token:") . "</label><span id='token'>{$gettoken}</span>" . "<input type='hidden' name='token' value='{$gettoken}'></li>"; } if (function_exists("ImageCreate") && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { echo "<li>\n <label for='captchaimage'>" . gT("Security Question") . "</label><img id='captchaimage' src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . $surveyid) . "' alt='captcha' /><input type='text' size='5' maxlength='3' name='loadsecurity' value='' />\n </li>"; } echo "<li><input class='submit' type='submit' value='" . gT("Continue") . "' /></li>\n </ul>\n </form>\n </id>"; } echo '</div>' . templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1817]'); doFooter(); exit; } } } //RESET ALL THE SESSION VARIABLES AND START AGAIN unset($_SESSION['survey_' . $surveyid]['grouplist']); unset($_SESSION['survey_' . $surveyid]['fieldarray']); unset($_SESSION['survey_' . $surveyid]['insertarray']); unset($_SESSION['survey_' . $surveyid]['fieldnamesInfo']); unset($_SESSION['survey_' . $surveyid]['fieldmap-' . $surveyid . '-randMaster']); unset($_SESSION['survey_' . $surveyid]['groupReMap']); $_SESSION['survey_' . $surveyid]['fieldnamesInfo'] = array(); // Multi lingual support order : by REQUEST, if not by Token->language else by survey default language if (returnGlobal('lang', true)) { $language_to_set = returnGlobal('lang', true); } elseif (isset($oTokenEntry) && $oTokenEntry) { // If survey have token : we have a $oTokenEntry // Can use $oTokenEntry = Token::model($surveyid)->findByAttributes(array('token'=>$clienttoken)); if we move on another function : this par don't validate the token validity $language_to_set = $oTokenEntry->language; } else { $language_to_set = $thissurvey['language']; } // Always SetSurveyLanguage : surveys controller SetSurveyLanguage too, if different : broke survey (#09769) SetSurveyLanguage($surveyid, $language_to_set); UpdateGroupList($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']); $sQuery = "SELECT count(*)\n" . " FROM {{groups}} INNER JOIN {{questions}} ON {{groups}}.gid = {{questions}}.gid\n" . " WHERE {{questions}}.sid=" . $surveyid . "\n" . " AND {{groups}}.language='" . App()->getLanguage() . "'\n" . " AND {{questions}}.language='" . App()->getLanguage() . "'\n" . " AND {{questions}}.parent_qid=0\n"; $totalquestions = Yii::app()->db->createCommand($sQuery)->queryScalar(); $sQuery = "select count(*) from {{groups}}\n left join {{questions}} on {{groups}}.gid={{questions}}.gid\n where {{groups}}.sid={$surveyid} and qid is null"; $iTotalGroupsWithoutQuestions = Yii::app()->db->createCommand($sQuery)->queryScalar(); // Fix totalquestions by substracting Test Display questions $iNumberofQuestions = dbExecuteAssoc("SELECT count(*)\n" . " FROM {{questions}}" . " WHERE type in ('X','*')\n" . " AND sid={$surveyid}" . " AND language='" . $_SESSION['survey_' . $surveyid]['s_lang'] . "'" . " AND parent_qid=0")->read(); $_SESSION['survey_' . $surveyid]['totalquestions'] = $totalquestions - (int) reset($iNumberofQuestions); //2. SESSION VARIABLE: totalsteps //The number of "pages" that will be presented in this survey //The number of pages to be presented will differ depending on the survey format switch ($thissurvey['format']) { case "A": $_SESSION['survey_' . $surveyid]['totalsteps'] = 1; break; case "G": if (isset($_SESSION['survey_' . $surveyid]['grouplist'])) { $_SESSION['survey_' . $surveyid]['totalsteps'] = count($_SESSION['survey_' . $surveyid]['grouplist']); } break; case "S": $_SESSION['survey_' . $surveyid]['totalsteps'] = $totalquestions; } if ($totalquestions == 0 || $iTotalGroupsWithoutQuestions > 0) { sendCacheHeaders(); doHeader(); $redata = compact(array_keys(get_defined_vars())); echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1914]'); echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1915]'); echo "\t<div id='wrapper'>\n" . "\t<p id='tokenmessage'>\n" . "\t" . gT("This survey cannot be tested or completed for the following reason(s):") . "<br />\n"; echo "<ul>"; if ($totalquestions == 0) { echo '<li>' . gT("There are no questions in this survey.") . '</li>'; } if ($iTotalGroupsWithoutQuestions == 0) { echo '<li>' . gT("There are empty question groups in this survey - please create at least one question within a question group.") . '</li>'; } echo "</ul>" . "\t" . sprintf(gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)<br /><br />\n" . "\t</p>\n" . "\t</div>\n"; echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1925]'); doFooter(); exit; } //Perform a case insensitive natural sort on group name then question title of a multidimensional array // usort($arows, 'groupOrderThenQuestionOrder'); //3. SESSION VARIABLE - insertarray //An array containing information about used to insert the data into the db at the submit stage //4. SESSION VARIABLE - fieldarray //See rem at end.. if ($tokensexist == 1 && $clienttoken) { $_SESSION['survey_' . $surveyid]['token'] = $clienttoken; } if ($thissurvey['anonymized'] == "N") { $_SESSION['survey_' . $surveyid]['insertarray'][] = "token"; } $qtypes = getQuestionTypeList('', 'array'); $fieldmap = createFieldMap($surveyid, 'full', true, false, $_SESSION['survey_' . $surveyid]['s_lang']); // Randomization groups for groups $aRandomGroups = array(); $aGIDCompleteMap = array(); // first find all groups and their groups IDS $criteria = new CDbCriteria(); $criteria->addColumnCondition(array('sid' => $surveyid, 'language' => $_SESSION['survey_' . $surveyid]['s_lang'])); $criteria->addCondition("randomization_group != ''"); $oData = QuestionGroup::model()->findAll($criteria); foreach ($oData as $aGroup) { $aRandomGroups[$aGroup['randomization_group']][] = $aGroup['gid']; } // Shuffle each group and create a map for old GID => new GID foreach ($aRandomGroups as $sGroupName => $aGIDs) { $aShuffledIDs = $aGIDs; shuffle($aShuffledIDs); $aGIDCompleteMap = $aGIDCompleteMap + array_combine($aGIDs, $aShuffledIDs); } $_SESSION['survey_' . $surveyid]['groupReMap'] = $aGIDCompleteMap; $randomized = false; // So we can trigger reorder once for group and question randomization // Now adjust the grouplist if (count($aRandomGroups) > 0 && !$preview) { $randomized = true; // So we can trigger reorder once for group and question randomization // Now adjust the grouplist Yii::import('application.helpers.frontend_helper', true); // make sure frontend helper is loaded UpdateGroupList($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']); // ... and the fieldmap // First create a fieldmap with GID as key foreach ($fieldmap as $aField) { if (isset($aField['gid'])) { $GroupFieldMap[$aField['gid']][] = $aField; } else { $GroupFieldMap['other'][] = $aField; } } // swap it foreach ($GroupFieldMap as $iOldGid => $fields) { $iNewGid = $iOldGid; if (isset($aGIDCompleteMap[$iOldGid])) { $iNewGid = $aGIDCompleteMap[$iOldGid]; } $newGroupFieldMap[$iNewGid] = $GroupFieldMap[$iNewGid]; } $GroupFieldMap = $newGroupFieldMap; // and convert it back to a fieldmap unset($fieldmap); foreach ($GroupFieldMap as $aGroupFields) { foreach ($aGroupFields as $aField) { if (isset($aField['fieldname'])) { $fieldmap[$aField['fieldname']] = $aField; // isset() because of the shuffled flag above } } } unset($GroupFieldMap); } // Randomization groups for questions // Find all defined randomization groups through question attribute values $randomGroups = array(); if (in_array(Yii::app()->db->getDriverName(), array('mssql', 'sqlsrv', 'dblib'))) { $rgquery = "SELECT attr.qid, CAST(value as varchar(255)) as value FROM {{question_attributes}} as attr right join {{questions}} as quests on attr.qid=quests.qid WHERE attribute='random_group' and CAST(value as varchar(255)) <> '' and sid={$surveyid} GROUP BY attr.qid, CAST(value as varchar(255))"; } else { $rgquery = "SELECT attr.qid, value FROM {{question_attributes}} as attr right join {{questions}} as quests on attr.qid=quests.qid WHERE attribute='random_group' and value <> '' and sid={$surveyid} GROUP BY attr.qid, value"; } $rgresult = dbExecuteAssoc($rgquery); foreach ($rgresult->readAll() as $rgrow) { // Get the question IDs for each randomization group $randomGroups[$rgrow['value']][] = $rgrow['qid']; } // If we have randomization groups set, then lets cycle through each group and // replace questions in the group with a randomly chosen one from the same group if (count($randomGroups) > 0 && !$preview) { $randomized = true; // So we can trigger reorder once for group and question randomization $copyFieldMap = array(); $oldQuestOrder = array(); $newQuestOrder = array(); $randGroupNames = array(); foreach ($randomGroups as $key => $value) { $oldQuestOrder[$key] = $randomGroups[$key]; $newQuestOrder[$key] = $oldQuestOrder[$key]; // We shuffle the question list to get a random key->qid which will be used to swap from the old key shuffle($newQuestOrder[$key]); $randGroupNames[] = $key; } // Loop through the fieldmap and swap each question as they come up foreach ($fieldmap as $fieldkey => $fieldval) { $found = 0; foreach ($randomGroups as $gkey => $gval) { // We found a qid that is in the randomization group if (isset($fieldval['qid']) && in_array($fieldval['qid'], $oldQuestOrder[$gkey])) { // Get the swapped question $idx = array_search($fieldval['qid'], $oldQuestOrder[$gkey]); foreach ($fieldmap as $key => $field) { if (isset($field['qid']) && $field['qid'] == $newQuestOrder[$gkey][$idx]) { $field['random_gid'] = $fieldval['gid']; // It is possible to swap to another group $copyFieldMap[$key] = $field; } } $found = 1; break; } else { $found = 2; } } if ($found == 2) { $copyFieldMap[$fieldkey] = $fieldval; } reset($randomGroups); } $fieldmap = $copyFieldMap; } if ($randomized === true) { // reset the sequencing counts $gseq = -1; $_gid = -1; $qseq = -1; $_qid = -1; $copyFieldMap = array(); foreach ($fieldmap as $key => $val) { if ($val['gid'] != '') { if (isset($val['random_gid'])) { $gid = $val['random_gid']; } else { $gid = $val['gid']; } if ($gid != $_gid) { $_gid = $gid; ++$gseq; } } if ($val['qid'] != '' && $val['qid'] != $_qid) { $_qid = $val['qid']; ++$qseq; } if ($val['gid'] != '' && $val['qid'] != '') { $val['groupSeq'] = $gseq; $val['questionSeq'] = $qseq; } $copyFieldMap[$key] = $val; } $fieldmap = $copyFieldMap; unset($copyFieldMap); $_SESSION['survey_' . $surveyid]['fieldmap-' . $surveyid . $_SESSION['survey_' . $surveyid]['s_lang']] = $fieldmap; $_SESSION['survey_' . $surveyid]['fieldmap-' . $surveyid . '-randMaster'] = 'fieldmap-' . $surveyid . $_SESSION['survey_' . $surveyid]['s_lang']; } // TMSW Condition->Relevance: don't need hasconditions, or usedinconditions $_SESSION['survey_' . $surveyid]['fieldmap'] = $fieldmap; foreach ($fieldmap as $field) { if (isset($field['qid']) && $field['qid'] != '') { $_SESSION['survey_' . $surveyid]['fieldnamesInfo'][$field['fieldname']] = $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']; $_SESSION['survey_' . $surveyid]['insertarray'][] = $field['fieldname']; //fieldarray ARRAY CONTENTS - // [0]=questions.qid, // [1]=fieldname, // [2]=questions.title, // [3]=questions.question // [4]=questions.type, // [5]=questions.gid, // [6]=questions.mandatory, // [7]=conditionsexist, // [8]=usedinconditions // [8]=usedinconditions // [9]=used in group.php for question count // [10]=new group id for question in randomization group (GroupbyGroup Mode) if (!isset($_SESSION['survey_' . $surveyid]['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']])) { //JUST IN CASE : PRECAUTION! //following variables are set only if $style=="full" in createFieldMap() in common_helper. //so, if $style = "short", set some default values here! if (isset($field['title'])) { $title = $field['title']; } else { $title = ""; } if (isset($field['question'])) { $question = $field['question']; } else { $question = ""; } if (isset($field['mandatory'])) { $mandatory = $field['mandatory']; } else { $mandatory = 'N'; } if (isset($field['hasconditions'])) { $hasconditions = $field['hasconditions']; } else { $hasconditions = 'N'; } if (isset($field['usedinconditions'])) { $usedinconditions = $field['usedinconditions']; } else { $usedinconditions = 'N'; } $_SESSION['survey_' . $surveyid]['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']] = array($field['qid'], $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid'], $title, $question, $field['type'], $field['gid'], $mandatory, $hasconditions, $usedinconditions); } if (isset($field['random_gid'])) { $_SESSION['survey_' . $surveyid]['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']][10] = $field['random_gid']; } } } // Prefill questions/answers from command line params $reservedGetValues = array('token', 'sid', 'gid', 'qid', 'lang', 'newtest', 'action'); $startingValues = array(); if (isset($_GET)) { foreach ($_GET as $k => $v) { if (!in_array($k, $reservedGetValues) && isset($_SESSION['survey_' . $surveyid]['fieldmap'][$k])) { $startingValues[$k] = $v; } else { // Search question codes to use those for prefilling. foreach ($_SESSION['survey_' . $surveyid]['fieldmap'] as $sgqa => $details) { if ($details['title'] == $k) { $startingValues[$sgqa] = $v; } } } } } $_SESSION['survey_' . $surveyid]['startingValues'] = $startingValues; if (isset($_SESSION['survey_' . $surveyid]['fieldarray'])) { $_SESSION['survey_' . $surveyid]['fieldarray'] = array_values($_SESSION['survey_' . $surveyid]['fieldarray']); } //Check if a passthru label and value have been included in the query url $oResult = SurveyURLParameter::model()->getParametersForSurvey($surveyid); foreach ($oResult->readAll() as $aRow) { if (isset($_GET[$aRow['parameter']]) && !$preview) { $_SESSION['survey_' . $surveyid]['urlparams'][$aRow['parameter']] = $_GET[$aRow['parameter']]; if ($aRow['targetqid'] != '') { foreach ($fieldmap as $sFieldname => $aField) { if ($aRow['targetsqid'] != '') { if ($aField['qid'] == $aRow['targetqid'] && $aField['sqid'] == $aRow['targetsqid']) { $_SESSION['survey_' . $surveyid]['startingValues'][$sFieldname] = $_GET[$aRow['parameter']]; $_SESSION['survey_' . $surveyid]['startingValues'][$aRow['parameter']] = $_GET[$aRow['parameter']]; } } else { if ($aField['qid'] == $aRow['targetqid']) { $_SESSION['survey_' . $surveyid]['startingValues'][$sFieldname] = $_GET[$aRow['parameter']]; $_SESSION['survey_' . $surveyid]['startingValues'][$aRow['parameter']] = $_GET[$aRow['parameter']]; } } } } } } Yii::trace('end', 'survey.buildsurveysession'); }
/** * Log out of the attached external service. * * @return void */ public function custom_logout() { // Grab plugin settings. $auth_settings = $this->get_plugin_options('single admin', 'allow override'); // Reset option containing old error messages. delete_option('auth_settings_advanced_login_error'); if (session_id() == '') { session_start(); } $current_user_authenticated_by = get_user_meta(get_current_user_id(), 'authenticated_by', true); // If logged in to CAS, Log out of CAS. if ($current_user_authenticated_by === 'cas' && $auth_settings['cas'] === '1') { if (!array_key_exists('PHPCAS_CLIENT', $GLOBALS) || !array_key_exists('phpCAS', $_SESSION)) { // Set the CAS client configuration if it hasn't been set already. phpCAS::client(SAML_VERSION_1_1, $auth_settings['cas_host'], intval($auth_settings['cas_port']), $auth_settings['cas_path']); // Restrict logout request origin to the CAS server only (prevent DDOS). phpCAS::handleLogoutRequests(true, array($auth_settings['cas_host'])); } if (phpCAS::isAuthenticated()) { phpCAS::logoutWithRedirectService(get_option('siteurl')); } } // If session token set, log out of Google. if ($current_user_authenticated_by === 'google' && array_key_exists('token', $_SESSION)) { $token = json_decode($_SESSION['token'])->access_token; // Build the Google Client. $client = new Google_Client(); $client->setApplicationName('WordPress'); $client->setClientId($auth_settings['google_clientid']); $client->setClientSecret($auth_settings['google_clientsecret']); $client->setRedirectUri('postmessage'); // Revoke the token $client->revokeToken($token); // Remove the credentials from the user's session. $_SESSION['token'] = ''; } }
// Harden session cookie to prevent some attacks on the cookie (e.g. XSS) session_set_cookie_params($client_lifetime, $client_path, $client_domain, $client_secure, $client_httpOnly); // Initialize phpCAS phpCAS::client(SAML_VERSION_1_1, $cas_host, $cas_port, $cas_context); // For production use set the CA certificate that is the issuer of the cert // on the CAS server and uncomment the line below phpCAS::setCasServerCACert($cas_server_ca_cert_path); // For quick testing you can disable SSL validation of the CAS server. // THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION. // VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL! // phpCAS::setNoCasServerValidation(); // Handle SAML logout requests that emanate from the CAS host exclusively. // Failure to restrict SAML logout requests to authorized hosts could // allow denial of service attacks where at the least the server is // tied up parsing bogus XML messages. phpCAS::handleLogoutRequests(true, $cas_real_hosts); // Force CAS authentication on any page that includes this file phpCAS::forceAuthentication(); // Some small code triggered by the logout button if (isset($_REQUEST['logout'])) { phpCAS::logout(); } ?> <html> <head> <title>Advanced SAML 1.1 example</title> </head> <body> <h2>Advanced SAML 1.1 example</h2> <?php require 'script_info.php';
/** * @brief 全局初始化接口 * * @return success-true failed-false * @retval boolean * @see getCasInit() * @note 这个函数修改了session的存储文件路径为/odp/data/phpcas,并关闭了phpCAS第三方库本身的日志 * @note 在一个CGI中phpCAS client对象只能被初始化一次,因此设置$isCasClientInit属性用来控制 * @author chenyijie * @date 2012/09/28 22:28:43 **/ private static function init() { if (self::$isCasClientInit) { return true; } if (!self::getCasInit()) { Bd_Log::warning('UUAP CAS protocol init failed'); return false; } $link = self::$arrConf['Server'][0]['Hostname']; $port = self::$arrConf['DefaultPort']; if (defined("IS_ODP")) { $path = Bd_AppEnv::getEnv('data'); $path = dirname(dirname($path)) . '/phpcas/'; session_save_path($path); } phpCAS::setDebug(''); phpCAS::client(CAS_VERSION_2_0, $link, intval($port), ''); phpCAS::setNoCasServerValidation(); phpCAS::handleLogoutRequests(false); self::$isCasClientInit = true; return true; }
require_once $phpcas_path . '/CAS.php'; // Enable debugging phpCAS::setDebug(); // Enable verbose error messages. Disable in production! phpCAS::setVerbose(true); // Initialize phpCAS phpCAS::client(CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context); // For production use set the CA certificate that is the issuer of the cert // on the CAS server and uncomment the line below // phpCAS::setCasServerCACert($cas_server_ca_cert_path); // For quick testing you can disable SSL validation of the CAS server. // THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION. // VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL! phpCAS::setNoCasServerValidation(); // handle incoming logout requests phpCAS::handleLogoutRequests(); // Or as an advanced featue handle SAML logout requests that emanate from the // CAS host exclusively. // Failure to restrict SAML logout requests to authorized hosts could // allow denial of service attacks where at the least the server is // tied up parsing bogus XML messages. // phpCAS::handleLogoutRequests(true, $cas_real_hosts); // force CAS authentication phpCAS::forceAuthentication(); // for this test, simply print that the authentication was successfull ?> <html> <head> <title>phpCAS simple client</title> </head> <body>
phpCAS::setExtraCurlOption(CURLOPT_PROXY, SERVEUR_PROXY_NAME); phpCAS::setExtraCurlOption(CURLOPT_PROXYPORT, (int) SERVEUR_PROXY_PORT); phpCAS::setExtraCurlOption(CURLOPT_PROXYTYPE, constant(SERVEUR_PROXY_TYPE)); if (SERVEUR_PROXY_AUTH_USED) { phpCAS::setExtraCurlOption(CURLOPT_PROXYAUTH, constant(SERVEUR_PROXY_AUTH_METHOD)); phpCAS::setExtraCurlOption(CURLOPT_PROXYUSERPWD, SERVEUR_PROXY_AUTH_USER . ':' . SERVEUR_PROXY_AUTH_PASS); } } // On indique qu'il faut vérifier la validité du certificat SSL, sauf exception paramétrée, mais alors dans ce cas ça ne sert à rien d'utiliser une connexion sécurisée. if (strpos(PHPCAS_NO_CERTIF_LISTING, ',' . $connexion_nom . ',') === FALSE) { phpCAS::setCasServerCACert(CHEMIN_FICHIER_CA_CERTS_FILE); } else { phpCAS::setNoCasServerValidation(); } // Gestion du single sign-out phpCAS::handleLogoutRequests(FALSE); // Déconnexion de CAS phpCAS::logout(); exit; } // //////////////////////////////////////////////////////////////////////////////////////////////////// // Déconnexion avec Shibboleth // //////////////////////////////////////////////////////////////////////////////////////////////////// if ($connexion_mode == 'shibboleth') { /* Pour le moment, on a acté avec le Catice qu'une déconnexion depuis une application entrainera seulement une déconnexion de cette application. Seule une déconnexion depuis Argos lancera le SLO (single sign out). Juste pour info, nous faisons le SLO par un appel à un url dont le path est /Shibboleth.sso/Logout Donc on ne rentre pas dans l'application (argos), c'est Shibboleth qui reçoit cette requête. Il envoie un message xml/soap (contenant l'ID Shibboleth) à une opération soap d'argos (implémentée pour l'occasion), qui déclenche la suppression du fichier de session php,
/** * @brief 全局初始化接口 * * @return success-true failed-false * @retval boolean * @see getCasInit() * @note 这个函数修改了session的存储文件路径为/odp/data/phpcas,并关闭了phpCAS第三方库本身的日志 * @note 在一个CGI中phpCAS client对象只能被初始化一次,因此设置$isCasClientInit属性用来控制 * @author chenyijie * @date 2012/09/28 22:28:43 **/ private static function init() { if (self::$isCasClientInit) { return true; } if (!self::getCasInit()) { Bd_Log::warning('UUAP CAS protocol init failed'); return false; } $link = self::$arrConf['Server'][0]['Hostname']; $port = self::$arrConf['DefaultPort']; phpCAS::setDebug(''); phpCAS::client(CAS_VERSION_2_0, $link, intval($port), '', false); // 自己管理session,最后参数为false by yuliang phpCAS::setNoCasServerValidation(); phpCAS::handleLogoutRequests(false); self::$isCasClientInit = true; return true; }
die('Stop!!!'); } // Enable debugging phpCAS::setDebug(); // Initialize phpCAS phpCAS::client($global_config['config_sso']['cas_version'], $global_config['config_sso']['cas_hostname'], $global_config['config_sso']['cas_port'], $global_config['config_sso']['cas_baseuri']); // For production use set the CA certificate that is the issuer of the cert // on the CAS server and uncomment the line below // phpCAS::setCasServerCACert($global_config['config_sso']['cas_certificate_path']); // For quick testing you can disable SSL validation of the CAS server. // THIS SETTING IS NOT RECOMMENDED FOR PRODUCTION. // VALIDATING THE CAS SERVER IS CRUCIAL TO THE SECURITY OF THE CAS PROTOCOL! phpCAS::setNoCasServerValidation(); // set the language to french //phpCAS::setLang(PHPCAS_LANG_FRENCH); phpCAS::handleLogoutRequests(false); // https://wiki.jasig.org/display/casum/single+sign+out#SingleSignOut-Howitworks // force CAS authentication phpCAS::forceAuthentication(); // logout if desired if (defined('CAS_LOGOUT_URL_REDIRECT')) { phpCAS::logoutWithRedirectService(CAS_LOGOUT_URL_REDIRECT); } $username = phpCAS::getUser(); if (!empty($username)) { if (nv_function_exists('ldap_connect')) { $ldapconn = ldap_connect($global_config['config_sso']['ldap_host_url']); ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, $global_config['config_sso']['ldap_version']); ldap_set_option($ldapconn, LDAP_OPT_REFERRALS, 0); if (!empty($global_config['config_sso']['ldap_bind_dn']) and !empty($global_config['config_sso']['ldap_bind_pw'])) { $ldapbind = ldap_bind($ldapconn, $global_config['config_sso']['ldap_bind_dn'], $global_config['config_sso']['ldap_bind_pw']);
function casSetup() { global $CASAuth; global $casIsSetUp; require_once $CASAuth["phpCAS"] . "/CAS.php"; phpCAS::client($CASAuth["Version"], $CASAuth["Server"], $CASAuth["Port"], $CASAuth["Url"], false); phpCAS::setSingleSignoutCallback('casSingleSignOut'); phpCAS::setPostAuthenticateCallback('casPostAuth'); phpCAS::handleLogoutRequests(true, isset($CASAuth["LogoutServers"]) ? $CASAuth["LogoutServers"] : false); phpCAS::setNoCasServerValidation(); $casIsSetUp = true; }
function casSetup() { global $CASAuth; if (!defined('PHPCAS_VERSION') || !class_exists('phpCAS')) { require_once $CASAuth["phpCAS"] . "/CAS.php"; } static $casIsSetUp = false; if ($casIsSetUp) { // phpCAS cannot be initialized twice. return; } phpCAS::client($CASAuth["Version"], $CASAuth["Server"], $CASAuth["Port"], $CASAuth["Url"], false); phpCAS::setSingleSignoutCallback('casSingleSignOut'); phpCAS::setPostAuthenticateCallback('casPostAuth'); phpCAS::handleLogoutRequests(true, isset($CASAuth["LogoutServers"]) ? $CASAuth["LogoutServers"] : false); phpCAS::setNoCasServerValidation(); $casIsSetUp = true; }
// (To be able to login via sch.gr's CAS, the app must be whitelisted from their admins) if (!$prDebug) { // phpCAS simple client, import phpCAS lib include_once 'include/CAS/CAS.php'; // initialize phpCAS using SAML phpCAS::client(SAML_VERSION_1_1, 'sso-test.sch.gr', 443, ''); // if logout if (isset($_POST['logout'])) { session_unset(); session_destroy(); phpCAS::logout(); } // no SSL validation for the CAS server, only for testing environments phpCAS::setNoCasServerValidation(); // handle backend logout requests from CAS server phpCAS::handleLogoutRequests(array('sso-test.sch.gr')); // force CAS authentication if (!phpCAS::checkAuthentication()) { phpCAS::forceAuthentication(); } // at this step, the user has been authenticated by the CAS server and the user's login name can be read with phpCAS::getUser(). $_SESSION['loggedin'] = 1; } else { $_SESSION['loggedin'] = 1; } header('Content-Type: text/html; charset=utf-8'); ?> <html> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <head> <title> <?php