checkAuthentication() public static method

This method is called to check if the user is already authenticated locally or has a global cas session. A already existing cas session is determined by a cas gateway call.(cas login call without any interactive prompt)
public static checkAuthentication ( ) : true
return true when the user is authenticated, false when a previous gateway login failed or the function will not return if the user is redirected to the cas server for a gateway login attempt
 /**
  * Logs the user out / destroys the CAS session
  */
 public function index()
 {
     if (\phpCAS::checkAuthentication()) {
         \phpCAS::logout();
     }
     session_destroy();
     header("Location: /landing");
     return;
 }
 function checkAuth()
 {
     if (CASUser::setup()) {
         //Allow it to be called multiple times, and return the auth info
         //Normally it will force a login if this isn't done
         return phpCAS::checkAuthentication();
     } else {
         return CASUser::isAuthenticated();
     }
 }
示例#3
0
文件: login.php 项目: Elwell/concerto
function check_login($callback)
{
    if (isLoggedIn()) {
        return true;
    }
    if ($callback->controller == 'users' && $callback->action == 'create') {
        return true;
    }
    //   if(phpCAS::isAuthenticated()) {
    //    login_login();
    //}
    if (phpCAS::checkAuthentication()) {
        login_login();
    }
}
    /**
     * [Put your description here]
     */
    function main($content, $conf)
    {
        $this->conf = $conf;
        $this->pi_setPiVarDefaults();
        $this->pi_USER_INT_obj = 1;
        // Configuring so caching is not expected. This value means that no cHash params are ever set. We do this, because it's a USER_INT object!
        $this->pi_loadLL();
        session_start();
        $this->typeExecution = "prod";
        $urlCas = "none";
        $portCas = "none";
        if ($this->typeExecution == "dev") {
            $urlCas = "xinf-devlinux.intranet.haras-nationaux.fr";
            $portCas = 7777;
        } else {
            if ($this->typeExecution == "prod") {
                $urlCas = "cerbere.haras-nationaux.fr";
                $portCas = 443;
            }
        }
        if (isset($_GET["userdebug"])) {
            include_once "typo3conf/ext/dlcube_hn_01/class.WebservicesCompte.php";
            include_once "typo3conf/ext/dlcube_hn_01/class.WebservicesAccess.php";
            $param[] = array("login" => $_GET["userdebug"], "ctx" => null);
            $ws = new WebservicesCompte();
            if (!$ws->connectIdent()) {
                $content = "ERROR:" . $ws->getErrorMessage();
                return $content;
            }
            $result = $ws->getPersonneByLogin($param);
            debug($result);
            print_r($result);
        }
        if (isset($_GET["action"]) && $_GET["action"] == "auth" && !isset($_GET["ticket"])) {
            phpCAS::setDebug();
            phpCAS::client(CAS_VERSION_2_0, $urlCas, $portCas, 'cas', 'true');
            $ur = phpCAS::getServerLoginURL(false);
            $content .= '<IFRAME src="' . $ur . '" frameborder="no" height="600" width="670"></IFRAME>';
            return $this->pi_wrapInBaseClass($content);
        }
        phpCAS::client(CAS_VERSION_2_0, $urlCas, $portCas, 'cas', 'true');
        phpCAS::checkAuthentication();
        $_SESSION["portalId"] = phpCAS::getUser();
        echo '<html><body><script type="text/javascript">
		    window.open( "' . $this->pi_getPageLink($_SESSION["service_id_auth"]) . '", "_top");
		</script></body>';
        exit;
    }
 /**
  * Cette methode permet de verifier si l'utilisateur
  * du portail poss�de d�j� une authentification SSO sur le
  * serveur CAS.
  * Si ce dernier ne poss�de pas d'authetification, le plugin redirige l'utilisateur sur
  * une page d'authentification CAS dans une iframe.
  */
 function main($content, $conf)
 {
     session_start();
     //$idPageAuth = '3434';
     $idPageAuth = '3682';
     $this->typeExecution = "prod";
     $urlCas = "none";
     $portCas = "none";
     if ($this->typeExecution == "dev") {
         $urlCas = "xinf-devlinux.intranet.haras-nationaux.fr";
         $portCas = 7777;
     } else {
         if ($this->typeExecution == "prod") {
             $urlCas = "cerbere.haras-nationaux.fr";
             $portCas = 443;
         }
     }
     //debug($_SESSION);
     if ($GLOBALS["TSFE"]->page["tx_dlcube04CAS_auth_cas_required"] == 1) {
         phpCAS::client(CAS_VERSION_2_0, $urlCas, $portCas, 'cas', 'true');
         $auth = phpCAS::checkAuthentication();
         if (!$auth) {
             $_SESSION["service_id_auth"] = $GLOBALS["TSFE"]->id;
             header('Location: ' . t3lib_div::locationHeaderUrl($this->pi_getPageLink($idPageAuth, "", array("action" => "auth"))));
             exit;
         } else {
             $_SESSION["portalId"] = phpCAS::getUser();
         }
     }
     if (isset($_GET["action_cas"]) && $_GET["action_cas"] == "logout") {
         unset($_SESSION["portalId"]);
         header('Location: ' . t3lib_div::locationHeaderUrl($this->pi_getPageLink("3683", "", array("action" => "disconnect"))));
     }
     /**
      * Gestion des langues pour le cookie
      */
     if (isset($_GET["lang"])) {
         if ($_GET["lang"] == "fr") {
             $this->cookie_fr();
         }
         if ($_GET["lang"] == "en") {
             $this->cookie_en();
         }
     }
 }
示例#6
0
 /**
  * Displays the login page
  */
 public function actionLogin()
 {
     Yii::import('application.vendors.CAS.*');
     include_once 'CAS/Autoload.php';
     spl_autoload_unregister(array('YiiBase', 'autoload'));
     spl_autoload_register(array('YiiBase', 'autoload'));
     include_once 'CAS.php';
     phpCAS::setDebug();
     phpCAS::client(CAS_VERSION_2_0, 'sso.ui.ac.id', 443, 'cas');
     phpCAS::setNoCasServerValidation();
     phpCAS::forceAuthentication();
     phpCAS::checkAuthentication();
     $username = phpCAS::getUser();
     $identity = new UserIdentity($username);
     if ($identity->authenticate()) {
         Yii::app()->user->login($identity);
     }
     $this->redirect(array('home/index'));
 }
