<?php


require_once('../../www/_include.php');

define('TOKENS_ATTR', 'seciossallowedservice');

$config = SimpleSAML_Configuration::getInstance();
$metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
$session = SimpleSAML_Session::getInstance();

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');

/* Load the RelayState argument. The RelayState argument contains the address
 * we should redirect the user to after a successful authentication.
 */
if (!array_key_exists('RelayState', $_REQUEST)) {
        SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NORELAYSTATE');
}

$relaystate = $_REQUEST['RelayState'];

try {
        $protocol = $_REQUEST['protocol'];
        $authid = $_REQUEST['AuthId'];
        $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);
        } 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) {
                              if (preg_match('/^([^=]+)=(.+)$/', $elt, $matches)) {
                                  $attributes[$matches[1]] = preg_split('/,/', $matches[2]);
                              }
                         }
                }
        }

        if (isset($attributes['sn']) && isset($attributes['givenName']) && !isset($attributes['cn'])) {
            $attributes['cn'] = array($attributes['sn'][0].' '.$attributes['givenName'][0]);
        }
        if (isset($attributes['memberOf']) && is_array($attributes['memberOf'])) {
            $usergroups = array();
            $secgroups = array();
            for ($i = 0; $i < count($attributes['memberOf']); $i++) {
                if (preg_match('/^(.+),ou=(Groups|SecurityGroups),/i', $attributes['memberOf'][$i], $matches)) {
                    $elts = array();
                    foreach (preg_split('/, */', $matches[1]) as $elt) {
                        array_unshift($elts, preg_replace('/^[^=]+=/', '', $elt));
                    }
                    if (!strcasecmp($matches[2], 'SecurityGroups')) {
                        array_push($secgroups, join('/', $elts));
                    } else {
                        array_push($usergroups, join('/', $elts));
                    }
                }
            }
            $attributes['seciossUserGroup'] = $usergroups;
            $attributes['seciossSecurityGroup'] = $secgroups;
        }
        $attributes['seciossloginid'] = array($username);
        $attributes['seciosssystemid'] = array(preg_replace('/@.+$/', '', $username));
        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');
		

        $returnto = $_REQUEST['RelayState'];
        SimpleSAML_Utilities::redirect($returnto);	
	
	
} catch (Exception $e) {
        SimpleSAML_Utilities::fatalError($session->getTrackID(), 'CONFIG', $e);

}



?>
