SugarCRM CE 5.2 ile CAS Entegrasyonu

Bu makalede Jasig'in Open source CAS sunucusu ile SugarCRM'i nasıl entegre edeceğimizi anlatacağız.

Öncelikle şunu belirtmemiz gerekiyor bu non-upgrade safe bir yöntem. Olası bir patch veya update işleminde bu değişiklik uçacaktır. Şimdi bize öncelikle PHP CAS gerekiyor. PHP CAS'ı buradan indirebilirsiniz.

  • PHP CAS'ı indirdikten sonra sugarCRM'in kök dizinine CAS adında bir dizin açıp kopyalıyoruz.
  • config.php dosyasına aşağıdaki satırı ekliyoruz
    'authenticationClass' => 'CASAuthenticate'
  • /modules/Users/authentication altındaki AuthenticationController.php dosyası aşağıdaki gibi değiştirilecek:
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/**
 * SugarCRM is a customer relationship management program developed by
 * SugarCRM, Inc. Copyright (C) 2004 - 2009 SugarCRM Inc.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License version 3 as published by the
 * Free Software Foundation with the addition of the following permission added
 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, see http://www.gnu.org/licenses or write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 *
 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU General Public License version 3,
 * these Appropriate Legal Notices must retain the display of the "Powered by
 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
 * technical reasons, the Appropriate Legal Notices must display the words
 * "Powered by SugarCRM".
 */


class AuthenticationController {
	var $loggedIn = false; //if a user has attempted to login
	var $authenticated = false;
	var $loginSuccess = false;// if a user has successfully logged in
	/**
	 * Creates an instance of the authentication controller and loads it
	 *
	 * @param STRING $type - the authentication Controller - default to SugarAuthenticate
	 * @return AuthenticationController -
	 */
	function AuthenticationController($type = 'SugarAuthenticate') {

         if(isset($_SESSION['invalid_CAS'])) $type='SugarAuthenticate';

		if(!file_exists('modules/Users/authentication/'.$type.'/' . $type . '.php'))$type = 'SugarAuthenticate';


		if($type == 'SugarAuthenticate' && !empty($GLOBALS['system_config']->settings['system_ldap_enabled']) && empty($_SESSION['sugar_user'])){
			$type = 'LDAPAuthenticate';
		}
		require_once('modules/Users/authentication/'.$type.'/' . $type . '.php');
		$this->authController = new $type();

	}


	/**
	 * Returns an instance of the authentication controller
	 *
	 * @param STRING $type this is the type of authetnication you want to use default is SugarAuthenticate
	 * @return an instance of the authetnciation controller
	 */
	function &getInstance($type='SugarAuthenticate'){
		static $authcontroller;
		if(empty($authcontroller)){
			$authcontroller = new AuthenticationController($type);
		}
		return $authcontroller;
	}

	/**
	 * This function is called when a user initially tries to login.
	 * It will return true if the user successfully logs in or false otherwise.
	 *
	 * @param STRING $username
	 * @param STRING $password
	 * @param ARRAY $PARAMS
	 * @return boolean
	 */
	function login($username, $password, $PARAMS = array ()) {

		//kbrill bug #13225
		$_SESSION['loginAttempts'] = (isset($_SESSION['loginAttempts']))? $_SESSION['loginAttempts'] + 1: 1;
		unset($GLOBALS['login_error']);


		if($this->loggedIn) return $this->loginSuccess;

		$this->loginSuccess = $this->authController->loginAuthenticate($username, $password, $PARAMS);

		$this->loggedIn = true;

		if($this->loginSuccess){
			//Ensure the user is authorized
			checkAuthUserStatus();

			loginLicense();
			if(!empty($GLOBALS['login_error'])){
				session_unregister('authenticated_user_id');
				$GLOBALS['log']->fatal('FAILED LOGIN: potential hack attempt');
				$this->loginSuccess = false;
				return false;
			}
			$ut = $GLOBALS['current_user']->getPreference('ut');
			if(empty($ut) && $_REQUEST['action'] != 'SaveTimezone') {
				$GLOBALS['module'] = 'Users';
				$GLOBALS['action'] = 'SetTimezone';
				ob_clean();
				header("Location: index.php?module=Users&action=SetTimezone");
				sugar_cleanup(true);
			}
			//call business logic hook
			if(isset($GLOBALS['current_user']))
				$GLOBALS['current_user']->call_custom_logic('after_login');
		}else{
			//kbrill bug #13225
			LogicHook::initialize();
			$GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed');
			$GLOBALS['log']->fatal('FAILED LOGIN:attempts[' .$_SESSION['loginAttempts'] .'] - '. $username);
		}

		return $this->loginSuccess;
	}
	/**
	 * This is called on every page hit.
	 * It returns true if the current session is authenticated or false otherwise
	 * @return booelan
	 */
	function sessionAuthenticate() {

		if(!$this->authenticated){
			$this->authenticated = $this->authController->sessionAuthenticate();
		}
		if($this->authenticated){
			if(!isset($_SESSION['userStats']['pages'])){
			    $_SESSION['userStats']['loginTime'] = time();
			    $_SESSION['userStats']['pages'] = 0;
			}
			$_SESSION['userStats']['lastTime'] = time();
			$_SESSION['userStats']['pages']++;

		}
		return $this->authenticated;
	}

