Exemplo n.º 1
0
 /**
  * Method to get the field input markup.
  *
  * @return  string	The field input markup.
  *
  * @since   1.6
  */
 protected function getInput()
 {
     $html = array();
     $attr = '';
     // Initialize some field attributes.
     $attr .= $this->element['class'] ? ' class="' . (string) $this->element['class'] . '"' : '';
     $attr .= (string) $this->element['disabled'] == 'true' ? ' disabled="disabled"' : '';
     $attr .= $this->element['size'] ? ' size="' . (int) $this->element['size'] . '"' : '';
     // Initialize JavaScript field attributes.
     $attr .= $this->element['onchange'] ? ' onchange="' . (string) $this->element['onchange'] . '"' : '';
     // Get some field values from the form.
     $id = (int) $this->form->getValue('id');
     $db = JFactory::getDbo();
     $table = SHFactory::getConfig()->get('ldap:table', '#__sh_ldap_config');
     $query = $db->getQuery(true);
     // Build the query for the ordering list
     $query->select('ordering AS value')->select('name AS text')->select($db->quoteName('id'))->from($db->quoteName($table))->order($db->quoteName('ordering'));
     if ((string) $this->element['readonly'] == 'true') {
         // Create a read-only list (no name) with a hidden input to store the value.
         $html[] = JHtml::_('list.ordering', '', (string) $query, trim($attr), $this->value, $id ? 0 : 1);
         $html[] = '<input type="hidden" name="' . $this->name . '" value="' . $this->value . '"/>';
     } else {
         // Create a regular list.
         $html[] = JHtml::_('list.ordering', $this->name, (string) $query, trim($attr), $this->value, $id ? 0 : 1);
     }
     return implode($html);
 }
 public function testConfigInvalidSource()
 {
     $this->setExpectedException('InvalidArgumentException', 'LIB_SHLDAPHELPER_ERR_10601', 10601);
     // Change it to a invalid LDAP config source
     $platform = SHFactory::getConfig('file', array('file' => static::PLATFORM_CONFIG_FILE, 'namespace' => 'single'));
     $platform->set('ldap.config', 84);
     SHLdapHelper::getConfig(null, $platform);
 }
Exemplo n.º 3
0
 /**
  * Constructor
  *
  * @param   object  &$subject  The object to observe
  * @param   array   $config    An array that holds the plugin configuration
  *
  * @since  2.0
  */
 public function __construct(&$subject, $config = array())
 {
     parent::__construct($subject, $config);
     $this->loadLanguage();
     $this->templateName = $this->params->get('template_name', 'default');
     $this->templateBase = $this->params->get('template_base', JPATH_PLUGINS . '/ldap/creation/templates');
     $this->domain = SHFactory::getConfig()->get('ldap.defaultconfig');
 }
Exemplo n.º 4
0
 /**
  * Initialises and imports the Shmanic platform and project libraries.
  * This is fired on application initialise typically by the CMS.
  *
  * @return  void
  *
  * @since   2.0
  */
 public function onAfterInitialise()
 {
     // Check if the Shmanic platform has already been imported
     if (!defined('SHPATH_PLATFORM')) {
         $platform = JPATH_PLATFORM . '/shmanic/import.php';
         if (!file_exists($platform)) {
             // Failed to find the import file
             return false;
         }
         // Shmanic Platform import
         if (!(include_once $platform)) {
             // Failed to import the Shmanic platform
             return false;
         }
     }
     // Import the logging method
     SHLog::import($this->params->get('log_group', 'shlog'));
     // Container to store project specific import results
     $results = array();
     // Use the default SQL configuration
     $config = SHFactory::getConfig();
     // Get all the importable projects
     if ($imports = json_decode($config->get('platform.import'))) {
         foreach ($imports as $project) {
             // Attempts to import the specified project
             $results[] = shImport(trim($project));
         }
     }
     // Fire the onAfterInitialise for all the registered imports/projects
     JDispatcher::getInstance()->trigger('onSHPlaformInitialise');
     if (in_array(false, $results, true)) {
         // One of the specific projects failed to import
         return false;
     }
     // Everything imported successfully
     return true;
 }
