<?php


define('TOKENS_ATTR', 'seciossallowedservice');

SimpleSAML_Logger::info('AUTH  - env: Accessing auth endpoint login');

SimpleSAML_Configuration::init($configdir, 'ldapconfig', 'ldap.php');
$ldapconfig = SimpleSAML_Configuration::getInstance('ldapconfig');

$error = null;
$attributes = array();
$username = null;

if (empty($session))
        SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NOSESSION');

try {
        $authrequestcache = $session->getAuthnRequest($protocol, $authId);
} catch (Exception $e) {
        SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NOSESSION', $e);
}
 
try {
        if (!array_key_exists('REMOTE_USER', $_SERVER))
                throw new Exception('Apache environment variable REMOTE_USER was not available. Recheck your apache configuration.');


        $username = preg_replace('/^.+\\\/', '', $_SERVER['REMOTE_USER']);


        /* Escape any characters with a special meaning in LDAP. The following
         * characters have a special meaning (according to RFC 2253):
         * ',', '+', '"', '\', '<', '>', ';', '*'
         * These characters are escaped by prefixing them with '\'.
         */
        $ldapusername = addcslashes($username, ',+"\\<>;*');


        /*
         * Connecting to LDAP.
         */
        $ldap = new SimpleSAML_Auth_LDAP($ldapconfig->getValue('auth.ldap.hostname'),
                $ldapconfig->getValue('auth.ldap.enable_tls'));

        if($ldapconfig->getValue('auth.ldap.search.enable', FALSE)) {
                /* We are configured to search for the users dn. */

                $searchUsername = $ldapconfig->getValue('auth.ldap.search.username', NULL);

                if($searchUsername !== NULL) {
                        /* Log in with username & password for searching. */

                        $searchPassword = $ldapconfig->getValue('auth.ldap.search.password', NULL);
                        if($searchPassword === NULL) {
                                throw new Exception('"auth.ldap.search.username" is configured, but not' .
                                            ' "auth.ldap.search.password".');
                        }

                        if(!$ldap->bind($searchUsername, $searchPassword)) {
                                throw new Exception('Error authenticating using search username & password.');
                        }
                }

                $searchBase = $ldapconfig->getValue('auth.ldap.search.base', NULL);
                $searchAttributes = $ldapconfig->getValue('auth.ldap.search.attributes', NULL);
                if($searchBase === NULL || $searchAttributes === NULL) {
                        throw new Exception('"auth.ldap.search.base" and "auth.ldap.search.attributes"' .
                                ' must be configured before LDAP search can be enabled.');
                }

                /* Search for the dn. */
                $dn = $ldap->searchfordn($searchBase, $searchAttributes, $username, false, $ldapconfig->getValue('auth.ldap.search.filter', NULL));
        } else {
                /* We aren't configured to search for the dn. Insert the LDAP username into the pattern
                 * configured in the 'auth.ldap.dnpattern' option.
                 */
                $dn = str_replace('%username%', $ldapusername, $ldapconfig->getValue('auth.ldap.dnpattern'));
        }
                
        /*
         * Retrieve attributes from LDAP
         */
        $attributes = $ldap->getAttributes($dn, $ldapconfig->getValue('auth.ldap.attributes', null));

        if (array_key_exists('REMOTE_USER_TOKENS', $_SERVER)) {
                if ($_SERVER['REMOTE_USER_TOKENS']) {
                         $attributes[TOKENS_ATTR] = preg_split('/,/', $_SERVER['REMOTE_USER_TOKENS']);
                }
        }
        if (array_key_exists('REMOTE_USER_DATA', $_SERVER)) {
                if ($_SERVER['REMOTE_USER_DATA']) {
                         foreach (preg_split('/#/', $_SERVER['REMOTE_USER_DATA']) as $elt) {
                              list($attr, $values) = preg_split('/=/', $elt);
                              $attributes[$attr] = preg_split('/,/', $values);
                         }
                }
        }

        $attributes['seciossloginid'] = array($username);
        $attributes['seciosssystemid'] = array(preg_replace('/@.+$/', '', $username));
	if (preg_match('/@(.+)$/', $username, $matches)) {
        	$attributes['tenant'] = $matches[1];
	}
        SimpleSAML_Logger::info('AUTH - ldap: '. $username . ' successfully authenticated');

        $session->doLogin('login');
        $session->setAttributes($attributes);

	SimpleSAML_Logger::info('AUTH - env: '. $username . ' successfully authenticated');
	
	
	$session->setNameID(array(
		'value' => SimpleSAML_Utilities::generateID(),
		'Format' => 'urn:oasis:names:tc:SAML:2.0:nameid-format:transient'));
		
	/**
	 * Create a statistics log entry for every successfull login attempt.
	 * Also log a specific attribute as set in the config: statistics.authlogattr
	 */
	$authlogattr = $config->getValue('statistics.authlogattr', null);
	if ($authlogattr && array_key_exists($authlogattr, $attributes)) 
                SimpleSAML_Logger::stats('AUTH-env OK ' . $attributes[$authlogattr][0]);
	else 
                SimpleSAML_Logger::stats('AUTH-env OK');

} catch (Exception $e) {
        SimpleSAML_Utilities::fatalError($session->getTrackID(), 'CONFIG', $e);

}



?>