示例#7
0
 /**
  * authentication choice (CAS or other)
  * redirection to the CAS form or to login/index.php
  * for other authentication
  */
 function loginpage_hook()
 {
     global $frm;
     global $CFG;
     global $SESSION;
     $site = get_site();
     $CASform = get_string("CASform", "auth");
     $username = optional_param("username");
     if (!empty($username)) {
         if (strstr($SESSION->wantsurl, 'ticket') || strstr($SESSION->wantsurl, 'NOCAS')) {
             unset($SESSION->wantsurl);
         }
         return;
     }
     // Test si cas activ� et param�tres non remplis
     if (empty($this->config->hostname)) {
         return;
     }
     // Connection to CAS server
     $this->connectCAS();
     // Gestion de la connection CAS si acc�s direct d'un ent ou autre
     if (phpCAS::checkAuthentication()) {
         $frm->username = phpCAS::getUser();
         //		if (phpCAS::getUser()=='esup9992')
         //			$frm->username='******';
         $frm->password = "******";
         return;
     }
     if ($_GET["loginguest"] == true) {
         $frm->username = "******";
         $frm->password = "******";
         return;
     }
     if ($this->config->multiauth) {
         $authCAS = optional_param("authCAS");
         if ($authCAS == "NOCAS") {
             return;
         }
         // choice authentication form for multi-authentication
         // test pgtIou parameter for proxy mode (https connection
         // in background from CAS server to the php server)
         if ($authCAS != "CAS" && !isset($_GET["pgtIou"])) {
             $navlinks = array();
             $navlinks[] = array('name' => $CASform, 'link' => null, 'type' => 'misc');
             $navigation = build_navigation($navlinks);
             print_header("{$site->fullname}: {$CASform}", $site->fullname, $navigation);
             include $CFG->dirroot . "/auth/cas/cas_form.html";
             print_footer();
             exit;
         }
     }
     // CAS authentication
     if (!phpCAS::isAuthenticated()) {
         phpCAS::forceAuthentication();
     }
 }