Exemplo n.º 5
0
 /**
  * Returns all the Ldap configured IDs and names in an associative array
  * where [id] => [name].
  *
  * @param   JRegistry  $registry  Platform configuration.
  *
  * @return  Array  Array of configured IDs
  *
  * @since   2.0
  */
 public static function getConfigIDs($registry = null)
 {
     // Get the Ldap configuration from the factory
     $registry = is_null($registry) ? SHFactory::getConfig() : $registry;
     // Get the Ldap configuration source (e.g. sql | plugin | file)
     $source = (int) $registry->get('ldap.config', self::CONFIG_SQL);
     if ($source === self::CONFIG_SQL) {
         // Get the database table using the sh_ldap_config as default
         $table = $registry->get('ldap.table', '#__sh_ldap_config');
         // Get the global JDatabase object
         $db = JFactory::getDbo();
         $query = $db->getQuery(true);
         // Do the SQL query
         $query->select($db->quoteName('id'))->select($db->quoteName('name'))->from($db->quoteName($table))->where($db->quoteName('enabled') . ' >= ' . $db->quote('1'));
         $db->setQuery($query);
         // Execute the query
         $results = $db->loadAssocList('id', 'name');
         return $results;
     } elseif ($source === self::CONFIG_FILE) {
         // Grab the LDAP configuration file path from the registry and include it
         if ($file = $registry->get('ldap.file', JPATH_CONFIGURATION . '/ldap.php')) {
             @(include_once $file);
         }
         // Lets find all classes in the LDAP configuration file
         $classes = array_values(preg_grep('/(' . self::CONFIG_PREFIX . '){1}\\w*/i', get_declared_classes()));
         if (!empty($classes)) {
             $namespaces = $classes;
             // Retrieve the namespaces from the classes
             foreach ($namespaces as &$namespace) {
                 $namespace = str_ireplace(self::CONFIG_PREFIX, '', $namespace);
             }
             return $namespaces;
         }
         // There are no namespaces, there return an array with one null element
         return array(null);
     }
 }
Exemplo n.º 6
0
 /**
  * This method handles the user adapter authorisation and reports
  * back to the subject. This method is also used for single sign on.
  *
  * There is no custom logging in the authentication.
  *
  * @param   array  $response  Authentication response object from onUserAuthenticate()
  * @param   array  $options   Array of extra options
  *
  * @return  JAuthenticationResponse  Authentication response object
  *
  * @since   2.0
  */
 public function onUserAuthorisation($response, $options = array())
 {
     // Create a new authentication response
     $retResponse = new JAuthenticationResponse();
     // Check if some other authentication system is dealing with this request
     if (!empty($response->type) && strtoupper($response->type) !== self::AUTH_TYPE) {
         return $retResponse;
     }
     // Check the Shmanic platform has been imported
     if (!$this->_checkPlatform()) {
         // Failed to import the platform
         $response->status = JAuthentication::STATUS_FAILURE;
         $response->error_message = JText::_('PLG_AUTHENTICATION_SHADAPTER_ERR_12601');
         return false;
     }
     $response->type = self::AUTH_TYPE;
     /*
      * Attempt to authorise with User Adapter. This method will automatically detect
      * the correct configuration (if multiple ones are specified) and return a
      * SHUserAdapter object. If this method returns false, then the authorise was
      * unsuccessful - basically the user was not found or configuration was
      * bad.
      */
     try {
         // Setup user adapter injecting the domain from SSO if specified
         $credentials = array('username' => $response->username);
         if (isset($options['domain'])) {
             $credentials['domain'] = $options['domain'];
         }
         $adapter = SHFactory::getUserAdapter($credentials);
         // Get the authorising user dn
         $id = $adapter->getId(false);
     } catch (Exception $e) {
         // Configuration or authorisation failure
         $response->status = JAuthentication::STATUS_FAILURE;
         $response->error_message = JText::_('JGLOBAL_AUTH_NO_USER');
         return;
     }
     try {
         // Let's get the user attributes
         $attributes = $adapter->getAttributes();
         if (!is_array($attributes) || !count($attributes)) {
             // No attributes therefore error
             throw new Exception(JText::_('PLG_AUTHENTICATION_SHADAPTER_ERR_12611'), 12611);
         }
     } catch (Exception $e) {
         // Error getting user attributes.
         $response->status = JAuthentication::STATUS_FAILURE;
         $response->error_message = JText::_('PLG_AUTHENTICATION_SHADAPTER_ERR_12611');
         // Process a error log
         SHLog::add($e, 12622, JLog::ERROR, 'auth');
         return false;
     }
     // Set the required Joomla specific user fields with the returned User Adapter Attributes
     $response->username = $adapter->getUid();
     $response->fullname = $adapter->getFullname();
     $response->email = $adapter->getEmail();
     // The adapter type needs to be set before returning the response
     $response->type = $adapter->getType();
     if (SHFactory::getConfig()->get('user.nullpassword')) {
         // Do not store password in Joomla database
         $response->password_clear = '';
     }
     /*
      * Everything appears to be a success and therefore we shall log the user login
      * then report back to the subject.
      */
     SHLog::add(JText::sprintf('PLG_AUTHENTICATION_SHADAPTER_INFO_12612', $response->username), 12612, JLog::INFO, 'auth');
     $retResponse->status = JAuthentication::STATUS_SUCCESS;
     unset($adapter);
     return $retResponse;
 }