	/**
	 * Called when a user requests to logout. Should invalidate the session and redirect
	 * to the login page.
	 *
	 */
	function logout(){
		$GLOBALS['current_user']->call_custom_logic('before_logout');
		$this->authController->logout();
		LogicHook::initialize();
		$GLOBALS['logic_hook']->call_custom_logic('Users', 'after_logout');
	}


}
?>
  • /modules/Users/CASAuthenticate adında bir dizin açılarak CASAuthenticate.php ve CASAuthenticateUser.php dosyaları bu dizine eklenecek.
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');

require_once('modules/Users/authentication/SugarAuthenticate/SugarAuthenticate.php');
require_once('/var/www/crm/html/sr/CAS/CAS.php');


/********************************************************************
 * Module that allows Sugar to perform user authentication using
 *  CAS.
 *********************************************************************/

class CASAuthenticate extends SugarAuthenticate {

    var $userAuthenticateClass = 'CASAuthenticateUser';
    var $authenticationDir = 'CASAuthenticate';


      function CASAuthenticate(){

	 //  parent::SugarAuthenticate();
       require_once('modules/Users/authentication/'. $this->authenticationDir . '/'. $this->userAuthenticateClass . '.php');
        $this->userAuthenticate = new $this->userAuthenticateClass();
        $this->doCASAuth();
          }


        function doCASAuth(){

         @session_start();

		 // Don't try to login if the user is logging out
        if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'Logout') {
            $this->logout();
        }
        // If the user is already authenticated, do this.
        elseif (isset($_SESSION['authenticated_user_id']) ) {
            $this->sessionAuthenticate();
            return;
        }
         // Try to log the user in via SSO
        else {
            if ($this->userAuthenticate->loadUserOnLogin() == true) {
			    $this->postLoginAuthenticate();
                 }
              else {
			       $_SESSION['invalid_CAS']=1;
		     	   parent::SugarAuthenticate();
			 //I should redirect here.  I'm not sure on the syntax -- sorry.
            } //end nested else.
        } // end top else.
        } //end doCASAuth()




  	function sessionAuthenticate(){

		global $module, $action, $allowed_actions;
		$authenticated = false;
		$allowed_actions = array ("Authenticate", "Login"); // these are actions where the user/server keys aren't compared
		if (isset ($_SESSION['authenticated_user_id'])) {
			$GLOBALS['log']->debug("We have an CAS authenticated user id: ".$_SESSION["authenticated_user_id"]);

			$authenticated = $this->postSessionAuthenticate();

		} else
		if (isset ($action) && isset ($module) && $action == "Authenticate" && $module == "Users") {
			$GLOBALS['log']->debug("We are authenticating user now");
		} else {
			$GLOBALS['log']->debug("The current CAS user does not have a session.  Going to the login page");
			$action = "Login";
			$module = "Users";
			$_REQUEST['action'] = $action;
			$_REQUEST['module'] = $module;
		}
		if (empty ($GLOBALS['current_user']->id) && !in_array($action, $allowed_actions)) {

			$GLOBALS['log']->debug("The current CAS user is not logged in going to login page");
			$action = "Login";
			$module = "Users";
			$_REQUEST['action'] = $action;
			$_REQUEST['module'] = $module;

		}

		if($authenticated && ((empty($_REQUEST['module']) || empty($_REQUEST['action'])) || ($_REQUEST['module'] != 'Users' || $_REQUEST['action'] != 'Logout'))){
			$this->validateIP();
		}
		return $authenticated;
	}


  /*

     function sessionAuthenticate(){

        global $module, $action, $allowed_actions;
        $authenticated = false;
        $allowed_actions = array ("Authenticate", "Login"); // these are actions where the user/server keys aren't compared

        if (isset ($_SESSION['authenticated_user_id'])) {
            $GLOBALS['log']->debug("We have an authenticated user with CAS: ".$_SESSION["authenticated_user_id"]);
            $authenticated = $this->postSessionAuthenticate();
         } else
            if (isset ($action) && isset ($module) && $action == "Authenticate" && $module == "Users") {
            $GLOBALS['log']->debug("We are NOT authenticating user now.  CAS will redirect.");
        }
        return $authenticated;
        } //end sessionAuthenticate() */


        function logout() {
        phpCAS::setDebug();
        phpCAS::client(CAS_VERSION_2_0,'login.example.com',443,'cas');
        phpCAS::setNoCasServerValidation();
        phpCAS::logout();
		session_destroy();
		ob_clean();
		sugar_cleanup(true);
      }




}//end CASAuthenticate class
CASAuthenticateUser.php
<?php