function send_to_cas($config)
{
    require_once dirname(__DIR__) . '/vendor/autoload.php';
    try {
        // get module configuration
        $cas_version = $config->cas_version ? $config->cas_version : CAS_VERSION_2_0;
        // phpCAS::setDebug();
        phpCAS::client($cas_version, $config->cashostname, (int) $config->casport, $config->casbaseuri, false);
        // check authentication; returns true/false
        $result = phpCAS::checkAuthentication();
        if ($result) {
            // grab username
            $NetUsername = phpCAS::getUser();
            return $NetUsername;
        } else {
            return false;
        }
    } catch (Exception $e) {
        error_log("CAS ERROR: " . $e->getMessage());
        register_error($e->getMessage());
        return false;
    }
}
function RWSPCReqs()
{
    global $RWSESL3;
    global $RWSCRURL;
    $r_rwc = RWSGSOpt("rwscas", PARAM_ALPHANUM);
    if ($r_rwc === false || strlen($r_rwc) == 0) {
        return;
    }
    if ($r_rwc != "1" && $r_rwc != "2" && $r_rwc != "3") {
        return;
    }
    $r_ver = RWSGSOpt("version", PARAM_ALPHANUMEXT);
    if ($r_ver === false || strlen($r_ver) == 0) {
        return;
    }
    $r_rwu = RWSGSOpt("rwsuser", PARAM_RAW);
    if ($r_rwu === false || strlen($r_rwu) == 0) {
        unset($r_rwu);
    }
    $r_rwp = RWSGSOpt("rwspass", PARAM_RAW);
    if ($r_rwp === false || strlen($r_rwp) == 0) {
        unset($r_rwp);
    }
    $r_tkt = RWSGSOpt("ticket", PARAM_RAW);
    if ($r_tkt === false || strlen($r_tkt) == 0) {
        unset($r_tkt);
    }
    $r_pid = RWSGSOpt("pgtId", PARAM_RAW);
    if ($r_pid === false || strlen($r_pid) == 0) {
        unset($r_pid);
    }
    $r_piou = RWSGSOpt("pgtIou", PARAM_RAW);
    if ($r_piou === false || strlen($r_piou) == 0) {
        unset($r_piou);
    }
    $r_aus = get_enabled_auth_plugins();
    foreach ($r_aus as $r_aun) {
        $r_aup = get_auth_plugin($r_aun);
        if (strcasecmp($r_aup->authtype, RWSCAS) == 0) {
            $r_csp = $r_aup;
            break;
        }
    }
    if (!isset($r_csp)) {
        return;
    }
    if (empty($r_csp->config->hostname)) {
        return;
    }
    list($r_v1, $r_v2, $r_v3) = explode(".", phpCAS::getVersion());
    $r_csp->connectCAS();
    if ($r_rwc == "1") {
        if (isset($r_tkt)) {
            RWSRHXml();
            echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n";
            echo "<rwscas>\r\n";
            echo "\t<st>";
            echo utf8_encode(htmlspecialchars(trim($r_tkt)));
            echo "\t</st>\r\n";
            echo "</rwscas>\r\n";
            exit;
        } else {
            if ($_SERVER['REQUEST_METHOD'] == "GET") {
                $r_ok = phpCAS::checkAuthentication();
                if (!isset($r_rwu)) {
                    $r_rwu = phpCAS::getUser();
                }
                if (!isset($r_rwp)) {
                    $r_rwp = "passwdCas";
                }
                RWSLIMUser($r_rwu, $r_rwp, $r_ok);
            } else {
                if ($_SERVER['REQUEST_METHOD'] == "POST") {
                    $r_psd = urldecode(file_get_contents("php://input"));
                    if (stripos($r_psd, "<samlp:LogoutRequest ") !== false) {
                        RWSAOLog();
                    }
                }
            }
        }
    } else {
        if ($r_rwc == "2") {
            if (isset($r_pid) && isset($r_piou)) {
                if ($r_csp->config->proxycas) {
                    phpCAS::checkAuthentication();
                }
            } else {
                if ($_SERVER['REQUEST_METHOD'] == "POST") {
                    $r_psd = urldecode(file_get_contents("php://input"));
                    if (stripos($r_psd, "<samlp:LogoutRequest ") !== false) {
                        RWSAOLog();
                    }
                }
            }
        } else {
            if ($r_rwc == "3") {
                if (isset($r_tkt)) {
                    if (strlen($RWSCRURL) > 0) {
                        $r_svu = $RWSCRURL;
                    } else {
                        $r_svu = RWSGSUrl(false, false);
                    }
                    $r_svu .= "?rwscas=1";
                    if (isset($r_ver)) {
                        $r_svu .= "&version=";
                        $r_svu .= urlencode($r_ver);
                    }
                    if (isset($r_rwu)) {
                        $r_svu .= "&rwsuser="******"&rwspass="******"?rwscas=2";
                        if (isset($r_ver)) {
                            $r_cbu .= "&version=";
                            $r_cbu .= urlencode($r_ver);
                        }
                        if (isset($r_rwu)) {
                            $r_cbu .= "&rwsuser="******"&rwspass="******"2008");
}
示例#10
0
文件: index.php 项目: rhertzog/lcs
    }
    // Render
    $claroline->display->body->setContent($template->render());
    if (!(isset($_REQUEST['logout']) && isset($_SESSION['isVirtualUser']))) {
        echo $claroline->display->render();
    }
} else {
    require_once get_path('clarolineRepositorySys') . '/desktop/index.php';
}
// Logout request : delete session data
if (isset($_REQUEST['logout'])) {
    if (isset($_SESSION['isVirtualUser'])) {
        unset($_SESSION['isVirtualUser']);
        claro_redirect(get_conf('rootWeb') . 'claroline/admin/admin_users.php');
        exit;
    }
    // notify that a user has just loggued out
    if (isset($logout_uid)) {
        $eventNotifier->notifyEvent('user_logout', array('uid' => $logout_uid));
    }
    /* needed to be able to :
       - log with claroline when 'magic login' has previously been clicked
       - notify logout event
       (logout from CAS has been commented in casProcess.inc.php)*/
    if (get_conf('claro_CasEnabled', false) && (get_conf('claro_CasGlobalLogout') && !phpCAS::checkAuthentication())) {
        phpCAS::logout((isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . get_conf('urlAppend') . '/index.php');
    }
    session_destroy();
}
// Hide breadcrumbs and view mode on platform home page
// $claroline->display->banner->hideBreadcrumbLine();
示例#11
0
 /**
  * Authenticates the user with CAS and fulfills setting changes (login/out and gender change).
  * $force: whether or not to require login
  * $controller: required to access the model and check what page is being visited
  */
 private function authenticate($force, $controller)
 {
     // Load the settings from the central config file
     require_once __DIR__ . '/../config/cas-config.php';
     // Load the CAS lib
     require_once $phpcas_path . '/CAS.php';
     // Enable debugging
     phpCAS::setDebug();
     // Initialize phpCAS
     phpCAS::client(CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context);
     // Set the CA certificate that is the issuer of the cert on the CAS server
     phpCAS::setCasServerCACert($cas_server_ca_cert_path);
     // log in or out if desired
     if (isset($_REQUEST['login'])) {
         phpCAS::forceAuthentication();
     }
     if (isset($_REQUEST['logout'])) {
         if (!isset($_SESSION)) {
             if (!isset($_SESSION)) {
                 session_start();
             }
         }
         session_destroy();
         phpCAS::logout(array('service' => URL, 'url' => URL));
     }
     if ($force) {
         phpCAS::forceAuthentication();
     } else {
         phpCAS::checkAuthentication();
     }
     // Raise an exception if the user has insufficient privileges for an admin page.
     if (in_array(strtolower(get_class($controller)), $this->admin_controllers) && (!Helper::isLoggedIn() || !$controller->model->userIsAdmin(phpCAS::getUser()))) {
         // Sorry about using runtime, but I don't really want to subclass anything :/
         throw new RuntimeException("Must log in as admin.");
     }
     if (Helper::isLoggedIn()) {
         if (isset($_REQUEST['male'])) {
             $gender = 'male';
         } elseif (isset($_REQUEST['female'])) {
             $gender = 'female';
         } elseif (isset($_REQUEST['all'])) {
             $gender = 'both';
         }
         if (isset($gender)) {
             $controller->model->setGender($gender, phpCAS::getUser());
         }
     }
 }
示例#12
0
<?php

require_once "./cas/phpCAS-master/CAS.php";
require_once "config.example.php";
phpCAS::client(CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context);
phpCAS::setNoCasServerValidation();
if (isset($_REQUEST['logout'])) {
    $_SESSION['cas'] = "yes";
    phpCAS::logoutWithRedirectService("https://osr-etudiant.unistra.fr/~r.henry/aCalendar/");
}
if (phpCAS::checkAuthentication()) {
    $_SESSION['user'] = phpCas::getUser();
    $_SESSION['cas'] = "yes";
    header('Location: ../index.php');
} else {
    phpCAS::forceAuthentication();
}
//echo phpCAS::logoutWithRedirectService('inscription.php');
//
?>
<!--<!<?php 
//if (isset($erreur)) echo '<br /><br />',$erreur;
//if(isset($_POST['connexion']) && $_POST['connexion'] == 'Connexion'){
//if((isset($_POST['login']) && isset($_POST['pass'])) && (!empty($_POST['login']) && !empty($_POST['pass'])))
//{
//$base = new PDO('mysql:host=localhost;dbname=test', 'root', '') ;
//or die("Erreur".mysql_error($base));
//mysqli_select_db ('test', $base);
//$sql = 'select count(*) from membre where login="******" and
//pass_md5="'. $base->quote($_POST['pass']).'"';
//$requete= $base->query($sql) or die('Erreur sql !'.$sql.mysql_error());
示例#13
0
 /**
  * Check login status of current user with regards to Purdue CAS
  *
  * @return  array  $status
  */
 public function status()
 {
     $status = array();
     if (Config::Get('debug')) {
         $debug_location = $this->params->get('debug_location', '/var/log/apache2/php/phpCAS.log');
         phpCAS::setDebug($debug_location);
     }
     $this->initialize();
     if (phpCAS::checkAuthentication()) {
         $status['username'] = phpCAS::getUser();
     }
     return $status;
 }
示例#14
0
 /**
  * Authentication choice (CAS or other)
  * Redirection to the CAS form or to login/index.php
  * for other authentication
  */
 function loginpage_hook()
 {
     global $frm;
     global $CFG;
     global $SESSION, $OUTPUT, $PAGE;
     $site = get_site();
     $CASform = get_string('CASform', 'auth_cas');
     $username = optional_param('username', '', PARAM_RAW);
     $courseid = optional_param('courseid', 0, PARAM_INT);
     if (!empty($username)) {
         if (isset($SESSION->wantsurl) && (strstr($SESSION->wantsurl, 'ticket') || strstr($SESSION->wantsurl, 'NOCAS'))) {
             unset($SESSION->wantsurl);
         }
         return;
     }
     // Return if CAS enabled and settings not specified yet
     if (empty($this->config->hostname)) {
         return;
     }
     // If the multi-authentication setting is used, check for the param before connecting to CAS.
     if ($this->config->multiauth) {
         // If there is an authentication error, stay on the default authentication page.
         if (!empty($SESSION->loginerrormsg)) {
             return;
         }
         $authCAS = optional_param('authCAS', '', PARAM_RAW);
         if ($authCAS == 'NOCAS') {
             return;
         }
         // Show authentication form for multi-authentication.
         // Test pgtIou parameter for proxy mode (https connection in background from CAS server to the php server).
         if ($authCAS != 'CAS' && !isset($_GET['pgtIou'])) {
             $PAGE->set_url('/login/index.php');
             $PAGE->navbar->add($CASform);
             $PAGE->set_title("{$site->fullname}: {$CASform}");
             $PAGE->set_heading($site->fullname);
             echo $OUTPUT->header();
             include $CFG->dirroot . '/auth/cas/cas_form.html';
             echo $OUTPUT->footer();
             exit;
         }
     }
     // Connection to CAS server
     $this->connectCAS();
     if (phpCAS::checkAuthentication()) {
         $frm = new stdClass();
         $frm->username = phpCAS::getUser();
         $frm->password = '******';
         // Redirect to a course if multi-auth is activated, authCAS is set to CAS and the courseid is specified.
         if ($this->config->multiauth && !empty($courseid)) {
             redirect(new moodle_url('/course/view.php', array('id' => $courseid)));
         }
         return;
     }
     if (isset($_GET['loginguest']) && $_GET['loginguest'] == true) {
         $frm = new stdClass();
         $frm->username = '******';
         $frm->password = '******';
         return;
     }
     // Force CAS authentication (if needed).
     if (!phpCAS::isAuthenticated()) {
         phpCAS::setLang($this->config->language);
         phpCAS::forceAuthentication();
     }
 }
示例#15
0
	function validate_user_cas(&$user, $checkOnly = false)
	{
		global $tikilib, $prefs, $base_url;

		// just make sure we're supposed to be here
		if (!$this->_init_cas_client()) {
			return false;
		}

		// Redirect to this URL after authentication
		if ( !empty($prefs['cas_extra_param']) && basename($_SERVER['SCRIPT_NAME']) == 'tiki-login.php' ) {
			phpCAS::setFixedServiceURL($base_url . 'tiki-login.php?cas=y&' . $prefs['cas_extra_param']);
		}

		// check CAS authentication
		phpCAS::setNoCasServerValidation();
		if ( $checkOnly ) {
			unset($_SESSION['phpCAS']['auth_checked']);
			$auth = phpCAS::checkAuthentication();
		} else {
			$auth = phpCAS::forceAuthentication();
		}
		$_SESSION['cas_validation_time'] = $tikilib->now;

		// at this step, the user has been authenticated by the CAS server
		// and the user's login name can be read with phpCAS::getUser().
		if ( $auth && ($user = strtolower(phpCAS::getUser())) ) {
			return USER_VALID;
		} else {
			$user = null;
			return PASSWORD_INCORRECT;
		}

	}
示例#16
0
 /**
  * Zend_Auth Authentication
  *
  * @param return boolean
  */
 public function authenticate()
 {
     if (phpCAS::checkAuthentication()) {
         $user = phpCAS::getAttributes();
         return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $user);
     }
     return new Zend_Auth_Result(Zend_Auth_Result::FAILURE, null, $this->_errors);
     /*
             if($user = $this->validateTicket($this->getTicket(), $this->getService())) {
                 return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $user);
             } 
             else {
                 return new Zend_Auth_Result(Zend_Auth_Result::FAILURE, null, $this->_errors);
             }*/
 }
示例#17
0
function checkAuthentication_raw($noCache, $haveTicket)
{
    if (isset($_GET["auth_checked"])) {
        $noCookies = !isset($_COOKIE["PHPSESSID"]);
        if ($noCookies) {
            debug_msg("cookie disabled or not accepted");
        }
        $_SESSION['time_before_verifying_CAS_ticket'] = microtime(true);
        $_SESSION['time_before_redirecting_to_CAS'] = getAndUnset($_SESSION, 'time_before_adding_auth_checked');
        if ($noCookies || $noCache) {
            // do not redirect otherwise
            // - if noCookies, it will dead-loop
            // - if noCache, we must not clean url otherwise "cleanup SESSION" will be done after final redirect to clean URL
            phpCAS::setNoClearTicketsFromUrl();
        } else {
            if ($haveTicket) {
                // remove "auth_checked" after CAS before redirecting to final URL
                toggle_auth_checked_in_redirect();
            }
        }
        try {
            $isAuthenticated = phpCAS::isAuthenticated();
        } catch (Exception $e) {
            // ignore
        }
        $wasPreviouslyAuthenticated = false;
    } else {
        // add "auth_checked" in url before redirecting to CAS
        toggle_auth_checked_in_redirect();
        $_SESSION['time_before_adding_auth_checked'] = microtime(true);
        $isAuthenticated = phpCAS::checkAuthentication();
        // NB: if we reach this point, we are either in "wasPreviouslyAuthenticated" case or after final redirect to clean URL
        $noCookies = false;
    }
    return array($isAuthenticated, $noCookies);
}
示例#18
0
 function verificar_logout()
 {
     if ($this->uso_login_basico() && $this->permite_login_toba()) {
         //Si es login toba, no chequear logout de CAS
         return;
     }
     // Se conecta al CAS
     $this->instanciar_cliente_cas();
     return phpCAS::checkAuthentication();
 }
示例#19
0
文件: main.php 项目: Galinijay/PAS
	**/
if ($currentPageData = getCurrentPageData()) {
    if ($currentPageData['fullRight'][$_SESSION['rang']] == 0) {
        // On invite l'utilisateur à se connecter au CAS
        phpCAS::client(CAS_VERSION_2_0, CAS_SERVER_URI, (int) constant('CAS_SERVER_PORT'), '');
        phpCAS::setServerServiceValidateURL(CAS_SERVER_VALIDATEURI);
        if (is_file(CAS_SERVER_CERTIFICATPATH)) {
            phpCAS::setCasServerCACert(CAS_SERVER_CERTIFICATPATH);
        } else {
            phpCAS::setNoCasServerValidation();
        }
        phpCAS::forceAuthentication();
        if (phpCAS::getUser()) {
            //Si l'utilisateur s'est connecté
            // Récupération des données serveur
            $test = phpCAS::checkAuthentication();
            // Récupération des données utilisateur
            $sql = 'SELECT * FROM user WHERE nbEtudiant = :nbEtu LIMIT 1';
            $res = $db->prepare($sql);
            $res->execute(array('nbEtu' => phpCAS::getUser()));
            if ($res_f = $res->fetch()) {
                $_SESSION['id'] = $res_f['id'];
                $_SESSION['nom'] = $res_f['nom'];
                $_SESSION['prenom'] = $res_f['prenom'];
                $_SESSION['rang'] = $res_f['rang'];
                if (isset($res_f['promotion'])) {
                    $_SESSION['promotion'] = $res_f['promotion'];
                }
            } else {
                $errorCode = serialize(array(32 => true));
                phpCAS::logout(array('service' => ROOT . 'index.php?erreur=' . $errorCode));
示例#20
0
/**
* checks if the user already get a session
* @return the user login if the user already has a session ,false otherwise
**/
function cas_is_authenticated()
{
    global $cas_auth_ver, $cas_auth_server, $cas_auth_port, $cas_auth_uri;
    global $PHPCAS_CLIENT;
    global $logout;
    if (!cas_configured()) {
        return;
    }
    if (!is_object($PHPCAS_CLIENT)) {
        phpCAS::client($cas_auth_ver, $cas_auth_server, $cas_auth_port, $cas_auth_uri);
        phpCAS::setNoCasServerValidation();
    }
    $auth = phpCAS::checkAuthentication();
    if ($auth) {
        $login = trim(phpCAS::getUser());
        /*
          Get user  attributes. Here are the attributes for crdp platform
          sn => name
          ENTPersonMailInterne => mail
          ENTPersonAlias => login
          ENTPersonProfils => profil
          givenName => first name
        */
        /*$user=phpCAS::getAttributes();
        		$firstName = trim($user['givenName']);
        		$lastName = trim($user['sn']);
        		$login = trim($user['ENTPersonAlias']);
        		$profil = trim($user['ENTPersonProfils']);
        		$email = trim($user['ENTPersonMailInterne']);
        		$satus=5;
        		switch ($profil){
        			case 'admin_etab':
        				$status=3; //Session admin
        				break;
        			case 'admin_sie':
        				$status=3; //Session admin
        				break;
        			case 'National_3':
        				$status=1; // Teacher
        				break;
        			case 'National_1':
        				$status=5; // Student
        				break;
        			default:
        				$status=5; // Student
        		}*/
        if (!$logout) {
            // get user info from username
            $tab_user_info = UserManager::get_user_info($login);
            // user found in the chamilo database
            if (is_array($tab_user_info)) {
                // if option is on we update user automatically from ldap server
                if (api_get_setting("update_user_info_cas_with_ldap") == "true") {
                    $ldapuser = extldap_authenticate($login, 'nopass', true);
                    if ($ldap_user !== false) {
                        $chamilo_user = extldap_get_chamilo_user($ldapuser);
                        $chamilo_user['user_id'] = $tab_user_info['user_id'];
                        $chamilo_user['status'] = $tab_user_info['status'];
                        UserManager::update_user($chamilo_user["user_id"], $chamilo_user["firstname"], $chamilo_user["lastname"], $login, null, null, $chamilo_user["email"], $chamilo_user["status"], '', '', '', '', 1, null, 0, null, '');
                    }
                }
                return $login;
            } else {
                // if option is on we can ADD user automatically from ldap server or by modify own profil
                $user_added = false;
                switch (api_get_setting("cas_add_user_activate")) {
                    case PLATFORM_AUTH_SOURCE:
                        // user will have to modify firstname, lastname, email in chamilo profil edit
                        $userdata = get_lang("EditInProfil");
                        UserManager::create_user($userdata, $userdata, '5', $userdata, $login, 'casplaceholder', '', '', '', '', CAS_AUTH_SOURCE);
                        $user_added = $login;
                        break;
                    case LDAP_AUTH_SOURCE:
                        // user info are read from ldap connexion
                        // get user info from ldap server
                        // user has already been authenticated by CAS
                        // If user not found in LDAP, user not created
                        $ldapuser = extldap_authenticate($login, 'nopass', true);
                        if ($ldap_user !== false) {
                            $chamilo_user = extldap_get_chamilo_user($ldapuser);
                            $chamilo_user['username'] = $login;
                            $chamilo_user['auth_source'] = CAS_AUTH_SOURCE;
                            $chamilo_uid = external_add_user($chamilo_user);
                            $user_added = $login;
                        }
                        break;
                    default:
                        break;
                }
                return $user_added;
            }
        }
        //		//If the user is in the dokeos database and we are ,not in a logout request, we upgrade his infomration by ldap
        //		if (! $logout){
        //			$user_table = Database::get_main_table(TABLE_MAIN_USER);
        //			$sql = "SELECT user_id, username, password, auth_source, active, expiration_date ".
        //				"FROM $user_table ".
        //				"WHERE username = '******' ";
        //
        //			$result = Database::query($sql,__FILE__,__LINE__);
        //			if(mysql_num_rows($result) == 0) {
        //				require_once(api_get_path(SYS_PATH).'main/inc/lib/usermanager.lib.php');
        //				$rnumber=rand(0,256000);
        //				UserManager::create_user($firstName, $lastName, $status, $email, $login, md5('casplaceholder'.$rnumber), $official_code='',$language='',$phone='',$picture_uri='',$auth_source = PLATFORM_AUTH_SOURCE);
        //			}
        //			else {
        //				$user = mysql_fetch_assoc($result);
        //				$user_id = intval($user['user_id']);
        //				//echo "deb : $status";
        //				UserManager::update_user ($user_id, $firstname, $lastname, $login, null, null, $email, $status, '', '', '', '', 1, null, 0, null,'') ;
        //
        //			}
        //		}
        return $login;
    } else {
        return false;
    }
}
示例#21
0
文件: hooks.php 项目: jas01/user_cas
 public static function post_login($parameters)
 {
     $uid = $parameters['uid'];
     $wuid = $uid;
     $casBackend = new OC_USER_CAS();
     $userDB = new OC_User_Database();
     /*
      * Récupération des données du fichier config général /config/config.php
      */
     $serveur_Search = OCP\Config::getSystemValue('serveur_Search', 'error');
     $port = OCP\Config::getSystemValue('port', 'error');
     $racineAMU = OCP\Config::getSystemValue('racineAMU', 'error');
     $racineAMUGRP = OCP\Config::getSystemValue('racineAMUGRP', 'error');
     $AMU_nuage_dn = OCP\Config::getSystemValue('AMU_nuage_dn', 'error');
     $AMU_nuage_pw = OCP\Config::getSystemValue('AMU_nuage_pw', 'error');
     $PQuota = OCP\Config::getSystemValue('PQuota', 'unManaged');
     $EQuota = OCP\Config::getSystemValue('EQuota', 'unManaged');
     $LDAP = new LDAP_Infos($serveur_Search, $AMU_nuage_dn, $AMU_nuage_pw, $racineAMUGRP, $racineAMUGRP);
     $restrictGrp = array("cn", "member");
     /*
      * Récupération tableau Groupes
      * Si le tableau 'groupMapping' est vide pas de contrôle sur les groupes
      */
     $AccesCloud = 0;
     OCP\Util::writeLog('user_cas', "Authentification (Mapping groups=" . $casBackend->groupMapping . ")", OCP\Util::DEBUG);
     if ($casBackend->groupMapping) {
         $wTabGrp = str_replace(array('<br>', '<br />', "\n", "\r"), array('@', '', '@', ''), $casBackend->groupMapping);
         $tabGRP = explode("@", $wTabGrp);
         $i = 0;
         $mesGroupes = array();
         foreach ($tabGRP as $key => $value) {
             $ListeMembre = $LDAP->getMembersOfGroup($value, $restrictGrp);
             if (in_array($uid, $ListeMembre)) {
                 $AccesCloudAMU = 1;
             }
         }
     } else {
         $AccesCloud = 1;
     }
     /*
      * Si pas d'acces, alors déconnexion
      */
     if ($AccesCloud == 0) {
         /*
          * On vérifie si le compte utilisé est un compte local
          */
         if (!$userDB->userExists($uid)) {
             OCP\Util::writeLog('user_cas', "Aucun droit d'accès pour l'utilisateur " . $uid, OCP\Util::ERROR);
             \OC_User::logout();
         } else {
             OCP\Util::writeLog('user_cas', "Authentification locale pour l'utilisateur " . $uid, OCP\Util::DEBUG);
             OC::$REQUESTEDAPP = '';
             OC_Util::redirectToDefaultPage();
             exit(0);
         }
     }
     /**
      * Récupère les groupes liés à l'utilisateur avec la racine définie dans le formulaire 'cas_group_root'
      * Si 'cas_group_root' n'est pas renseingé => pas de récupération de groupes
      */
     $mesGroupes = array();
     OCP\Util::writeLog('user_cas', "Authentification (Racine Groupes LDAP=" . $casBackend->groupRoot . ")", OCP\Util::DEBUG);
     if ($casBackend->groupRoot) {
         $i = 0;
         $ListeGRP = $LDAP->getMemberOf($uid);
         $a = sizeof($ListeGRP);
         OCP\Util::writeLog('user_cas', "Taille=" . $a . " UID=" . $uid, OCP\Util::ERROR);
         OCP\Util::writeLog('user_cas', "Racine Groupe=" . $casBackend->groupRoot, OCP\Util::ERROR);
         foreach ($ListeGRP as $key => $value) {
             if (strstr($value, $casBackend->groupRoot)) {
                 $mesGroupes[$i] = strtoupper(str_replace(':', '_', substr($value, 8)));
                 OCP\Util::writeLog('user_cas', "Groupe[{$i}]=" . $mesGroupes[$i], OCP\Util::ERROR);
                 $i++;
             }
         }
     }
     if (phpCAS::checkAuthentication()) {
         //$attributes = phpCAS::getAttributes();
         $cas_uid = phpCAS::getUser();
         if ($cas_uid == $uid) {
             /*
              * Récupération des information utilisateur (LDAP)
              */
             $tabLdapUser = $LDAP->getUserInfo($uid);
             if ($tabLdapUser) {
                 $DisplayName = $tabLdapUser['displayName'];
             }
             if (!$userDB->userExists($uid)) {
                 if (preg_match('/[^a-zA-Z0-9 _\\.@\\-]/', $uid)) {
                     OCP\Util::writeLog('cas', 'Utilisateur  invalide "' . $uid . '", caracteres autorises "a-zA-Z0-9" and "_.@-" ', OCP\Util::DEBUG);
                     return false;
                 } else {
                     /*
                      * Dans le cas d'une création
                      */
                     $random_password = \OC_Util::generateRandomBytes(20);
                     $userDB->createUser($uid, $tabLdapUser['userpassword']);
                     $userDB->setDisplayName($uid, $DisplayName);
                     /*
                      * Mise à jour du quota si gestion dans fichier de configuration
                      */
                     if ($EQuota != "unManaged" && $tabLdapUser['eduPersonPrimaryAffiliation'] == 'student') {
                         update_quota($uid, $EQuota);
                     }
                     if ($PQuota != "unManaged" && $tabLdapUser['eduPersonPrimaryAffiliation'] != 'student') {
                         update_quota($uid, $PQuota);
                     }
                 }
             }
             /*
              * Mise à jour des groupes associés
              */
             if (sizeof($mesGroupes) > 0) {
                 $cas_groups = $mesGroupes;
                 update_groups($uid, $cas_groups, $casBackend->protectedGroups, true);
             }
             /*
              * Mise à jour du mail
              */
             update_mail($uid, $tabLdapUser['Mail']);
             /*
              * Mise à jour du display name
              */
             $userDB->setDisplayName($uid, $DisplayName);
             return true;
         }
     }
     return false;
 }
示例#22
0
function xcas_auth($groupid, $ruleid)
{
    Debuglogs("Rule:{$ruleid} Groupid:{$groupid} Testing source groups...", __FUNCTION__, __LINE__);
    if (!isMustAuth($ruleid)) {
        Debuglogs("Rule:{$ruleid} Groupid:{$groupid} From groups not match rule.", __FUNCTION__, __LINE__);
        return;
    }
    Debuglogs("Rule:{$ruleid} Groupid:{$groupid} From groups match rule.", __FUNCTION__, __LINE__);
    if (isset($_SESSION["AUTH_GROUP_DATA"][$groupid])) {
        if ($_SESSION["AUTH_GROUP_DATA"][$groupid]["params"] == null) {
            unset($_SESSION["AUTH_GROUP_DATA"][$groupid]);
        }
    }
    if (!isset($_SESSION["AUTH_GROUP_DATA"][$groupid])) {
        if (!isset($GLOBALS["Q"])) {
            $GLOBALS["Q"] = new mysql_squid_builder();
        }
        Debuglogs("Rule:{$ruleid} Groupid:{$groupid} Run MySQL query", __FUNCTION__, __LINE__);
        $ligne = mysql_fetch_array($GLOBALS["Q"]->QUERY_SQL("SELECT groupname,group_type,params FROM authenticator_auth WHERE ID='{$groupid}'"));
        if (!$GLOBALS["Q"]->ok) {
            Debuglogs("Rule:{$_GET["ruleid"]} Groupid:{$groupid} {$GLOBALS["Q"]->mysql_error}", __FUNCTION__, __LINE__);
        }
        $_SESSION["AUTH_GROUP_DATA"][$groupid]["groupname"] = $ligne["groupname"];
        $_SESSION["AUTH_GROUP_DATA"][$groupid]["group_type"] = $ligne["group_type"];
        $_SESSION["AUTH_GROUP_DATA"][$groupid]["params"] = unserialize(base64_decode($ligne["params"]));
    }
    $groupname = $_SESSION["AUTH_GROUP_DATA"][$groupid]["groupname"];
    $group_type = $_SESSION["AUTH_GROUP_DATA"][$groupid]["group_type"];
    $params = $_SESSION["AUTH_GROUP_DATA"][$groupid]["params"];
    include_once dirname(__FILE__) . "/ressources/externals/jasigcas/CAS.php";
    Debuglogs("Rule:{$ruleid} Groupid:{$groupid} checking group:{$groupname} type:{$group_type}", __FUNCTION__, __LINE__);
    if (!preg_match("#\\?ticket=(.+)#", $_GET["uri"], $re)) {
        Debuglogs("Not ticket found in `{$_GET["uri"]}`", __FUNCTION__, __LINE__);
        return false;
    }
    //$_SESSION["USER"]=$user;
    //$_SESSION["CASTIME"]=time();
    if (preg_match("#\\?ticket=(.+)#", $_GET["uri"], $re)) {
        $ticket = $re[1];
        Debuglogs("{$_GET["uri"]} -> {$ticket}", __FUNCTION__, __LINE__);
        $uriToSend = "https://auth.u-cergy.fr/serviceValidate?ticket={$ticket}&service=http://{$_GET["servername"]}";
        Debuglogs("{$uriToSend}", __FUNCTION__, __LINE__);
        @unlink("/tmp/toto.txt");
        exec("wget \"{$uriToSend}\" -O /tmp/toto.txt");
        $tr = explode("\n", @file_get_contents("/tmp/toto.txt"));
        while (list($index, $alias) = each($tr)) {
            Debuglogs("{$alias}", __FUNCTION__, __LINE__);
        }
    } else {
        Debuglogs("{$_GET["uri"]} no pregmatch", __FUNCTION__, __LINE__);
    }
    if ($GLOBALS["DEBUG"]) {
        Debuglogs("Rule:{$ruleid} Groupid:{$groupid} checking group:{$groupname} set to debug", __FUNCTION__, __LINE__);
        phpCAS::setDebug("/var/log/apache2/cas.debug.log");
    }
    phpCAS::setDebug("/var/log/apache2/cas.debug.log");
    Debuglogs("for debug purpose cmdline should be \"" . __FILE__ . " --cas {$groupid} {$ruleid}\"", __FUNCTION__, __LINE__);
    $cas_host = $params["CAS_HOST"];
    $cas_port = intval($params["CAS_PORT"]);
    $cas_context = $params["CAS_CONTEXT"];
    $certificate = $params["CAS_CERT"];
    Debuglogs("Using certificate: {$certificate} ", __FUNCTION__, __LINE__);
    Debuglogs("Rule:{$ruleid} Groupid:{$groupid} checking group:{$groupname} Initialize phpCAS host:{$cas_host} Port:\"{$cas_port}\" context={$cas_context}", __FUNCTION__, __LINE__);
    phpCAS::client(CAS_VERSION_2_0, $cas_host, intval($cas_port), $cas_context);
    //phpCAS::proxy(CAS_VERSION_2_0, $cas_host, intval($cas_port), $cas_context);
    // 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!
    if (is_file($certificate)) {
        //Debuglogs("Using certificate: $certificate ",__FUNCTION__,__LINE__);
        //phpCAS::setCasServerCACert($certificate);
    } else {
        Debuglogs(" {$certificate} no such file", __FUNCTION__, __LINE__);
    }
    unset($_SESSION["AUTH_GROUP_DATA"]);
    Debuglogs("Rule:{$ruleid} Groupid:{$groupid} checking group:{$groupname} Initialize phpCAS setNoCasServerValidation()", __FUNCTION__, __LINE__);
    phpCAS::setNoCasServerValidation();
    phpCAS::setFixedServiceURL("http://biblioweb.u-cergy.org");
    //https://auth.u-cergy.fr/is/cas/serviceValidate?ticket=ST-956-Lyg0BdLkgdrBO9W17bXS&service=http://localhost/bling
    //phpCAS::forceAuthentication();
    if (!phpCAS::checkAuthentication()) {
        Debuglogs("Rule:{$ruleid} Groupid:{$groupid} checking group:{$groupname} Initialize phpCAS, not authenticated", __FUNCTION__, __LINE__);
        return false;
    }
    // force CAS authentication
    //phpCAS::forceAuthentication();
    return true;
}
示例#23
0
文件: auth.php 项目: verbazend/AWFA
 /**
  * Authentication choice (CAS or other)
  * Redirection to the CAS form or to login/index.php
  * for other authentication
  */
 function loginpage_hook()
 {
     global $frm;
     global $CFG;
     global $SESSION, $OUTPUT, $PAGE;
     $site = get_site();
     $CASform = get_string('CASform', 'auth_cas');
     $username = optional_param('username', '', PARAM_RAW);
     if (!empty($username)) {
         if (isset($SESSION->wantsurl) && (strstr($SESSION->wantsurl, 'ticket') || strstr($SESSION->wantsurl, 'NOCAS'))) {
             unset($SESSION->wantsurl);
         }
         return;
     }
     // Return if CAS enabled and settings not specified yet
     if (empty($this->config->hostname)) {
         return;
     }
     // Connection to CAS server
     $this->connectCAS();
     if (phpCAS::checkAuthentication()) {
         $frm = new stdClass();
         $frm->username = phpCAS::getUser();
         $frm->password = '******';
         return;
     }
     if (isset($_GET['loginguest']) && $_GET['loginguest'] == true) {
         $frm = new stdClass();
         $frm->username = '******';
         $frm->password = '******';
         return;
     }
     if ($this->config->multiauth) {
         $authCAS = optional_param('authCAS', '', PARAM_RAW);
         if ($authCAS == 'NOCAS') {
             return;
         }
         // Show authentication form for multi-authentication
         // test pgtIou parameter for proxy mode (https connection
         // in background from CAS server to the php server)
         if ($authCAS != 'CAS' && !isset($_GET['pgtIou'])) {
             $PAGE->set_url('/login/index.php');
             $PAGE->navbar->add($CASform);
             $PAGE->set_title("{$site->fullname}: {$CASform}");
             $PAGE->set_heading($site->fullname);
             echo $OUTPUT->header();
             include $CFG->dirroot . '/auth/cas/cas_form.html';
             echo $OUTPUT->footer();
             exit;
         }
     }
     // Force CAS authentication (if needed).
     if (!phpCAS::isAuthenticated()) {
         phpCAS::setLang($this->config->language);
         phpCAS::forceAuthentication();
     }
 }
示例#24
0
function cas_authenticate($auth, $new = false, $cas_host = null, $cas_port = null, $cas_context = null, $cas_cachain = null)
{
    global $langConnectWith, $langNotSSL;
    // SESSION does not exist if user has not been authenticated
    $ret = array();
    if (!$new) {
        $cas = get_auth_settings($auth);
        if ($cas) {
            $cas_host = $cas['cas_host'];
            $cas_port = $cas['cas_port'];
            $cas_context = $cas['cas_context'];
            $cas_cachain = $cas['cas_cachain'];
            $casusermailattr = $cas['casusermailattr'];
            $casuserfirstattr = $cas['casuserfirstattr'];
            $casuserlastattr = $cas['casuserlastattr'];
            $cas_altauth = $cas['cas_altauth'];
        }
    }
    if ($new or $cas) {
        $cas_url = 'https://' . $cas_host;
        $cas_port = intval($cas_port);
        if ($cas_port != '443') {
            $cas_url = $cas_url . ':' . $cas_port;
        }
        $cas_url = $cas_url . $cas_context;
        // The "real" hosts that send SAML logout messages
        // Assumes the cas server is load balanced across multiple hosts
        $cas_real_hosts = array($cas_host);
        // Uncomment to enable debugging
        // phpCAS::setDebug();
        // Initialize phpCAS - keep session in application
        $ret['message'] = "{$langConnectWith} {$cas_url}";
        phpCAS::client(SAML_VERSION_1_1, $cas_host, $cas_port, $cas_context, FALSE);
        // Set the CA certificate that is the issuer of the cert on the CAS server
        if (isset($cas_cachain) && !empty($cas_cachain) && is_readable($cas_cachain)) {
            phpCAS::setCasServerCACert($cas_cachain);
        } else {
            phpCAS::setNoCasServerValidation();
            $ret['error'] = "{$langNotSSL}";
        }
        // Single Sign Out
        //phpCAS::handleLogoutRequests(true, $cas_real_hosts);
        // Force CAS authentication on any page that includes this file
        phpCAS::forceAuthentication();
        //$ret['attrs'] = get_cas_attrs(phpCAS::getAttributes(), $cas);
        if (phpCAS::checkAuthentication()) {
            $ret['attrs'] = phpCAS::getAttributes();
        }
        return $ret;
    } else {
        return null;
    }
}
示例#25
0
 function _setCASGroups()
 {
     if (phpCAS::checkAuthentication()) {
         $attributes = plaincas_pattern_attributes(phpCAS::getAttributes());
         if (!is_array($attributes)) {
             $attributes = array($attributes);
         }
         $patterns = plaincas_group_patterns();
         if (!empty($patterns)) {
             foreach ($patterns as $role => $pattern) {
                 foreach ($attributes as $attribute) {
                     // An invalid pattern will generate a php warning and will not be considered.
                     if (preg_match($pattern, $attribute)) {
                         $this->_addUserGroup($role);
                     }
                 }
             }
         } else {
             foreach ($attributes as $attribute) {
                 // Add all attributes as groups
                 $this->_addUserGroup($attribute);
             }
         }
     }
 }
 function authenticate()
 {
     include_once "./Services/Init/classes/class.ilInitialisation.php";
     $this->init = new ilInitialisation();
     $this->init->requireCommonIncludes();
     //$init->initSettings();
     if (!$this->getClient()) {
         $this->__setMessage('No client given');
         return false;
     }
     if (!$this->getUsername()) {
         $this->__setMessage('No username given');
         return false;
     }
     // Read ilias ini
     if (!$this->__buildDSN()) {
         $this->__setMessage('Error building dsn/Wrong client Id?');
         return false;
     }
     if (!$this->__setSessionSaveHandler()) {
         return false;
     }
     if (!$this->__checkAgreement('cas')) {
         return false;
     }
     if (!$this->__buildAuth()) {
         return false;
     }
     if ($this->soap_check and !$this->__checkSOAPEnabled()) {
         $this->__setMessage('SOAP is not enabled in ILIAS administration for this client');
         $this->__setMessageCode('Server');
         return false;
     }
     // check whether authentication is valid
     //if (!$this->auth->checkCASAuth())
     if (!phpCAS::checkAuthentication()) {
         $this->__setMessage('ilSOAPAuthenticationCAS::authenticate(): No valid CAS authentication.');
         return false;
     }
     $this->auth->forceCASAuth();
     if ($this->getUsername() != $this->auth->getCASUser()) {
         $this->__setMessage('ilSOAPAuthenticationCAS::authenticate(): SOAP CAS user does not match to ticket user.');
         return false;
     }
     include_once './Services/User/classes/class.ilObjUser.php';
     $local_user = ilObjUser::_checkExternalAuthAccount("cas", $this->auth->getCASUser());
     if ($local_user == "") {
         $this->__setMessage('ilSOAPAuthenticationCAS::authenticate(): SOAP CAS user authenticated but not existing in ILIAS user database.');
         return false;
     }
     /*
     		$init->initIliasIniFile();
     		$init->initSettings();
     		$ilias =& new ILIAS();
     		$GLOBALS['ilias'] =& $ilias;*/
     $this->auth->start();
     if (!$this->auth->getAuth()) {
         $this->__getAuthStatus();
         return false;
     }
     $this->setSid(session_id());
     return true;
 }
 /**
  * Populates this class' session array with the following variables
  *   netId
  *   area
  *
  * If the user is not authenticated, this function does nothing
  */
 protected function getUserInfo()
 {
     // If the user is not authenticated, don't try to retrieve netId or area
     if (!$this->authenticated) {
         return;
     }
     // Pull information from CAS or LDAP, whichever way the user is authenticated
     if (isset($_SESSION['ldap'])) {
         $this->user['netId'] = $_SESSION['user'];
     } else {
         if (\phpCAS::checkAuthentication()) {
             $this->user['netId'] = \phpCAS::getUser();
         } else {
             // This should never happen because they would somehow have authenticated set to true
             //   and not be logged in to CAS or LDAP
             $this->user['netId'] = null;
         }
     }
     // In case a problem occurred and netId was not set, don't try to get area
     if ($this->user['netId'] == null) {
         return;
     }
     // Pull area
     $areaAcc = new \TMT\accessor\AreaAccessor();
     $employeeAcc = new \TMT\accessor\Employee();
     $employee = $employeeAcc->get($this->user['netId']);
     if (isset($_COOKIE['area'])) {
         if ($areaAcc->checkAreaRights($this->user['netId'], $_COOKIE['area'])) {
             $this->user['area'] = $_COOKIE['area'];
         } else {
             // The cookie was changed to an area the user does not have rights to
             // So unset the cookie and change to default area
             unset($_COOKIE['area']);
             setcookie("area", "", time() - 3600, '/');
             $this->user['area'] = $employee->area;
         }
     } else {
         // Cookie not set, use default area
         $this->user['area'] = $employee->area;
     }
     $area = $areaAcc->get($this->user['area']);
     $this->user['guid'] = $employee->guid;
     $this->user['areaGuid'] = $area->guid;
 }
示例#28
0
文件: login.php 项目: pmolfese/nidb
function AuthenticateCASUser()
{
    //phpCAS::setDebug("/tmp/phpCAS.log");
    // Enable verbose error messages. Disable in production!
    //phpCAS::setVerbose(true);
    //echo "I'm in the AuthenticateCASUser function<br>";
    if (isset($_SESSION)) {
        //phpCAS::client(CAS_VERSION_2_0, $GLOBALS['cfg']['casserver'], intval($GLOBALS['cfg']['casport']), $GLOBALS['cfg']['cascontext'], false);
        echo "Created the client (session already exists)...<br>";
        phpCAS::setNoCasServerValidation();
        if (phpCAS::checkAuthentication()) {
            $username = phpCAS::getUser();
            //echo "Username [$username]";
            return $username;
        } else {
            phpCAS::forceAuthentication();
        }
    }
    phpCAS::setNoCasServerValidation();
    //echo "Set the no server validation...<br>";
    //actually authenticate
    if (phpCAS::checkAuthentication()) {
        //echo "Already authenticated...<br>";
    } else {
        //echo "NOT already authenticated...<br>";
        phpCAS::forceAuthentication();
        # We'll never get back to this point! because CAS will redirect back to login.php with no POST variables passed in...
        echo "Did the authentication...<br>";
    }
    return '';
}
示例#29
0
//
// import phpCAS lib
include_once 'CAS.php';
phpCAS::setDebug();
// initialize phpCAS
phpCAS::client(CAS_VERSION_2_0, 'sso-cas.univ-rennes1.fr', 443, '');
// no SSL validation for the CAS server
phpCAS::setNoCasServerValidation();
if (isset($_REQUEST['logout'])) {
    phpCAS::logout();
}
if (isset($_REQUEST['login'])) {
    phpCAS::forceAuthentication();
}
// check CAS authentication
$auth = phpCAS::checkAuthentication();
?>
<html>
  <head>
    <title>phpCAS simple client</title>
  </head>
  <body>
<?php 
if ($auth) {
    // for this test, simply print that the authentication was successfull
    ?>
    <h1>Successfull Authentication!</h1>
    <p>the user's login is <b><?php 
    echo phpCAS::getUser();
    ?>
</b>.</p>
 /**
  * checkCAS
  *
  * checks if a CAS Session is established, without forcing authentication
  *
  * @since               version 1.0.1
  * @access              public
  * @return      string/boolean
  */
 static function checkCAS($host = 'my', $dir = 'cas/')
 {
     self::setupCAS($host, $dir);
     // check CAS authentication
     $auth = phpCAS::checkAuthentication();
     if ($auth) {
         return phpCAS::getUser();
     } else {
         return false;
     }
 }