Exemplo n.º 7
0
	/**
	 * Loads the profile XML and passes it to the form to load the fields (excluding data).
	 *
	 * @param   JForm  $form  The form to be altered.
	 * @param   array  $data  The associated data for the form.
	 *
	 * @return  boolean
	 *
	 * @since   2.0
	 */
	public function onContentPrepareForm($form, $data)
	{
		// Check if the profile parameter is enabled
		if (!$this->use_profile)
		{
			return true;
		}

		if (!($form instanceof JForm))
		{
			$this->_subject->setError('JERROR_NOT_A_FORM');

			return false;
		}

		// Check we are manipulating a valid form
		if (!in_array($form->getName(), $this->permittedForms))
		{
			return true;
		}

		$showForm = true;
		$domain = null;

		// Check if this user should have a profile
		if ($userId = isset($data->id) ? $data->id : 0)
		{
			if (SHLdapHelper::isUserLdap($userId))
			{
				$domain = SHUserHelper::getDomainParam($data);
			}
			else
			{
				$showForm = false;
			}
		}
		elseif (!JFactory::getUser()->guest)
		{
			/*
			 * Sometimes the $data variable is not populated even when an edit is required.
			 * This means we have to check the form post data directly for the user ID.
			 * We do not worry about frontend registrations as we check for guest.
			 * If there is no form posted then this could be a backend registration.
			 */
			if ($inForm = JFactory::getApplication()->input->get('jform', false, 'array'))
			{
				$id = SHUtilArrayhelper::getValue($inForm, 'id', 0, 'int');

				if ($id === 0)
				{
					// Ask all plugins if there is a plugin willing to deal with user creation for ldap
					if (count($results = SHFactory::getDispatcher('ldap')->trigger('askUserCreation')))
					{
						// Due to being unaware of the domain for this new user, we are forced to use the default domain
						$domain = SHFactory::getConfig()->get('ldap.defaultconfig');
					}
					else
					{
						// LDAP creation not enabled
						$showForm = false;
					}
				}
				else
				{
					if (SHLdapHelper::isUserLdap($id))
					{
						// Existing ldap user
						$domain = SHUserHelper::getDomainParam($id);
					}
					else
					{
						// Existing non-ldap user
						$showForm = false;
					}
				}
			}
		}

		if ($showForm)
		{
			// We have to launch the getxmlfields to correctly include languages
			$this->getXMLFields($domain);

			// Get the File and Path for the Profile XML
			$file 		= $this->getXMLFileName($domain);
			$xmlPath 	= $this->profile_base . '/' . $file . '.xml';

			// Load in the profile XML file to the form
			if (($xml = JFactory::getXML($xmlPath, true)) && ($form->load($xml, false, false)))
			{
				// Successfully loaded in the XML
				return true;
			}
		}
	}
Exemplo n.º 8
0
 /**
  * Method to get a JDatabaseQuery object for retrieving the data set from a database.
  *
  * @return  JDatabaseQuery   A JDatabaseQuery object to retrieve the data set.
  *
  * @since   2.0
  */
 public function getListQuery()
 {
     // Create a new query object.
     $db = $this->getDbo();
     $query = $db->getQuery(true);
     // Select the required fields from the table.
     $query->select($db->escape($this->getState('list.select', 'a.*')));
     $query->from($db->quoteName(SHFactory::getConfig()->get('ldap.table', '#__sh_ldap_config')) . ' AS a');
     // Filter the items over the search string if set.
     $search = $this->getState('filter.search');
     if (!empty($search)) {
         if (stripos($search, 'id:') === 0) {
             $query->where($db->quoteName('a.id') . ' = ' . $db->quote((int) substr($search, 3)));
         } else {
             // Note: * we use an escape so no quote required *
             $search = $db->quote('%' . $db->escape($search, true) . '%');
             $query->where('(' . $db->quoteName('name') . ' LIKE ' . $search . ')');
         }
     }
     // Add the list ordering clause.
     $query->order($db->escape($this->getState('list.ordering', 'ordering')) . ' ' . $db->escape($this->getState('list.direction', 'ASC')));
     return $query;
 }
Exemplo n.º 9
0
 /**
  * Constructor
  *
  * @param   object  &$db  Database object
  *
  * @since   2.0
  */
 public function __construct(&$db)
 {
     $this->table = SHFactory::getConfig()->get('ldap.table', '#__sh_ldap_config');
     parent::__construct($this->table, 'id', $db);
 }
