/** * Build the array sent to GenericUser for use in Auth::user() * * @param adLDAP\adLDAP $infoCollection * @return array $info */ protected function setInfoArray($infoCollection) { /* * in app/auth.php set the fields array with each value * as a field you want from active directory * If you have 'user' => 'samaccountname' it will set the $info['user'] = $infoCollection->samaccountname * refer to the adLDAP docs for which fields are available. */ if (!empty($this->config['fields'])) { foreach ($this->config['fields'] as $k => $field) { if ($k == 'groups') { $info[$k] = $this->getAllGroups($infoCollection->memberof); } elseif ($k == 'primarygroup') { $info[$k] = $this->getPrimaryGroup($infoCollection->distinguishedname); } else { $info[$k] = $infoCollection->{$field}; } } } else { //if no fields array present default to username and displayName $info['username'] = $infoCollection->samaccountname; $info['displayname'] = $infoCollection->displayName; $info['primarygroup'] = $this->getPrimaryGroup($infoCollection->distinguishedname); $info['groups'] = $this->getAllGroups($infoCollection->memberof); } /* * I needed a user list to populate a dropdown * Set userlist to true in app/config/auth.php and set a group in app/config/auth.php as well * The table is the OU in Active directory you need a list of. */ if (!empty($this->config['userList'])) { $info['userlist'] = $this->ad->folder()->listing(array($this->config['group'])); } return $info; }
/** * Get all users with their LDAP fields * * @return Collection * @throws Exception */ public function getAllUsersWithFields() { //Get all users from LDAP $users = $this->getAllUsers(); $collection = new Collection([]); foreach ($users as $user) { $info = $this->adldap->user()->info($user, $this->fields)[0]; //If there is no displayname its probably a local account if (!isset($info['displayname'])) { continue; } //Add it to the collection $collection->push(new LdapUserObject($info, $this->fields)); } return $collection; }
/** * Create an organizational unit * * @param array $attributes Default attributes of the ou * @return bool */ public function create($attributes) { if (!is_array($attributes)) { return "Attributes must be an array"; } if (!is_array($attributes["container"])) { return "Container attribute must be an array."; } if (!array_key_exists("ou_name", $attributes)) { return "Missing compulsory field [ou_name]"; } if (!array_key_exists("container", $attributes)) { return "Missing compulsory field [container]"; } $attributes["container"] = array_reverse($attributes["container"]); $add = array(); $add["objectClass"] = "organizationalUnit"; $add["OU"] = $attributes['ou_name']; $containers = ""; if (count($attributes['container']) > 0) { $containers = "OU=" . implode(",OU=", $attributes["container"]) . ","; } $containers = "OU=" . implode(",OU=", $attributes["container"]); $result = ldap_add($this->adldap->getLdapConnection(), "OU=" . $add["OU"] . ", " . $containers . $this->adldap->getBaseDn(), $add); if ($result != true) { return false; } return true; }
/** * Get the last logon time of any user as a Unix timestamp * * @param string $username * @return long $unixTimestamp */ public function getLastLogon($username) { if (!$this->adldap->getLdapBind()) { return false; } if ($username === null) { return "Missing compulsory field [username]"; } $userInfo = $this->info($username, array("lastLogonTimestamp")); $lastLogon = adLDAPUtils::convertWindowsTimeToUnixTime($userInfo[0]['lastLogonTimestamp'][0]); return $lastLogon; }
/** * Returns a list of Databases within any given storage group in Exchange for a given mail server * * @param string $storageGroup The full DN of an Storage Group. You can use exchange_storage_groups() to find the DN * @param array $attributes An array of the AD attributes you wish to return * @return array */ public function storageDatabases($storageGroup, $attributes = array('cn', 'distinguishedname', 'displayname')) { if (!$this->adldap->getLdapBind()) { return false; } if ($storageGroup === NULL) { return "Missing compulsory field [storageGroup]"; } $filter = '(&(objectCategory=msExchPrivateMDB))'; $sr = @ldap_search($this->adldap->getLdapConnection(), $storageGroup, $filter, $attributes); $entries = @ldap_get_entries($this->adldap->getLdapConnection(), $sr); return $entries; }
/** * Convert DN string to array * * @param $dnStr * @param bool $excludeBaseDn exclude base DN from results * * @return array */ public function dnStrToArr($dnStr, $excludeBaseDn = true) { $dnArr = array(); if (!empty($dnStr)) { $tmpArr = explode(',', $dnStr); $baseDnArr = explode(',', $this->adldap->getBaseDn()); foreach ($tmpArr as $_tmpStr) { if ($excludeBaseDn && in_array($_tmpStr, $baseDnArr)) { continue; } $dnArr[] = substr($_tmpStr, strpos($_tmpStr, '=') + 1); } } return $dnArr; }
/** * Coping with AD not returning the primary group * http://support.microsoft.com/?kbid=321360 * * For some reason it's not possible to search on primarygrouptoken=XXX * If someone can show otherwise, I'd like to know about it :) * this way is resource intensive and generally a pain in the @#%^ * * @deprecated deprecated since version 3.1, see get get_primary_group * @param string $gid Group ID * @return bool|string */ public function cn($gid) { if ($gid === NULL) { return false; } $r = ''; $filter = "(&(objectCategory=group)(samaccounttype=" . adLDAP::ADLDAP_SECURITY_GLOBAL_GROUP . "))"; $fields = array("primarygrouptoken", "samaccountname", "distinguishedname"); $sr = ldap_search($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), $filter, $fields); $entries = ldap_get_entries($this->adldap->getLdapConnection(), $sr); for ($i = 0; $i < $entries["count"]; $i++) { if ($entries[$i]["primarygrouptoken"][0] == $gid) { $r = $entries[$i]["distinguishedname"][0]; $i = $entries["count"]; } } return $r; }
/** * Return list of groups (except domain and suffix). * * @param array $groups * * @return array */ protected function getAllGroups($groups) { $grps = ''; if (is_null($groups)) { return $grps; } if ($this->ad->getRecursiveGroups()) { return array_combine($groups, $groups); } if (!is_array($groups)) { $groups = explode(',', $groups); } foreach ($groups as $k => $group) { $splitGroups = explode(',', $group); foreach ($splitGroups as $splitGroup) { if (substr($splitGroup, 0, 3) == 'CN=') { $grps[substr($splitGroup, '3')] = substr($splitGroup, '3'); } } } return $grps; }
/** * Get the groups a computer is in * * @param string $computerName The name of the computer * @param null $recursive Whether to check recursively * @return array|bool */ public function groups($computerName, $recursive = NULL) { if ($computerName === NULL) { return false; } if ($recursive === NULL) { $recursive = $this->adldap->getRecursiveGroups(); } //use the default option if they haven't set it if (!$this->adldap->getLdapBind()) { return false; } //search the directory for their information $info = @$this->info($computerName, array("memberof", "primarygroupid")); $groups = $this->adldap->utilities()->niceNames($info[0]["memberof"]); //presuming the entry returned is our guy (unique usernames) if ($recursive === true) { foreach ($groups as $id => $groupName) { $extraGroups = $this->adldap->group()->recursiveGroups($groupName); $groups = array_merge($groups, $extraGroups); } } return $groups; }
<?php use adLDAP\adLDAP; /* Examples file To test any of the functions, just change the 0 to a 1. */ //error_reporting(E_ALL ^ E_NOTICE); include dirname(__FILE__) . '/../lib/adLDAP/adLDAP.php'; try { $adldap = new adLDAP($options); } catch (adLDAPException $e) { echo $e; exit; } //var_dump($ldap); echo "<pre>\n"; // authenticate a username/password if (0) { $result = $adldap->authenticate('username', 'password'); var_dump($result); } // add a group to a group if (0) { $result = $adldap->group()->addGroup('Parent Group Name', 'Child Group Name'); var_dump($result); } // add a user to a group if (0) { $result = $adldap->group()->addUser('Group Name', 'username');
/** * Mail enable a contact. Allows email to be sent to them through Exchange. * * @param $distinguishedName * @param $emailAddress * @param null $mailNickname * @return bool */ public function contactMailEnable($distinguishedName, $emailAddress, $mailNickname = NULL) { return $this->adldap->exchange()->contactMailEnable($distinguishedName, $emailAddress, $mailNickname); }
public function fetchData(adUser $adUser, TokenInterface $token, adLDAP $adLdap) { $connected = $adLdap->connect(); $isAD = $adLdap->authenticate($adUser->getUsername(), $token->getCredentials()); if (!$isAD || !$connected) { $msg = $this->translator->trans('ztec.security.active_directory.ad.bad_response', array('%connection_status%' => var_export($connected, 1), '%is_AD%' => var_export($isAD, 1))); throw new \Exception($msg); } /** @var adLDAPUserCollection $user */ $user = $adLdap->user()->infoCollection($adUser->getUsername()); //$userInfo = $adLdap->user_info($this->username); if ($user) { $groups = array(); //$allGroups = $adLdap->search_groups(ADLDAP_SECURITY_GLOBAL_GROUP,true); $groups = $adLdap->user()->groups($adUser->getUsername(), $this->recursiveGrouproles); /*if ($this->recursiveGrouproles == true) { // get recursive groups via adLdap $groups = $adLdap->user()->groups($adUser->getUsername(), true); } else { foreach ($user->memberOf as $k => $group) { if ($k !== 'count' && $group) { $reg = '#CN=([^,]*)#'; preg_match_all($reg, $group, $out); $groups[] = $out[1][0]; /* if(array_key_exists($out[1][0],$allGroups)){ $groups[$out[1][0]] = $allGroups[$out[1][0]]; }*/ /*} } }*/ /** End Fetching */ $sfRoles = array(); $sfRolesTemp = array(); foreach ($groups as $r) { if (in_array($r, $sfRolesTemp) === false) { $sfRoles[] = 'ROLE_' . strtoupper(str_replace(' ', '_', $r)); $sfRolesTemp[] = $r; } } $adUser->setRoles($sfRoles); unset($sfRolesTemp); $adUser->setDisplayName($user->displayName); $adUser->setEmail($user->mail); return true; } }
public function authenticate($username, $password) { return $this->adServer->authenticate($username, $password); }
/** * @param Authenticatable $user * @param array $credentials * @return bool */ public function validateCredentials(Authenticatable $user, array $credentials) { $username = $credentials['username']; $password = $credentials['password']; return $this->adldap->authenticate($username, $password); }
/** * Validates the credentials against the configured LDAP/AD server. * The credentials are passed in an array with the keys 'username' * and 'password'. * * @param array $credentials The credentials to validate. * @return boolean */ private function validateLDAPCredentials(array $credentials) { $credentialsValidated = false; $adldap = false; try { $userPassword = $credentials['password']; $userName = $credentials['username']; $ldapConOp = $this->GetLDAPConnectionOptions(); // // Set LDAP debug log level - useful in DEV, dangerous in PROD!! // ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7); // Try to authenticate using AD/LDAP $adldap = new adLDAP($ldapConOp); $authUser = $adldap->user()->authenticate($userName, $userPassword); // If the user got authenticated if ($authUser == true) { $credentialsValidated = true; } else { $this->handleLDAPError($adldap); $credentialsValidated = false; } } catch (\Exception $ex) { Log::error('Exception validating LDAP credential for user: '******', Exception message: ' . $ex->getMessage()); Log::error($ex->getTraceAsString()); $this->handleLDAPError($adldap); $credentialsValidated = false; } if (isset($adldap)) { $adldap->close(); unset($adldap); } return $credentialsValidated; }
<?php use adLDAP\adLDAP; /* Examples file To test any of the functions, just change the 0 to a 1. */ //error_reporting(E_ALL ^ E_NOTICE); include dirname(__FILE__) . "/../lib/adLDAP/adLDAP.php"; try { $adldap = new adLDAP($options); } catch (adLDAPException $e) { echo $e; exit; } //var_dump($ldap); echo "<pre>\n"; // authenticate a username/password if (0) { $result = $adldap->authenticate("username", "password"); var_dump($result); } // add a group to a group if (0) { $result = $adldap->group()->addGroup("Parent Group Name", "Child Group Name"); var_dump($result); } // add a user to a group if (0) { $result = $adldap->group()->addUser("Group Name", "username");
/** * Finds GUID by DN * * @param adLDAP $adLdap * @param string $dn * @return null */ protected function findManagerGUID(adLDAP $adLdap, $dn = '') { if (!empty($dn)) { $filter = '(' . '&(objectClass=user)' . '(samaccounttype=' . adLDAP::ADLDAP_NORMAL_ACCOUNT . ')' . '(objectCategory=person)(distinguishedname=' . $dn . ')' . ')'; $sr = ldap_search($adLdap->getLdapConnection(), $adLdap->getBaseDn(), $filter, ['objectGUID']); $entries = ldap_get_entries($adLdap->getLdapConnection(), $sr); if (isset($entries['count']) && $entries['count'] > 0) { return $adLdap->utilities()->decodeGuid($entries[0]['objectguid'][0]); } } return null; }
} require_once __DIR__ . '/../vendor/autoload.php'; use adLDAP\adLDAP; use adLDAP\Exceptions\adLDAPException; $options = ['account_suffix' => '', 'base_dn' => null, 'domain_controllers' => [''], 'admin_username' => null, 'admin_password' => null, 'real_primarygroup' => '', 'use_ssl' => false, 'use_tls' => false, 'recursive_groups' => true, 'ad_port' => adLDAP::ADLDAP_LDAP_PORT, 'sso' => '']; foreach ($options as $optName => $defaultValue) { if (isset($_POST[$optName])) { $options[$optName] = $_POST[$optName]; } } $options['domain_controllers'] = array_filter($options['domain_controllers']); $adldap = false; $exception = false; if (is_array($options['domain_controllers']) && !empty($options['domain_controllers'][0])) { try { $adldap = new adLDAP($options); $options['base_dn'] = $adldap->getBaseDn(); $options['ad_port'] = $adldap->getPort(); } catch (adLDAPException $e) { $exception = $e; } } $username = !empty($_POST['username']) ? $_POST['username'] : ''; $info = false; if ($adldap && !empty($username)) { $password = $_POST['password']; try { $adldap->authenticate($username, $password); $info = $adldap->user()->info($username, ['*']); if (isset($info[0])) { $info = $info[0];