if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');

require_once('modules/Users/authentication/SugarAuthenticate/SugarAuthenticateUser.php');
require_once('/var/www/crm/html/sr/CAS/CAS.php');


class CASAuthenticateUser extends SugarAuthenticateUser {

    /********************************************************************************
     * This is called when a user logs in
     *
     * @param STRING $name
     * @param STRING $password
     * @return boolean
     ********************************************************************************/

     function loadUserOnLogin() {

      $user_id=$this->authUser();

     if(empty($user_id)){
		return false;
        }
     else{
        $GLOBALS['log']->debug("Starting user load for ". $user_id);
		 $this->loadUserOnSession($user_id);
        return true;
        }
      }//end loadUserOnlogin()

   /**********************************************************************************************************************
    * Attempt to authenticate the user via CAS SSO
    ***********************************************************************************************************************/

      function authUser() {

         phpCAS::client(CAS_VERSION_2_0,'login.example.com',443,'cas');
         phpCAS::setNoCasServerValidation();
         phpCAS::forceAuthentication();
         $authenticated = phpCAS::isAuthenticated();

        if ($authenticated)
        {
            $user_name = phpCAS::getUser();
            $query = "SELECT * from users where user_name='$user_name' and deleted=0";
            $result =$GLOBALS['db']->limitQuery($query,0,1,false);
            $row = $GLOBALS['db']->fetchByAssoc($result);
            if (!empty ($row))
            {
				$_SESSION['cas_user']=$row['user_name'];
				$_SESSION['cas_pass']=$row['user_hash'];
				$user_id=$row['id'];
                $_SESSION['login_user_name'] = $user_name;
                $_REQUEST['user_password'] =  $row['user_hash'];
            }
            else // row in Sugar DB was empty, even though user is in CAS.
            {
              return '';
		    }

            $action = 'Authenticate';
            $module = 'Users';
            $_REQUEST['action'] = 'Authenticate';
            $_REQUEST['module'] = 'Users';
            $_REQUEST['return_module'] = 'Users';
            $_REQUEST['action_module'] = 'Login';
			header("Location: index.php?module=Users&action=Authenticate");

            return $user_id; // SSO authentication was successful

        }
        else // not authenticated in CAS.
        {
          return;
        }

      }//end authenticateSSO();



/************************************************************************************************************/
/************************************************************************************************************/

}//End CASAuthenticateUSer class.
?>

SOAP ile sugar'a bağlanıyorsanız soap dizini altındaki SoapSugarUsers.php dosyasında

$authController = new AuthenticationController((!empty($sugar_config['authenticationClass'])? $sugar_config['authenticationClass'] : 'SugarAuthenticate'));

satırlarını bununla değiştirin:

<?php $authController = new AuthenticationController('SugarAuthenticate'); ?>

aksi takdirde soap sorgularda CAS athentication isteyecektir.

Yeni yorum ekle