Exemplo n.º 10
0
	/**
	 * This method returns a user object. If options['autoregister'] is true,
	 * and if the user doesn't exist, then it'll be created.
	 *
	 * @param   array  $user      Holds the user data.
	 * @param   array  &$options  Array holding options (remember, autoregister, group).
	 *
	 * @return  JUser  A JUser object containing the user.
	 *
	 * @since   1.0
	 * @throws  Exception
	 */
	public static function getUser(array $user, &$options = array())
	{
		$instance = JUser::getInstance();

		if (isset($options['adapter']))
		{
			// Tell the getUser to store the auth_type and auth_config based on whats inside the adapter
			$options['type'] = isset($options['type']) ? $options['type'] : $options['adapter']::getType();
			$options['domain'] = isset($options['domain']) ? $options['domain'] : $options['adapter']->getDomain();
		}

		// Check if the user already exists in the database
		if ($id = intval(JUserHelper::getUserId($user['username'])))
		{
			$instance->load($id);

			// Inject the type and domain into this object if they are set
			if (isset($options['type']))
			{
				if ($instance->getParam(self::PARAM_AUTH_TYPE) != $options['type'])
				{
					$options['change'] = true;
					$instance->setParam(self::PARAM_AUTH_TYPE, $options['type']);
				}
			}

			if (isset($options['domain']))
			{
				if ($instance->getParam(self::PARAM_AUTH_DOMAIN) != $options['domain'])
				{
					$options['change'] = true;
					$instance->setParam(self::PARAM_AUTH_DOMAIN, $options['domain']);
				}
			}

			return $instance;
		}

		// ** The remainder of this method is for new users only **

		$config = SHFactory::getConfig();

		// Deal with auto registration flags
		$autoRegister = (int) $config->get('user.autoregister', 1);

		if ($autoRegister === 0 || $autoRegister === 1)
		{
			// Inherited Auto-registration
			$options['autoregister'] = isset($options['autoregister']) ? $options['autoregister'] : $autoRegister;
		}
		else
		{
			// Override Auto-registration
			$options['autoregister'] = ($autoRegister === 2) ? 1 : 0;
		}

		// Deal with the default group
		jimport('joomla.application.component.helper');
		$comUsers = JComponentHelper::getParams('com_users', true);

		if ($comUsers === false)
		{
			// Check if there is a default set in the SHConfig
			$defaultUserGroup = $config->get('user.defaultgroup', 2);
		}
		else
		{
			// Respect Joomla's default user group
			$defaultUserGroup = $comUsers->get('new_usertype', 2);
		}

		// Setup the user fields for this new user
		$instance->set('id', 0);
		$instance->set('name', $user['fullname']);
		$instance->set('username', $user['username']);
		$instance->set('password_clear', $user['password_clear']);
		$instance->set('email', $user['email']);
		$instance->set('usertype', 'depreciated');
		$instance->set('groups', array($defaultUserGroup));

		// Set the User Adapter parameters
		if (isset($options['type']))
		{
			$instance->setParam(self::PARAM_AUTH_TYPE, $options['type']);
		}

		if (isset($options['domain']))
		{
			$instance->setParam(self::PARAM_AUTH_DOMAIN, $options['domain']);
		}

		// If autoregister is set, register the user
		if ($options['autoregister'])
		{
			if (!self::save($instance))
			{
				// Failed to save the user to the database
				throw new Exception(JText::sprintf('LIB_SHUSERHELPER_ERR_10501', $user['username'], $instance->getError()), 10501);
			}
		}
		else
		{
			// We don't want to proceed if autoregister is not enabled
			throw new Exception(JText::sprintf('LIB_SHUSERHELPER_ERR_10502', $user['username']), 10502);
		}

		return $instance;
	}
Exemplo n.º 11
0
 /**
  * Returns whether SSO is allowed to perform actions in the current session.
  *
  * @return  integer  True if session is enabled or False if SSO disabled.
  *
  * @since   1.0
  */
 public static function status()
 {
     $config = SHFactory::getConfig();
     $behaviour = (int) $config->get('sso.behaviour', 1);
     $status = JFactory::getSession()->get(self::SESSION_STATUS_KEY, false);
     if ($status === false) {
         $status = self::STATUS_ENABLE;
     }
     $status = (int) $status;
     if ($status === self::STATUS_BYPASS_DISABLE) {
         if ($behaviour !== 1) {
             // Manual bypass is activated
             return self::STATUS_BYPASS_DISABLE;
         }
     } elseif ($behaviour === 2 || $behaviour === 0) {
         $formLogin = true;
         // Get the login tasks and check if username can be null to sso
         $tasks = json_decode($config->get('sso.logintasks', '[]'));
         $usernameField = $config->get('sso.checkusernull', true);
         // Check if the URL contains this key and the value assigned to it
         $input = new JInput();
         $task = $input->get('task', false);
         if (!in_array($task, $tasks) || !JSession::checkToken() || $usernameField && $input->get('username', null)) {
             $formLogin = false;
         }
         if ($status === self::STATUS_LOGOUT_DISABLE) {
             // Logout bypass is activated
             if (!$formLogin) {
                 return self::STATUS_LOGOUT_DISABLE;
             }
         } elseif ($status === self::STATUS_ENABLE) {
             if ($behaviour === 0 && !$formLogin) {
                 return self::STATUS_BEHAVIOUR_DISABLED;
             }
         }
     }
     // Default to SSO enabled
     return self::STATUS_ENABLE;
 }
