3 * Name: LDAP Authenticate
4 * Description: Authenticate a user against an LDAP directory
6 * Author: Mike Macgirvin <http://macgirvin.com/profile/mike>
12 * Module: LDAP Authenticate
14 * Authenticate a user against an LDAP directory
15 * Useful for Windows Active Directory and other LDAP-based organisations
16 * to maintain a single password across the organisation.
18 * Optionally authenticates only if a member of a given group in the directory.
20 * The person must have registered with Friendica using the normal registration
21 * procedures in order to have a Friendica user record, contact, and profile.
23 * Note when using with Windows Active Directory: you may need to set TLS_CACERT in your site
24 * ldap.conf file to the signing cert for your LDAP server.
26 * The required configuration options for this module may be set in the .htconfig.php file
29 * $a->config['ldapauth']['ldap_server'] = 'host.example.com';
36 function ldapauth_install() {
37 register_hook('authenticate', 'addon/ldapauth/ldapauth.php', 'ldapauth_hook_authenticate');
41 function ldapauth_uninstall() {
42 unregister_hook('authenticate', 'addon/ldapauth/ldapauth.php', 'ldapauth_hook_authenticate');
46 function ldapauth_hook_authenticate($a,&$b) {
47 if(ldapauth_authenticate($b['username'],$b['password'])) {
48 $results = q("SELECT * FROM `user` WHERE `nickname` = '%s' AND `blocked` = 0 AND `verified` = 1 LIMIT 1",
52 $b['user_record'] = $results[0];
53 $b['authenticated'] = 1;
60 function ldapauth_authenticate($username,$password) {
62 $ldap_server = get_config('ldapauth','ldap_server');
63 $ldap_binddn = get_config('ldapauth','ldap_binddn');
64 $ldap_bindpw = get_config('ldapauth','ldap_bindpw');
65 $ldap_searchdn = get_config('ldapauth','ldap_searchdn');
66 $ldap_userattr = get_config('ldapauth','ldap_userattr');
67 $ldap_group = get_config('ldapauth','ldap_group');
69 if(! ((strlen($password))
70 && (function_exists('ldap_connect'))
71 && (strlen($ldap_server))))
74 $connect = @ldap_connect($ldap_server);
79 @ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION,3);
80 @ldap_set_option($connect, LDAP_OPT_REFERRALS, 0);
81 if((@ldap_bind($connect,$ldap_binddn,$ldap_bindpw)) === false) {
85 $res = @ldap_search($connect,$ldap_searchdn, $ldap_userattr . '=' . $username);
91 $id = @ldap_first_entry($connect,$res);
97 $dn = @ldap_get_dn($connect,$id);
99 if(! @ldap_bind($connect,$dn,$password))
102 if(! strlen($ldap_group))
105 $r = @ldap_compare($connect,$ldap_group,'member',$dn);
107 $err = @ldap_error($connect);
108 $eno = @ldap_errno($connect);
109 @ldap_close($connect);
112 logger("ldapauth: access control group Does Not Exist");
115 elseif ($eno === 16) {
116 logger('ldapauth: membership attribute does not exist in access control group');
120 logger('ldapauth: error: ' . $err);
124 elseif ($r === false) {
125 @ldap_close($connect);