Exemplo n.º 12
0
 /**
  * Entry point for the script.
  *
  * @return  void
  *
  * @since   2.0
  */
 public function doExecute()
 {
     // Setup some stats
     $failed = 0;
     $success = 0;
     $errors = array();
     // It appears we have to tell the system we are running with the site otherwise bad things happen
     JFactory::getApplication('site');
     $this->out(JText::_('CLI_SHMANIC_LDAP_INFO_13001'));
     // Get all the valid configurations
     if (!($configs = SHLdapHelper::getConfig())) {
         // Failed to find any Ldap configs
         $this->out(JText::_('CLI_SHMANIC_LDAP_ERR_13003'));
         $this->close(1);
     }
     // Check if only a single config was found
     if ($configs instanceof JRegistry) {
         /*
          * To make things easier, we pretend we returned multiple Ldap configs
          * by casting the single entry into an array.
          */
         $configs = array($configs);
     }
     $count = count($configs);
     $this->out(JText::sprintf('CLI_SHMANIC_LDAP_INFO_13002', $count))->out();
     // Loop around each LDAP configuration
     foreach ($configs as $config) {
         try {
             // Get a new Ldap object
             $ldap = new SHLdap($config);
             // Bind with the proxy user
             if (!$ldap->authenticate(SHLdap::AUTH_PROXY)) {
                 // Something is wrong with this LDAP configuration - cannot bind to proxy user
                 $errors[] = new Exception(JText::sprintf('CLI_SHMANIC_LDAP_ERR_13011', $ldap->info), 13011);
                 unset($ldap);
                 continue;
             }
             // Get all the Ldap users in the directory
             if (!($result = $ldap->search(null, $ldap->allUserFilter, array('dn', $ldap->keyUid)))) {
                 // Failed to search for all users in the directory
                 $errors[] = new Exception(JText::sprintf('CLI_SHMANIC_LDAP_ERR_13012', $ldap->getErrorMsg()), 13012);
                 unset($ldap);
                 continue;
             }
             // Loop around each Ldap user
             for ($i = 0; $i < $result->countEntries(); ++$i) {
                 // Get the Ldap username (case insensitive)
                 if (!($username = strtolower($result->getValue($i, $ldap->keyUid, 0)))) {
                     continue;
                 }
                 try {
                     // Check if this user is in the blacklist
                     if ($blacklist = (array) json_decode(SHFactory::getConfig()->get('user.blacklist'))) {
                         if (in_array($username, $blacklist)) {
                             throw new RuntimeException(JText::_('CLI_SHMANIC_LDAP_ERR_13025'), 13025);
                         }
                     }
                     // Create the new user adapter
                     $adapter = new SHUserAdaptersLdap(array('username' => $username), $config);
                     // Get the Ldap DN
                     if (!($dn = $adapter->getId(false))) {
                         continue;
                     }
                     $this->out(JText::sprintf('CLI_SHMANIC_LDAP_INFO_13020', $username));
                     // Get the Ldap user attributes
                     $source = $adapter->getAttributes();
                     // Get the core mandatory J! user fields
                     $username = $adapter->getUid();
                     $fullname = $adapter->getFullname();
                     $email = $adapter->getEmail();
                     if (empty($fullname)) {
                         // Full name doesnt exist; use the username instead
                         $fullname = $username;
                     }
                     if (empty($email)) {
                         // Email doesnt exist; cannot proceed
                         throw new Exception(JText::_('CLI_SHMANIC_LDAP_ERR_13022'), 13022);
                     }
                     // Create the user array to enable creating a JUser object
                     $user = array('fullname' => $fullname, 'username' => $username, 'password_clear' => null, 'email' => $email);
                     // Create a JUser object from the Ldap user
                     $options = array('adapter' => &$adapter);
                     $instance = SHUserHelper::getUser($user, $options);
                     if ($instance === false) {
                         // Failed to get the user either due to save error or autoregister
                         throw new Exception(JText::_('CLI_SHMANIC_LDAP_ERR_13024'), 13024);
                     }
                     // Fire the Ldap specific on Sync feature
                     $sync = SHLdapHelper::triggerEvent('onLdapSync', array(&$instance, $options));
                     // Check if the synchronise was successfully and report
                     if ($sync !== false) {
                         // Even if the sync does not need a save, do it anyway as Cron efficiency doesnt matter too much
                         SHUserHelper::save($instance);
                         // Update the user map linker
                         SHAdapterMap::setUser($adapter, $instance->id);
                         // Above should throw an exception on error so therefore we can report success
                         $this->out(JText::sprintf('CLI_SHMANIC_LDAP_INFO_13029', $username));
                         ++$success;
                     } else {
                         throw new Exception(JText::_('CLI_SHMANIC_LDAP_ERR_13026'), 13026);
                     }
                     unset($adapter);
                 } catch (Exception $e) {
                     unset($adapter);
                     ++$failed;
                     $errors[] = new Exception(JText::sprintf('CLI_SHMANIC_LDAP_ERR_13028', $username, $e->getMessage()), $e->getCode());
                 }
             }
         } catch (Exception $e) {
             $errors[] = new Exception(JText::_('CLI_SHMANIC_LDAP_ERR_13004'), 13004);
         }
     }
     // Print out some results and stats
     $this->out()->out()->out(JText::_('CLI_SHMANIC_LDAP_INFO_13032'))->out();
     $this->out(JText::_('CLI_SHMANIC_LDAP_INFO_13038'));
     foreach ($errors as $error) {
         if ($error instanceof Exception) {
             $this->out(' ' . $error->getCode() . ': ' . $error->getMessage());
         } else {
             $this->out(' ' . (string) $error);
         }
     }
     $this->out()->out(JText::sprintf('CLI_SHMANIC_LDAP_INFO_13034', $success));
     $this->out(JText::sprintf('CLI_SHMANIC_LDAP_INFO_13036', $failed));
     $this->out()->out('============================');
 }
Exemplo n.º 13
0
 /**
  * TODO: move to a SHPlatform specific test in the future
  */
 public function testSHPlatformFactoryBadConfig()
 {
     $this->setExpectedException('RuntimeException', 'LIB_SHPLATFORM_ERR_1121', 1121);
     $platform = SHFactory::getConfig('file', array('file' => static::PLATFORM_CONFIG_FILE, 'namespace' => 'asdas'));
 }
Exemplo n.º 14
0
	/**
	 * Returns all the Ldap configured IDs and names in an associative array
	 * where [id] => [name].
	 *
	 * @param   JRegistry  $registry  Platform configuration.
	 *
	 * @return  Array  Array of configured IDs
	 *
	 * @since   2.0
	 */
	public static function getConfigIDs($registry = null)
	{
		// Get the Ldap configuration from the factory
		$registry = (is_null($registry)) ? SHFactory::getConfig() : $registry;

		// Get the Ldap configuration source (e.g. sql | plugin | file)
		$source = (int) $registry->get('ldap.config', self::CONFIG_SQL);

		if ($source === self::CONFIG_SQL)
		{
			// Get the database table using the sh_ldap_config as default
			$table = $registry->get('ldap.table', '#__sh_ldap_config');

			// Get the global JDatabase object
			$db = JFactory::getDbo();

			$query = $db->getQuery(true);

			// Do the SQL query
			$query->select($db->quoteName('id'))
				->select($db->quoteName('name'))
				->from($db->quoteName($table))
				->where($db->quoteName('enabled') . ' >= ' . $db->quote('1'));

			$db->setQuery($query);

			// Execute the query
			$results = $db->loadAssocList('id', 'name');

			return $results;
		}
		elseif ($source === self::CONFIG_FILE)
		{
			// Generate the namesapce
			if ($namespaces = $registry->get('ldap.namespaces', false))
			{
				// Split multiple namespaces
				$namespaces = explode(';', $namespaces);

				return $namespaces;
			}

			// There are no namespaces, there return an array with one null element
			return array(null);
		}
	}
Exemplo n.º 15
0
	/**
	 * Find the correct Ldap parameters based on the authorised and configuration
	 * specified. If found then return the successful Ldap object.
	 *
	 * Note: you can use SHLdap::lastUserDn for the user DN instead of rechecking again.
	 *
	 * @param   integer|string  $id          Optional configuration record ID.
	 * @param   Array           $authorised  Optional authorisation/authentication options (authenticate, username, password).
	 * @param   JRegistry       $registry    Optional override for platform configuration registry.
	 *
	 * @return  SHLdap  An Ldap object on successful authorisation or False on error.
	 *
	 * @since   2.0
	 * @throws  InvalidArgumentException  Invalid configurations
	 * @throws  SHExceptionStacked        User or configuration issues (may not be important)
	 */
	public static function getInstance($id = null, array $authorised = array(), JRegistry $registry = null)
	{
		// Get the platform registry config from the factory if required
		$registry = is_null($registry) ? SHFactory::getConfig() : $registry;

		// Get the optional authentication/authorisation options
		$authenticate = SHUtilArrayhelper::getValue($authorised, 'authenticate', self::AUTH_NONE);
		$username = SHUtilArrayhelper::getValue($authorised, 'username', null);
		$password = SHUtilArrayhelper::getValue($authorised, 'password', null);

		// Get all the Ldap configs that are enabled and available
		$configs = SHLdapHelper::getConfig($id, $registry);

		// Check if only one configuration result was found
		if ($configs instanceof JRegistry)
		{
			// Wrap this around an array so we can use the same code below
			$configs = array($configs);
		}

		// Keep a record of any exceptions called and only log them after
		$errors = array();

		// Loop around each of the Ldap configs until one authenticates
		foreach ($configs as $config)
		{
			try
			{
				// Get a new SHLdap object
				$ldap = new SHLdap($config);

				// Check if the authenticate/authentication is successful
				if ($ldap->authenticate($authenticate, $username, $password))
				{
					// This is the correct configuration so return the new client
					return $ldap;
				}
			}
			catch (Exception $e)
			{
				// Add the error to the stack
				$errors[] = $e;
			}

			unset($ldap);
		}

		// Failed to find any configs to match
		if (count($errors) > 1)
		{
			// More than one config caused issues, use the stacked exception
			throw new SHExceptionStacked(JText::_('LIB_SHLDAP_ERR_10411'), 10411, $errors);
		}
		else
		{
			// Just rethrow the one exception
			throw $errors[0];
		}
	}
Exemplo n.º 16
0
 /**
  * Calls the logoutRemoteUser method within SSO plug-in if the user
  * was logged on with SSO.
  *
  * @return  void
  *
  * @since   2.0
  */
 public function logout()
 {
     $session = JFactory::getSession();
     $app = JFactory::getApplication();
     // Get the SSO plug-in name from login if we used SSO
     if ($class = $session->get(SHSsoHelper::SESSION_PLUGIN_KEY, false)) {
         // Lets disable SSO until the user requests login
         SHSsoHelper::disable();
         $router = $app->getRouter();
         // We need to add a callback on the router to tell the routed page we just logged out from SSO
         $router->setVar('ssologoutkey', SHFactory::getConfig()->get('sso.bypasskey', 'nosso'));
         $router->setVar('ssologoutval', $session->get(SHSsoHelper::SESSION_STATUS_KEY, SHSsoHelper::STATUS_ENABLE));
         $router->attachBuildRule('SHSso::logoutRouterRule');
         $index = array_search($class, $this->_observers);
         // Ensure the SSO plug-in is still available
         if ($index !== false && method_exists($this->_observers[$index], 'logoutRemoteUser')) {
             $this->_observers[$index]->logoutRemoteUser();
         }
     }
 }
Exemplo n.º 17
0
 * @copyright  Copyright (C) 2011-2013 Shaun Maunder. All rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE.txt
 */
defined('JPATH_PLATFORM') or die;
if (!defined('SHPATH_PLATFORM')) {
    // Load the platform
    require_once JPATH_PLATFORM . '/shmanic/import.php';
}
if (!defined('SHLDAP_VERSION')) {
    // Define the JMapMyLDAP version
    define('SHLDAP_VERSION', SHFactory::getConfig()->get('ldap.version'));
}
// Load the global Ldap language file
JFactory::getLanguage()->load('shmanic_ldap', JPATH_ROOT);
// Push the reqcert setting if defined
if ($reqcert = (int) SHFactory::getConfig()->get('ldap.reqcert', 0)) {
    if ($reqcert === 1) {
        putenv('LDAPTLS_REQCERT=never');
    } elseif ($reqcert === 2) {
        putenv('LDAPTLS_REQCERT=allow');
    } elseif ($reqcert === 3) {
        putenv('LDAPTLS_REQCERT=try');
    } elseif ($reqcert === 4) {
        putenv('LDAPTLS_REQCERT=hard');
    }
}
// Setup and get the Ldap dispatcher
$dispatcher = SHFactory::getDispatcher('ldap');
// Start the LDAP event debugger only if global jdebug is switched on
if (defined('JDEBUG') && JDEBUG && class_exists('SHLdapEventDebug')) {
    new SHLdapEventDebug($dispatcher);
Exemplo n.º 18
0
 /**
  * Method for attempting single sign on.
  *
  * @return  boolean  True on successful SSO or False on failure.
  *
  * @since   2.0
  */
 protected function _attemptSSO()
 {
     // Check the required SSO libraries exist
     if (!(class_exists('SHSsoHelper') && class_exists('SHSso'))) {
         // Error: classes missing
         SHLog::add(JText::_('LIB_SHSSOMONITOR_ERR_15001'), 15001, JLog::ERROR, 'sso');
         return;
     }
     try {
         $config = SHFactory::getConfig();
         // Check if SSO is disabled via the session
         if (SHSsoHelper::status() !== SHSsoHelper::STATUS_ENABLE) {
             // It is disabled so do not continue
             return;
         }
         SHSsoHelper::enable();
         $forceLogin = false;
         $userId = JFactory::getUser()->get('id');
         if ($config->get('sso.forcelogin', false)) {
             if ($userId) {
                 // Log out current user if detect user is not equal
                 $forceLogin = true;
             }
         } else {
             if ($userId) {
                 // User already logged in and no forcelogout
                 return;
             }
         }
         /*
          * Lets check the IP rule is valid before we continue -
          * if the IP rule is false then SSO is not allowed here.
          */
         jimport('joomla.application.input');
         $input = new JInput($_SERVER);
         // Get the IP address of this client
         $myIp = $input->get('REMOTE_ADDR', false, 'string');
         // Get a list of the IP addresses specific to the specified rule
         $ipList = json_decode($config->get('sso.iplist'));
         // Get the rule value
         $ipRule = $config->get('sso.iprule', SHSsoHelper::RULE_ALLOW_ALL);
         if (!SHSsoHelper::doIPCheck($myIp, $ipList, $ipRule)) {
             if (!$forceLogin) {
                 // This IP isn't allowed
                 SHLog::add(JText::_('LIB_SHSSO_DEBUG_15004'), 15004, JLog::DEBUG, 'sso');
             }
             return;
         }
         /*
          * We are going to check if we are in backend.
          * If so then we need to check if sso is allowed
          * to execute on the backend.
          */
         if (JFactory::getApplication()->isAdmin()) {
             if (!$config->get('sso.backend', false)) {
                 if (!$forceLogin) {
                     // Not allowed to SSO on backend
                     SHLog::add(JText::_('LIB_SHSSO_DEBUG_15006'), 15006, JLog::DEBUG, 'sso');
                 }
                 return;
             }
         }
         // Instantiate the main SSO library for detection & authentication
         $sso = new SHSso($config->get('sso.plugintype', 'sso'));
         $detection = $sso->detect();
         if ($detection) {
             // Check the detected user is not blacklisted
             $blacklist = (array) json_decode($config->get('user.blacklist'));
             if (in_array($detection['username'], $blacklist)) {
                 SHLog::add(JText::sprintf('LIB_SHSSO_DEBUG_15007', $detection['username']), 15007, JLog::DEBUG, 'sso');
                 // Detected user is blacklisted
                 return;
             }
             // Check if the current logged in user matches the detection
             if ($forceLogin && strtolower($detection['username']) != strtolower(JFactory::getUser()->get('username'))) {
                 SHLog::add(JText::sprintf('LIB_SHSSO_DEBUG_15008', $detection['username']), 15008, JLog::DEBUG, 'sso');
                 // Need to logout the current user
                 JFactory::getApplication()->logout();
             }
         }
         // Attempt the login
         return $sso->login($detection);
     } catch (Exception $e) {
         SHLog::add($e, 15002, JLog::ERROR, 'sso');
     }
 }
Exemplo n.º 19
0
 public function onUserBeforeSaveGroup($form, $table, $isNew)
 {
     $groupname = $table->title;
     try {
         // We want to check if this group is an existing group in an Adapter
         $adapter = SHFactory::getGroupAdapter($groupname);
         $adapter->getId();
         // We need to gather the adapter name to call the correct dispatcher
         $adapterName = $adapter::getName();
     } catch (Exception $e) {
         // We will assume this group doesnt exist in an Adapter
         $adapterName = false;
     }
     if ($adapterName) {
         $event = SHAdapterEventHelper::triggerEvent($adapterName, 'onGroupBeforeSave', array($groupname, $isNew));
         if ($event !== false) {
             try {
                 // Commit the changes to the Adapter if present
                 SHAdapterHelper::commitChanges($adapter, true, true);
                 //TODO: newId
                 SHLog::add(JText::sprintf('LIB_SHADAPTEREVENTBOUNCER_DEBUG_10986', $groupname), 10986, JLog::DEBUG, $adapterName);
                 return true;
             } catch (Excpetion $e) {
                 //TODO: newId
                 SHLog::add($e, 10981, JLog::ERROR, $adapterName);
             }
         }
         return $event;
     } elseif ($isNew) {
         // Use a default group adapter
         $name = SHFactory::getConfig()->get('user.type');
         // We must create and save the group as plugins may talk to adapter driver and expect a group object
         if (SHAdapterEventHelper::triggerEvent($name, 'onGroupCreation', array($groupname)) === true) {
             JFactory::getSession()->set('created', $groupname, SHGroupHelper::SESSION_KEY);
             $event = SHAdapterEventHelper::triggerEvent($adapterName, 'onGroupBeforeSave', array($groupname, $isNew));
             if ($event !== false) {
                 try {
                     // Commit the changes to the Adapter if present
                     $adapter = SHFactory::getGroupAdapter($groupname);
                     SHAdapterHelper::commitChanges($adapter, true, true);
                     return true;
                 } catch (Exception $e) {
                     //TODO: newId
                     SHLog::add($e, 10981, JLog::ERROR, $name);
                 }
             }
             return $event;
         }
         // Something went wrong with the group creation
         return false;
     }
 }