deleted plugin `AuthLDAP` version 2.3.1

This commit is contained in:
KawaiiPunk 2020-07-24 14:09:00 +00:00 committed by Gitium
parent fa69c9daa6
commit 3f0f8d3ac9
40 changed files with 0 additions and 2860 deletions

View File

@ -1,83 +0,0 @@
dn: dc=test space,{{ LDAP_BASE_DN }}
changetype: add
dc: test space
description: LDAP Example with space
objectClass: dcObject
objectClass: organization
o: test space
dn: cn=Manager,{{ LDAP_BASE_DN }}
changetype: add
cn: Manager
objectClass: organizationalRole
dn: ou=test,{{ LDAP_BASE_DN }}
changetype: add
objectClass: organizationalUnit
ou: test
dn: uid=user1,{{ LDAP_BASE_DN }}
changetype: add
objectClass: account
objectClass: simpleSecurityObject
uid: user1
userPassword: user1
dn: cn=group1,{{ LDAP_BASE_DN }}
changetype: add
objectclass: groupOfUniqueNames
cn: group1
uniqueMember: uid=user1,{{ LDAP_BASE_DN }}
dn: uid=user2,{{ LDAP_BASE_DN }}
changetype: add
objectClass: account
objectClass: simpleSecurityObject
uid: user2
userPassword: user2
dn: cn=group2,{{ LDAP_BASE_DN }}
changetype: add
objectclass: groupOfUniqueNames
cn: group2
uniqueMember: uid=user2,{{ LDAP_BASE_DN }}
dn: uid=user3,{{ LDAP_BASE_DN }}
changetype: add
objectClass: account
objectClass: simpleSecurityObject
uid: user3
userPassword: user!"
dn: cn=group3,{{ LDAP_BASE_DN }}
changetype: add
objectclass: groupOfUniqueNames
cn: group3
uniqueMember: uid=user2,{{ LDAP_BASE_DN }}
uniqueMember: uid=user3,{{ LDAP_BASE_DN }}
dn: uid=user 4,{{ LDAP_BASE_DN }}
changetype: add
objectClass: account
objectClass: simpleSecurityObject
uid: user 4
userPassword: user!"
dn: cn=group4,{{ LDAP_BASE_DN }}
changetype: add
objectclass: groupOfUniqueNames
cn: group4
uniqueMember: uid=user 4,{{ LDAP_BASE_DN }}
dn: uid=user 5,dc=test space,{{ LDAP_BASE_DN }}
changetype: add
objectClass: account
objectClass: simpleSecurityObject
uid: user 5
userPassword: user!"
dn: cn=group5,{{ LDAP_BASE_DN }}
changetype: add
objectclass: groupOfUniqueNames
cn: group5
uniqueMember: uid=user 5,dc=test space,{{ LDAP_BASE_DN }}

View File

@ -1,42 +0,0 @@
##
# Global Directives
##
# Schema and objectClass definitions
include /etc/ldap/schema/core.schema
include /etc/ldap/schema/cosine.schema
include /etc/ldap/schema/nis.schema
include /etc/ldap/schema/inetorgperson.schema
moduleload back_hdb
disallow bind_anon
##
# Test DB
##
database hdb
suffix "dc=example,dc=com"
rootdn "cn=Manager,dc=example,dc=com"
rootpw insecure
# The database directory MUST exist prior to running slapd AND
# change path as necessary
directory /tmp/ldap_db/
##
# ACL
##
# The userPassword by default can be changed
# by the entry owning it if they are authenticated.
# Others should not be able to see it, except the
# admin entry below
# These access lines apply to database #1 only
access to attrs=userPassword,shadowLastChange
by anonymous auth
by self write
by * none

View File

@ -1,16 +0,0 @@
#!/usr/bin/env bash
DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
LDAP_DB=/tmp/ldap_db
echo "Creating database directory"
rm -rf ${LDAP_DB} && mkdir ${LDAP_DB} && cp /usr/share/doc/slapd/examples/DB_CONFIG ${LDAP_DB}
echo "Launching OpenLDAP ..."
# Start slapd with non root privileges
slapd -h "ldap://0.0.0.0:3890/" -f ${DIR}/OpenLDAP/slapd.conf
# Wait for LDAP to start
sleep 1

View File

@ -1,6 +0,0 @@
dn: dc=example,dc=com
dc: example
description: LDAP Example
objectClass: dcObject
objectClass: organization
o: example

View File

@ -1,6 +0,0 @@
dn: dc=test space,dc=example,dc=com
dc: test space
description: LDAP Example with space
objectClass: dcObject
objectClass: organization
o: test space

View File

@ -1,3 +0,0 @@
dn: cn=Manager,dc=example,dc=com
cn: Manager
objectClass: organizationalRole

View File

@ -1,3 +0,0 @@
dn: ou=test,dc=example,dc=com
objectClass: organizationalUnit
ou: test

View File

@ -1,5 +0,0 @@
dn: uid=user1,dc=example,dc=com
objectClass: account
objectClass: simpleSecurityObject
uid: user1
userPassword: user1

View File

@ -1,16 +0,0 @@
dn: cn=group1,dc=example,dc=com
objectclass: groupOfUniqueNames
cn: group1
uniqueMember: uid=user1,dc=example,dc=com
dn: uid=user2,dc=example,dc=com
objectClass: account
objectClass: simpleSecurityObject
uid: user2
userPassword: user2
dn: cn=group2,dc=example,dc=com
objectclass: groupOfUniqueNames
cn: group2
uniqueMember: uid=user2,dc=example,dc=com

View File

@ -1,14 +0,0 @@
dn: cn=group3,dc=example,dc=com
objectclass: groupOfUniqueNames
cn: group3
uniqueMember: uid=user2,dc=example,dc=com
uniqueMember: uid=user3,dc=example,dc=com
dn: uid=user3,dc=example,dc=com
objectClass: account
objectClass: simpleSecurityObject
uid: user3
userPassword: user!"

View File

@ -1,13 +0,0 @@
dn: cn=group4,dc=example,dc=com
objectclass: groupOfUniqueNames
cn: group4
uniqueMember: uid=user 4,dc=example,dc=com
dn: uid=user 4,dc=example,dc=com
objectClass: account
objectClass: simpleSecurityObject
uid: user 4
userPassword: user!"

View File

@ -1,13 +0,0 @@
dn: cn=group5,dc=example,dc=com
objectclass: groupOfUniqueNames
cn: group5
uniqueMember: uid=user 5,dc=test space,dc=example,dc=com
dn: uid=user 5,dc=test space,dc=example,dc=com
objectClass: account
objectClass: simpleSecurityObject
uid: user 5
userPassword: user!"

View File

@ -1,13 +0,0 @@
#!/usr/bin/env bash
DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
FIXTURES_DIR="$DIR/ldif"
load_fixture () {
ldapadd -x -H ldap://127.0.0.1:3890/ -D "cn=Manager,dc=example,dc=com" -w insecure -f $1
}
for FIXTURE in `ls ${FIXTURES_DIR}`
do
load_fixture "${FIXTURES_DIR}/${FIXTURE}"
done;

View File

@ -1 +0,0 @@
extension=ldap.so

View File

@ -1,3 +0,0 @@
vendor
composer.lock
.svnAccess

View File

@ -1,26 +0,0 @@
svn
build.xml
tests
VERSION
Vagrantfile
phpunit.*
composer.*
vendor
tests
report*
build
bin
*~
.*
.gitignore
.travis*
composer.json
docker-compose-mu.yml
patchcoverage
phpunit*
tests
wp-app
wp-data
dockersetup
config
docker-compose.yml

View File

@ -1,2 +0,0 @@
username = svnUsername
password = svnPassword

View File

@ -1,6 +0,0 @@
set -x
if [ "$TRAVIS_PHP_VERSION" = '5.6' ] ; then
./vendor/bin/test-reporter --stdout > codeclimate.json
curl -X POST -d @codeclimate.json -H "Content-Type: application/json" -H "User-Agent: Code Climate (PHP Test Reporter v1.0.1-dev)" https://codeclimate.com/test_reports
php vendor/bin/coveralls
fi

View File

@ -1,9 +0,0 @@
set -x
if [ "$TRAVIS_PHP_VERSION" = 'hhvm' ] || [ "$TRAVIS_PHP_VERSION" = 'hhvm-nightly' ] ; then
curl -sS https://getcomposer.org/installer > composer-installer.php
hhvm composer-installer.php
hhvm -v ResourceLimit.SocketDefaultTimeout=30 -v Http.SlowQueryThreshold=30000 composer.phar update --prefer-source
else
composer self-update
composer update --prefer-source
fi

View File

@ -1,42 +0,0 @@
# Travic-CI-Config file for authLdap
#
language: php
addons:
apt:
packages:
- slapd
- ldap-utils
matrix:
fast_finish: true
include:
- php: 5.4
- php: 5.5
- php: 5.6
- php: 7.0
- php: 7.1
- php: 7.2
- php: 7.3
- php: hhvm
- php: nightly
allow_failures:
- php: 5.4
- php: 5.5
- php: nightly
- php: hhvm
before_script:
- ./.travis.install.sh
- phpenv config-add .ci/php.ini || return 0
- .ci/OpenLDAP_run.sh
- .ci/load_fixtures.sh
- composer dumpautoload
script:
# - ./vendor/bin/phpcs --standard=PSR2 ldap.php authLdap.php tests/
- ./vendor/bin/phpunit --configuration=phpunit.travis.xml
after_script:
- ./.travis.after.sh

View File

@ -1,7 +0,0 @@
Copyright <YEAR> <COPYRIGHT HOLDER>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -1,95 +0,0 @@
# authLDAP
[![Join the chat at https://gitter.im/heiglandreas/authLdap](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/heiglandreas/authLdap?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
Use your existing LDAP as authentication-backend for your wordpress!
[![Build Status](https://travis-ci.org/heiglandreas/authLdap.svg?branch=master)](https://travis-ci.org/heiglandreas/authLdap)
[![WordPress Stats](https://img.shields.io/wordpress/plugin/dt/authldap.svg)](https://wordpress.org/plugins/authldap/stats/)
[![WordPress Version](https://img.shields.io/wordpress/plugin/v/authldap.svg)](https://wordpress.org/plugins/authldap/)
[![WordPress testet](https://img.shields.io/wordpress/v/authldap.svg)](https://wordpress.org/plugins/authldap/)
[![Code Climate](https://codeclimate.com/github/heiglandreas/authLdap/badges/gpa.svg)](https://codeclimate.com/github/heiglandreas/authLdap)
[![Test Coverage](https://codeclimate.com/github/heiglandreas/authLdap/badges/coverage.svg)](https://codeclimate.com/github/heiglandreas/authLdap)
So what are the differences to other Wordpress-LDAP-Authentication-Plugins?
* **Flexible**: You are totaly free in which LDAP-backend to use. Due to the extensive configuration you can
freely decide how to do the authentication of your users. It simply depends on your
filters
* **Independent**: As soon as a user logs in, it is added/updated to the Wordpress' user-database
to allow wordpress to always use the correct data. You only have to administer your users once.
* **Failsafe**: Due to the users being created in Wordpress' User-database they can
also log in when the LDAP-backend currently is gone.
* **Role-Aware**: You can map Wordpress' roles to values of an existing LDAP-attribute.
## How does the plugin work?
Well, as a matter of fact it is rather simple. The plugin verifies, that the user
seeking authentification can bind to the LDAP using the provided password.
If that is so, the user is either created or updated in the wordpress-user-database.
This update includes the provided password (so the wordpress can authenticate users
even without the LDAP), the users name according to the authLDAP-preferences and
the status of the user depending on the groups-settings of the authLDAP-preferences
Writing this plugin would not have been as easy as it has been, without the
wonderfull plugin of Alistair Young from http://www.weblogs.uhi.ac.uk/sm00ay/?p=45
## Configuration
### Usage Settings
* **Enable Authentication via LDAP** Whether you want to enable authLdap for login or not
* **debug authLdap** When you have problems with authentication via LDAP you can enable a debugging mode here.
* **Save entered Password** Decide whether passwords will be cached in your wordpress-installation. **Attention:** Without the cache your users will not be able to log into your site when your LDAP is down!
### Server Settings
* **LDAP Uri** This is the URI where your ldap-backend can be reached. More information are actually on the Configuration page
* **Filter** This is the real McCoy! The filter you define here specifies how a user will be found. Before applying the filter a %s will be replaced with the given username. This means, when a user logs in using foobar as username the following happens:
* **uid=%1$s** check for any LDAP-Entry that has an attribute uid with value foobar
* **(&(objectclass=posixAccount)(|(uid=%1$s)(mail=%1$s)))** check for any LDAP-Entry that has an attribute objectclass with value posixAccout and either a UID- or a mail-attribute with value foobar
This filter is rather powerfull if used wisely.
### Creating Users
* **Name-Attribute** Which Attribute from the LDAP contains the Full or the First name of the user trying to log in. This defaults to name
* **Second Name Attribute** If the above Name-Attribute only contains the First Name of the user you can here specify an Attribute that contains the second name. This field is empty by default
* **User-ID Attribute** This field will be used as login-name for wordpress. Please give the Attribute, that is used to identify the user. This should be the same as you used in the above Filter-Option. This field defaults to uid
* **Mail Attribute** Which Attribute holds the eMail-Address of the user? If more than one eMail-Address are stored in the LDAP, only the first given is used. This field defaults to mail
* **Web-Attribute** If your users have a personal page (URI) stored in the LDAP, it can be provided here. This field is empty by default
### User-Groups for Roles
* **Group-Attribute** This is the attribute that defines the Group-ID that can be matched against the Groups defined further down This field defaults to gidNumber.
* **Group-Filter** Here you can add the filter for selecting groups for the currentlly logged in user The Filter should contain the string %s which will be replaced by the login-name of the currently logged in
## FAQ
<dl>
<dt>Can I change a users password with this plugin?</dt>
<dd>Short Answer: <strong>No</strong>!<br>Long Answer: As the users credentials are not
only used for a wordpress-site when you authenticate against an LDAP but for
many other services also chances are great that there is a centralized place
where password-changes shall be made. We'll later allow inclusion of a link
to such a place but currently it's not available. And as password-hashing and
where to store it requires deeper insight into the LDAP-Server then most users
have and admins are willing to give, password changes are out of scope of this
plugin. If you know exactyl what you do, you might want to have a look at
<a href="https://github.com/heiglandreas/authLdap/issues/54#issuecomment-125851029">
issue 54</a>
wherer a way of adding it is described!
</dd>
<dt>Can I add a user to the LDAP when she creates a user-account on wordpress?</dt>
<dd>Short Answer: <strong>No</strong>!<br>Long Answer: Even though that is technically possible
it's not in the scope of this plugin. As creating a user in an LDAP often involves
an administrative process that has already been implemented in your departments
administration it doesn't make sense to rebuild that - in most cases highly
individual - process in this plugin. If you know exactly what you do, have a look at
<a href="https://github.com/heiglandreas/authLdap/issues/65">issue 65</a>
where <a href="https://github.com/wtfiwtz">wtfiwtz</a> shows how to implement that feature.
</dd>
</dl>

View File

@ -1 +0,0 @@
2.3.1

View File

@ -1,28 +0,0 @@
# -*- mode: ruby -*-
# vi: set ft=ruby :
$install_ldap = <<SCRIPT
export DEBIAN_FRONTEND=noninteractive
apt-get -yq update
apt-get -yq --no-install-suggests --no-install-recommends --force-yes install slapd ldap-utils apparmor-utils
sudo aa-complain /usr/sbin/slapd
SCRIPT
$setup_vagrant_user_environment = <<SCRIPT
if ! grep "cd /vagrant" /home/vagrant/.profile > /dev/null; then
echo "cd /vagrant" >> /home/vagrant/.profile
fi
SCRIPT
Vagrant.configure(2) do |config|
config.vm.box = 'bento/ubuntu-14.04'
config.vm.box_check_update = false
# LDAP port
config.vm.network 'forwarded_port', guest: 3890, host: 3890
config.vm.provision 'shell', inline: $install_ldap
config.vm.provision 'shell', privileged: false, inline: '/vagrant/.ci/OpenLDAP_run.sh', :run => 'always'
config.vm.provision 'shell', privileged: false, inline: '/vagrant/.ci/load_fixtures.sh', :run => 'always'
config.vm.provision 'shell', inline: $setup_vagrant_user_environment
end

View File

@ -1,9 +0,0 @@
.row {
overflow: hidden;
padding-top: 10px;
}
.element {
float: right;
text-align: left;
}

View File

@ -1,835 +0,0 @@
<?php
/*
Plugin Name: AuthLDAP
Plugin URI: https://github.com/heiglandreas/authLdap
Description: This plugin allows you to use your existing LDAP as authentication base for WordPress
Version: 2.3.1
Author: Andreas Heigl <andreas@heigl.org>
Author URI: http://andreas.heigl.org
License: MIT
License URI: https://opensource.org/licenses/MIT
*/
require_once dirname(__FILE__) . '/ldap.php';
function authLdap_debug($message)
{
if (authLdap_get_option('Debug')) {
error_log('[AuthLDAP] ' . $message, 0);
}
}
function authLdap_addmenu()
{
if (! is_multisite()) {
add_options_page('AuthLDAP', 'AuthLDAP', 'manage_options', basename(__FILE__), 'authLdap_options_panel');
} else {
add_submenu_page('settings.php', 'AuthLDAP', 'AuthLDAP', 'manage_options', 'authldap', 'authLdap_options_panel');
}
}
function authLdap_get_post($name, $default = '')
{
return isset($_POST[$name]) ? $_POST[$name] : $default;
}
function authLdap_options_panel()
{
// inclusde style sheet
wp_enqueue_style('authLdap-style', plugin_dir_url(__FILE__) . 'authLdap.css');
if (($_SERVER['REQUEST_METHOD'] == 'POST') && array_key_exists('ldapOptionsSave', $_POST)) {
$new_options = array(
'Enabled' => authLdap_get_post('authLDAPAuth', false),
'CachePW' => authLdap_get_post('authLDAPCachePW', false),
'URI' => authLdap_get_post('authLDAPURI'),
'URISeparator' => authLdap_get_post('authLDAPURISeparator'),
'StartTLS' => authLdap_get_post('authLDAPStartTLS', false),
'Filter' => authLdap_get_post('authLDAPFilter'),
'NameAttr' => authLdap_get_post('authLDAPNameAttr'),
'SecName' => authLdap_get_post('authLDAPSecName'),
'UidAttr' => authLdap_get_post('authLDAPUidAttr'),
'MailAttr' => authLdap_get_post('authLDAPMailAttr'),
'WebAttr' => authLdap_get_post('authLDAPWebAttr'),
'Groups' => authLdap_get_post('authLDAPGroups', array()),
'GroupSeparator'=> authLdap_get_post('authLDAPGroupSeparator', ','),
'Debug' => authLdap_get_post('authLDAPDebug', false),
'GroupBase' => authLdap_get_post('authLDAPGroupBase'),
'GroupAttr' => authLdap_get_post('authLDAPGroupAttr'),
'GroupFilter' => authLdap_get_post('authLDAPGroupFilter'),
'DefaultRole' => authLdap_get_post('authLDAPDefaultRole'),
'GroupEnable' => authLdap_get_post('authLDAPGroupEnable', false),
'GroupOverUser' => authLdap_get_post('authLDAPGroupOverUser', false),
'DoNotOverwriteNonLdapUsers' => authLdap_get_post('authLDAPDoNotOverwriteNonLdapUsers', false),
);
if (authLdap_set_options($new_options)) {
echo "<div class='updated'><p>Saved Options!</p></div>";
} else {
echo "<div class='error'><p>Could not save Options!</p></div>";
}
}
// Do some initialization for the admin-view
$authLDAP = authLdap_get_option('Enabled');
$authLDAPCachePW = authLdap_get_option('CachePW');
$authLDAPURI = authLdap_get_option('URI');
$authLDAPURISeparator = authLdap_get_option('URISeparator');
$authLDAPStartTLS = authLdap_get_option('StartTLS');
$authLDAPFilter = authLdap_get_option('Filter');
$authLDAPNameAttr = authLdap_get_option('NameAttr');
$authLDAPSecName = authLdap_get_option('SecName');
$authLDAPMailAttr = authLdap_get_option('MailAttr');
$authLDAPUidAttr = authLdap_get_option('UidAttr');
$authLDAPWebAttr = authLdap_get_option('WebAttr');
$authLDAPGroups = authLdap_get_option('Groups');
$authLDAPGroupSeparator= authLdap_get_option('GroupSeparator');
$authLDAPDebug = authLdap_get_option('Debug');
$authLDAPGroupBase = authLdap_get_option('GroupBase');
$authLDAPGroupAttr = authLdap_get_option('GroupAttr');
$authLDAPGroupFilter = authLdap_get_option('GroupFilter');
$authLDAPDefaultRole = authLdap_get_option('DefaultRole');
$authLDAPGroupEnable = authLdap_get_option('GroupEnable');
$authLDAPGroupOverUser = authLdap_get_option('GroupOverUser');
$authLDAPDoNotOverwriteNonLdapUsers = authLdap_get_option('DoNotOverwriteNonLdapUsers');
$tChecked = ($authLDAP) ? ' checked="checked"' : '';
$tDebugChecked = ($authLDAPDebug) ? ' checked="checked"' : '';
$tPWChecked = ($authLDAPCachePW) ? ' checked="checked"' : '';
$tGroupChecked = ($authLDAPGroupEnable) ? ' checked="checked"' : '';
$tGroupOverUserChecked = ($authLDAPGroupOverUser) ? ' checked="checked"' : '';
$tStartTLSChecked = ($authLDAPStartTLS) ? ' checked="checked"' : '';
$tDoNotOverwriteNonLdapUsers = ($authLDAPDoNotOverwriteNonLdapUsers) ? ' checked="checked"' : '';
$roles = new WP_Roles();
$action = $_SERVER['REQUEST_URI'];
if (! extension_loaded('ldap')) {
echo '<div class="warning">The LDAP-Extension is not available on your '
. 'WebServer. Therefore Everything you can alter here does not '
. 'make any sense!</div>';
}
include dirname(__FILE__) . '/view/admin.phtml';
}
/**
* get a LDAP server object
*
* throws exception if there is a problem connecting
*
* @conf boolean authLDAPDebug true, if debugging should be turned on
* @conf string authLDAPURI LDAP server URI
*
* @return Org_Heigl\AuthLdap\LDAP LDAP server object
*/
function authLdap_get_server()
{
static $_ldapserver = null;
if (is_null($_ldapserver)) {
$authLDAPDebug = authLdap_get_option('Debug');
$authLDAPURI = explode(
authLdap_get_option('URISeparator', ' '),
authLdap_get_option('URI')
);
$authLDAPStartTLS = authLdap_get_option('StartTLS');
//$authLDAPURI = 'ldap:/foo:bar@server/trallala';
authLdap_debug('connect to LDAP server');
require_once dirname(__FILE__) . '/src/LdapList.php';
$_ldapserver = new \Org_Heigl\AuthLdap\LdapList();
foreach ($authLDAPURI as $uri) {
$_ldapserver->addLdap(new \Org_Heigl\AuthLdap\LDAP($uri, $authLDAPDebug, $authLDAPStartTLS));
}
}
return $_ldapserver;
}
/**
* This method authenticates a user using either the LDAP or, if LDAP is not
* available, the local database
*
* For this we store the hashed passwords in the WP_Database to ensure working
* conditions even without an LDAP-Connection
*
* @param null|WP_User|WP_Error
* @param string $username
* @param string $password
* @param boolean $already_md5
* @return boolean true, if login was successfull or false, if it wasn't
* @conf boolean authLDAP true, if authLDAP should be used, false if not. Defaults to false
* @conf string authLDAPFilter LDAP filter to use to find correct user, defaults to '(uid=%s)'
* @conf string authLDAPNameAttr LDAP attribute containing user (display) name, defaults to 'name'
* @conf string authLDAPSecName LDAP attribute containing second name, defaults to ''
* @conf string authLDAPMailAttr LDAP attribute containing user e-mail, defaults to 'mail'
* @conf string authLDAPUidAttr LDAP attribute containing user id (the username we log on with), defaults to 'uid'
* @conf string authLDAPWebAttr LDAP attribute containing user website, defaults to ''
* @conf string authLDAPDefaultRole default role for authenticated user, defaults to ''
* @conf boolean authLDAPGroupEnable true, if we try to map LDAP groups to Wordpress roles
* @conf boolean authLDAPGroupOverUser true, if LDAP Groups have precedence over existing user roles
*/
function authLdap_login($user, $username, $password, $already_md5 = false)
{
// don't do anything when authLDAP is disabled
if (! authLdap_get_option('Enabled')) {
authLdap_debug('LDAP disabled in AuthLDAP plugin options (use the first option in the AuthLDAP options to enable it)');
return $user;
}
// If the user has already been authenticated (only in that case we get a
// WP_User-Object as $user) we skip LDAP-authentication and simply return
// the existing user-object
if ($user instanceof WP_User) {
authLdap_debug(sprintf(
'User %s has already been authenticated - skipping LDAP-Authentication',
$user->get('nickname')));
return $user;
}
authLdap_debug("User '$username' logging in");
if ($username == 'admin') {
authLdap_debug('Doing nothing for possible local user admin');
return $user;
}
global $wpdb, $error;
try {
$authLDAP = authLdap_get_option('Enabled');
$authLDAPFilter = authLdap_get_option('Filter');
$authLDAPNameAttr = authLdap_get_option('NameAttr');
$authLDAPSecName = authLdap_get_option('SecName');
$authLDAPMailAttr = authLdap_get_option('MailAttr');
$authLDAPUidAttr = authLdap_get_option('UidAttr');
$authLDAPWebAttr = authLdap_get_option('WebAttr');
$authLDAPDefaultRole = authLdap_get_option('DefaultRole');
$authLDAPGroupEnable = authLdap_get_option('GroupEnable');
$authLDAPGroupOverUser = authLdap_get_option('GroupOverUser');
if (! $username) {
authLdap_debug('Username not supplied: return false');
return false;
}
if (! $password) {
authLdap_debug('Password not supplied: return false');
$error = __('<strong>Error</strong>: The password field is empty.');
return false;
}
// First check for valid values and set appropriate defaults
if (! $authLDAPFilter) {
$authLDAPFilter = '(uid=%s)';
}
if (! $authLDAPNameAttr) {
$authLDAPNameAttr = 'name';
}
if (! $authLDAPMailAttr) {
$authLDAPMailAttr = 'mail';
}
if (! $authLDAPUidAttr) {
$authLDAPUidAttr = 'uid';
}
// If already_md5 is TRUE, then we're getting the user/password from the cookie. As we don't want to store LDAP passwords in any
// form, we've already replaced the password with the hashed username and LDAP_COOKIE_MARKER
if ($already_md5) {
if ($password == md5($username).md5($ldapCookieMarker)) {
authLdap_debug('cookie authentication');
return true;
}
}
// Remove slashes as noted on https://github.com/heiglandreas/authLdap/issues/108
$password = stripslashes_deep($password);
// No cookie, so have to authenticate them via LDAP
$result = false;
try {
authLdap_debug('about to do LDAP authentication');
$result = authLdap_get_server()->Authenticate($username, $password, $authLDAPFilter);
} catch (Exception $e) {
authLdap_debug('LDAP authentication failed with exception: ' . $e->getMessage());
return false;
}
// Rebind with the default credentials after the user has been loged in
// Otherwise the credentials of the user trying to login will be used
// This fixes #55
authLdap_get_server()->bind();
if (true !== $result) {
authLdap_debug('LDAP authentication failed');
// TODO what to return? WP_User object, true, false, even an WP_Error object... all seem to fall back to normal wp user authentication
return;
}
authLdap_debug('LDAP authentication successfull');
$attributes = array_values(
array_filter(
array(
$authLDAPNameAttr,
$authLDAPSecName,
$authLDAPMailAttr,
$authLDAPWebAttr,
$authLDAPUidAttr
)
)
);
try {
$attribs = authLdap_get_server()->search(
sprintf($authLDAPFilter, $username),
$attributes
);
// First get all the relevant group informations so we can see if
// whether have been changes in group association of the user
if (! isset($attribs[0]['dn'])) {
authLdap_debug('could not get user attributes from LDAP');
throw new UnexpectedValueException('dn has not been returned');
}
if (! isset($attribs[0][strtolower($authLDAPUidAttr)][0])) {
authLdap_debug('could not get user attributes from LDAP');
throw new UnexpectedValueException('The user-ID attribute has not been returned');
}
$dn = $attribs[0]['dn'];
$realuid = $attribs[0][strtolower($authLDAPUidAttr)][0];
} catch (Exception $e) {
authLdap_debug('Exception getting LDAP user: ' . $e->getMessage());
return false;
}
$uid = authLdap_get_uid($realuid);
// This fixes #172
if (true == authLdap_get_option('DoNotOverwriteNonLdapUsers', false)) {
if (! get_user_meta($uid, 'authLDAP')) {
return null;
}
}
$role = '';
// we only need this if either LDAP groups are disabled or
// if the WordPress role of the user overrides LDAP groups
if (!$authLDAPGroupEnable || !$authLDAPGroupOverUser) {
$role = authLdap_user_role($uid);
}
// do LDAP group mapping if needed
// (if LDAP groups override worpress user role, $role is still empty)
if (empty($role) && $authLDAPGroupEnable) {
$role = authLdap_groupmap($realuid, $dn);
authLdap_debug('role from group mapping: ' . $role);
}
// if we don't have a role yet, use default role
if (empty($role) && !empty($authLDAPDefaultRole)) {
authLdap_debug('no role yet, set default role');
$role = $authLDAPDefaultRole;
}
if (empty($role)) {
// Sorry, but you are not in any group that is allowed access
trigger_error('no group found');
authLdap_debug('user is not in any group that is allowed access');
return false;
} else {
$roles = new WP_Roles();
// not sure if this is needed, but it can't hurt
if (!$roles->is_role($role)) {
trigger_error('no group found');
authLdap_debug('role is invalid');
return false;
}
}
// from here on, the user has access!
// now, lets update some user details
$user_info = array();
$user_info['user_login'] = $realuid;
$user_info['role'] = $role;
$user_info['user_email'] = '';
// first name
if (isset($attribs[0][strtolower($authLDAPNameAttr)][0])) {
$user_info['first_name'] = $attribs[0][strtolower($authLDAPNameAttr)][0];
}
// last name
if (isset($attribs[0][strtolower($authLDAPSecName)][0])) {
$user_info['last_name'] = $attribs[0][strtolower($authLDAPSecName)][0];
}
// mail address
if (isset($attribs[0][strtolower($authLDAPMailAttr)][0])) {
$user_info['user_email'] = $attribs[0][strtolower($authLDAPMailAttr)][0];
}
// website
if (isset($attribs[0][strtolower($authLDAPWebAttr)][0])) {
$user_info['user_url'] = $attribs[0][strtolower($authLDAPWebAttr)][0];
}
// display name, nickname, nicename
if (array_key_exists('first_name', $user_info)) {
$user_info['display_name'] = $user_info['first_name'];
$user_info['nickname'] = $user_info['first_name'];
$user_info['user_nicename'] = sanitize_title_with_dashes($user_info['first_name']);
if (array_key_exists('last_name', $user_info)) {
$user_info['display_name'] .= ' ' . $user_info['last_name'];
$user_info['nickname'] .= ' ' . $user_info['last_name'];
$user_info['user_nicename'] .= '_' . sanitize_title_with_dashes($user_info['last_name']);
}
}
$user_info['user_nicename'] = substr($user_info['user_nicename'], 0, 50);
// optionally store the password into the wordpress database
if (authLdap_get_option('CachePW')) {
// Password will be hashed inside wp_update_user or wp_insert_user
$user_info['user_pass'] = $password;
} else {
// clear the password
$user_info['user_pass'] = '';
}
// add uid if user exists
if ($uid) {
// found user in the database
authLdap_debug('The LDAP user has an entry in the WP-Database');
$user_info['ID'] = $uid;
unset ($user_info['display_name'], $user_info['nickname']);
$userid = wp_update_user($user_info);
} else {
// new wordpress account will be created
authLdap_debug('The LDAP user does not have an entry in the WP-Database, a new WP account will be created');
$userid = wp_insert_user($user_info);
}
// if the user exists, wp_insert_user will update the existing user record
if (is_wp_error($userid)) {
authLdap_debug('Error creating user : ' . $userid->get_error_message());
trigger_error('Error creating user: ' . $userid->get_error_message());
return $userid;
}
authLdap_debug('user id = ' . $userid);
// flag the user as an ldap user so we can hide the password fields in the user profile
update_user_meta($userid, 'authLDAP', true);
// return a user object upon positive authorization
return new WP_User($userid);
} catch (Exception $e) {
authLdap_debug($e->getMessage() . '. Exception thrown in line ' . $e->getLine());
trigger_error($e->getMessage() . '. Exception thrown in line ' . $e->getLine());
}
}
/**
* Get user's user id
*
* Returns null if username not found
*
* @param string $username username
* @param string user id, null if not found
*/
function authLdap_get_uid($username)
{
global $wpdb;
// find out whether the user is already present in the database
$uid = $wpdb->get_var(
$wpdb->prepare(
"SELECT ID FROM {$wpdb->users} WHERE user_login = %s",
$username
)
);
if ($uid) {
authLdap_debug("Existing user, uid = {$uid}");
return $uid;
} else {
return null;
}
}
/**
* Get the user's current role
*
* Returns empty string if not found.
*
* @param int $uid wordpress user id
* @return string role, empty if none found
*/
function authLdap_user_role($uid)
{
global $wpdb;
if (!$uid) {
return '';
}
$meta_value = $wpdb->get_var("SELECT meta_value FROM {$wpdb->usermeta} WHERE meta_key = '{$wpdb->prefix}capabilities' AND user_id = {$uid}");
if (!$meta_value) {
return '';
}
$capabilities = unserialize($meta_value);
$roles = is_array($capabilities) ? array_keys($capabilities) : array('');
$role = $roles[0];
authLdap_debug("Existing user's role: {$role}");
return $role;
}
/**
* Get LDAP groups for user and map to role
*
* @param string $username
* @param string $dn
* @return string role, empty string if no mapping found, first found role otherwise
* @conf array authLDAPGroups, associative array, role => ldap_group
* @conf string authLDAPGroupBase, base dn to look up groups
* @conf string authLDAPGroupAttr, ldap attribute that holds name of group
* @conf string authLDAPGroupFilter, LDAP filter to find groups. can contain %s and %dn% placeholders
*/
function authLdap_groupmap($username, $dn)
{
$authLDAPGroups = authLdap_sort_roles_by_capabilities(
authLdap_get_option('Groups')
);
$authLDAPGroupBase = authLdap_get_option('GroupBase');
$authLDAPGroupAttr = authLdap_get_option('GroupAttr');
$authLDAPGroupFilter = authLdap_get_option('GroupFilter');
$authLDAPGroupSeparator = authLdap_get_option('GroupSeparator');
if (! $authLDAPGroupAttr) {
$authLDAPGroupAttr = 'gidNumber';
}
if (! $authLDAPGroupFilter) {
$authLDAPGroupFilter = '(&(objectClass=posixGroup)(memberUid=%s))';
}
if (! $authLDAPGroupSeparator) {
$authLDAPGroupSeparator = ',';
}
if (!is_array($authLDAPGroups) || count(array_filter(array_values($authLDAPGroups))) == 0) {
authLdap_debug('No group names defined');
return '';
}
try {
// To allow searches based on the DN instead of the uid, we replace the
// string %dn% with the users DN.
$authLDAPGroupFilter = str_replace(
'%dn%',
ldap_escape($dn, '', LDAP_ESCAPE_FILTER),
$authLDAPGroupFilter
);
authLdap_debug('Group Filter: ' . json_encode($authLDAPGroupFilter));
authLdap_debug('Group Base: ' . $authLDAPGroupBase);
$groups = authLdap_get_server()->search(
sprintf($authLDAPGroupFilter, ldap_escape($username, '', LDAP_ESCAPE_FILTER)),
array($authLDAPGroupAttr),
$authLDAPGroupBase
);
} catch (Exception $e) {
authLdap_debug('Exception getting LDAP group attributes: ' . $e->getMessage());
return '';
}
$grp = array();
for ($i = 0; $i < $groups ['count']; $i++) {
for ($k = 0; $k < $groups[$i][strtolower($authLDAPGroupAttr)]['count']; $k++) {
$grp[] = $groups[$i][strtolower($authLDAPGroupAttr)][$k];
}
}
authLdap_debug('LDAP groups: ' . json_encode($grp));
// Check whether the user is member of one of the groups that are
// allowed acces to the blog. If the user is not member of one of
// The groups throw her out! ;-)
// If the user is member of more than one group only the first one
// will be taken into account!
$role = '';
foreach ($authLDAPGroups as $key => $val) {
$currentGroup = explode($authLDAPGroupSeparator, $val);
// Remove whitespaces around the group-ID
$currentGroup = array_map('trim', $currentGroup);
if (0 < count(array_intersect($currentGroup, $grp))) {
$role = $key;
break;
}
}
authLdap_debug("Role from LDAP group: {$role}");
return $role;
}
/**
* This function disables the password-change fields in the users preferences.
*
* It does not make sense to authenticate via LDAP and then allow the user to
* change the password only in the wordpress database. And changing the password
* LDAP-wide can not be the scope of Wordpress!
*
* Whether the user is an LDAP-User or not is determined using the authLDAP-Flag
* of the users meta-informations
*
* @return false, if the user whose prefs are viewed is an LDAP-User, true if
* he isn't
* @conf boolean authLDAP
*/
function authLdap_show_password_fields($return, $user)
{
if (! $user) {
return true;
}
if (get_user_meta($user->ID, 'authLDAP')) {
return false;
}
return $return;
}
/**
* This function disables the password reset for a user.
*
* It does not make sense to authenticate via LDAP and then allow the user to
* reset the password only in the wordpress database. And changing the password
* LDAP-wide can not be the scope of Wordpress!
*
* Whether the user is an LDAP-User or not is determined using the authLDAP-Flag
* of the users meta-informations
*
* @author chaplina (https://github.com/chaplina)
* @conf boolean authLDAP
* @return false, if the user is an LDAP-User, true if he isn't
*/
function authLdap_allow_password_reset($return, $userid)
{
if (!(isset($userid))) {
return true;
}
if (get_user_meta($userid, 'authLDAP')) {
return false;
}
return $return;
}
/**
* Sort the given roles by number of capabilities
*
* @param array $roles
*
* @return array
*/
function authLdap_sort_roles_by_capabilities($roles)
{
global $wpdb;
$myRoles = get_option($wpdb->get_blog_prefix() . 'user_roles');
authLdap_debug(print_r($roles, true));
uasort($myRoles, 'authLdap_sortByCapabilitycount');
$return = array();
foreach ($myRoles as $key => $role) {
if (isset($roles[$key])) {
$return[$key] = $roles[$key];
}
}
authLdap_debug(print_r($return, true));
return $return;
}
/**
* Sort according to the number of capabilities
*
* @param $a
* @param $b
*/
function authLdap_sortByCapabilitycount($a, $b)
{
if (count($a['capabilities']) > count($b['capabilities'])) {
return -1;
}
if (count($a['capabilities']) < count($b['capabilities'])) {
return 1;
}
return 0;
}
/**
* Load AuthLDAP Options
*
* Sets and stores defaults if options are not up to date
*/
function authLdap_load_options($reload = false)
{
static $options = null;
// the current version for options
$option_version_plugin = 1;
$optionFunction = 'get_option';
if (is_multisite()) {
$optionFunction = 'get_site_option';
}
if (is_null($options) || $reload) {
$options = $optionFunction('authLDAPOptions', array());
}
// check if option version has changed (or if it's there at all)
if (!isset($options['Version']) || ($options['Version'] != $option_version_plugin)) {
// defaults for all options
$options_default = array(
'Enabled' => false,
'CachePW' => false,
'URI' => '',
'URISeparator' => ' ',
'Filter' => '', // '(uid=%s)'
'NameAttr' => '', // 'name'
'SecName' => '',
'UidAttr' => '', // 'uid'
'MailAttr' => '', // 'mail'
'WebAttr' => '',
'Groups' => array(),
'Debug' => false,
'GroupAttr' => '', // 'gidNumber'
'GroupFilter' => '', // '(&(objectClass=posixGroup)(memberUid=%s))'
'DefaultRole' => '',
'GroupEnable' => true,
'GroupOverUser' => true,
'Version' => $option_version_plugin,
'DoNotOverwriteNonLdapUsers' => false,
);
// check if we got a version
if (!isset($options['Version'])) {
// we just changed to the new option format
// read old options, then delete them
$old_option_new_option = array(
'authLDAP' => 'Enabled',
'authLDAPCachePW' => 'CachePW',
'authLDAPURI' => 'URI',
'authLDAPFilter' => 'Filter',
'authLDAPNameAttr' => 'NameAttr',
'authLDAPSecName' => 'SecName',
'authLDAPUidAttr' => 'UidAttr',
'authLDAPMailAttr' => 'MailAttr',
'authLDAPWebAttr' => 'WebAttr',
'authLDAPGroups' => 'Groups',
'authLDAPDebug' => 'Debug',
'authLDAPGroupAttr' => 'GroupAttr',
'authLDAPGroupFilter' => 'GroupFilter',
'authLDAPDefaultRole' => 'DefaultRole',
'authLDAPGroupEnable' => 'GroupEnable',
'authLDAPGroupOverUser' => 'GroupOverUser',
);
foreach ($old_option_new_option as $old_option => $new_option) {
$value = get_option($old_option, null);
if (!is_null($value)) {
$options[$new_option] = $value;
}
delete_option($old_option);
}
delete_option('authLDAPCookieMarker');
delete_option('authLDAPCookierMarker');
}
// set default for all options that are missing
foreach ($options_default as $key => $default) {
if (!isset($options[$key])) {
$options[$key] = $default;
}
}
// set new version and save
$options['Version'] = $option_version_plugin;
update_option('authLDAPOptions', $options);
}
return $options;
}
/**
* Get an individual option
*/
function authLdap_get_option($optionname, $default = null)
{
$options = authLdap_load_options();
if (isset($options[$optionname]) && $options[$optionname]) {
return $options[$optionname];
}
if (null !== $default) {
return $default;
}
//authLdap_debug('option name invalid: ' . $optionname);
return null;
}
/**
* Set new options
*/
function authLdap_set_options($new_options = array())
{
// initialize the options with what we currently have
$options = authLdap_load_options();
// set the new options supplied
foreach ($new_options as $key => $value) {
$options[$key] = $value;
}
// store options
$optionFunction = 'update_option';
if (is_multisite()) {
$optionFunction = 'update_site_option';
}
if ($optionFunction('authLDAPOptions', $options)) {
// reload the option cache
authLdap_load_options(true);
return true;
}
// could not set options
return false;
}
/**
* Do not send an email after changing the password or the email of the user!
*
* @param boolean $result The initial resturn value
* @param array $user The old userdata
* @param array $newUserData The changed userdata
*
* @return bool
*/
function authLdap_send_change_email($result, $user, $newUserData)
{
if (get_usermeta($user['ID'], 'authLDAP')) {
return false;
}
return $result;
}
$hook = is_multisite() ? 'network_' : '';
add_action($hook . 'admin_menu', 'authLdap_addmenu');
add_filter('show_password_fields', 'authLdap_show_password_fields', 10, 2);
add_filter('allow_password_reset', 'authLdap_allow_password_reset', 10, 2);
add_filter('authenticate', 'authLdap_login', 10, 3);
/** This only works from WP 4.3.0 on */
add_filter('send_password_change_email', 'authLdap_send_change_email', 10, 3);
add_filter('send_email_change_email', 'authLdap_send_change_email', 10, 3);

View File

@ -1,95 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<project name="ajaxComments" default="build" basedir=".">
<php expression="include('vendor/autoload.php')"/>
<loadfile property = "version" file = "VERSION">
<filterchain>
<striplinebreaks/>
</filterchain>
</loadfile>
<target name="bumpversion">
<echo>Bumping version to ${version}</echo>
<reflexive>
<fileset dir=".">
<include name="index.php"/>
<include name="authLdap.php"/>
</fileset>
<filterchain>
<replaceregexp>
<regexp pattern="Version:.*" replace="Version: ${version}"/>
</replaceregexp>
</filterchain>
</reflexive>
</target>
<target name="build" depends="bumpversion,deploy.git,deploy.svn"/>
<target name="sync.svn">
<filesync
rsyncPath="rsync"
destinationDir="${project.basedir}/svn/trunk"
sourceDir="${project.basedir}/"
verbose="true"
excludeFile="${project.basedir}/.rsyncIgnore"
/>
</target>
<target name="deploy.svn" depends="sync.svn">
<property override="true" file="${project.basedir}/.svnAccess" prefix="svnaccess" />
<foreach param="dirname" target="svn.addFile">
<fileset dir="${project.basedir}/svn/trunk">
<include name="**/*"/>
</fileset>
</foreach>
<echo message="${svnaccess.username}"/>
<exec outputProperty="committedrevision" executable="svn" dir="${project.basedir}/svn/trunk">
<arg value="commit"/>
<arg value="--username"/>
<arg value="${svnaccess.username}"/>
<arg value="--password"/>
<arg value="${svnaccess.password}"/>
<arg value="--message"/>
<arg value="Bumps version to ${version}"/>
<arg value="--no-auth-cache"/>
<arg value="--quiet"/>
</exec>
<!--svncommit
username="${svnaccess.username}"
password="${svnaccess.password}"
workingcopy="${project.basedir}/svn"
message="Bumps version to ${version}"
nocache="true"
/-->
<echo message="Committed revision: ${committedrevision}"/>
</target>
<target name="svn.addFile">
<trycatch>
<try>
<svninfo workingcopy="${project.basedir}/svn/trunk/${dirname}"/>
</try>
<catch>
<exec command="svn add ${project.basedir}/svn/trunk/${dirname}"/>
<echo>${dirname}</echo>
</catch>
<finally>
</finally>
</trycatch>
<echo>${svn.info}</echo>
</target>
<target name="deploy.git">
<exec executable="git" dir=".">
<arg value="-m"/>
<arg value="Bumps version to ${version}"/>
</exec>
<exec executable="git" dir=".">
<arg value="tag"/>
<arg value="-s"/>
<arg value="-m"/>
<arg value="Version ${version}"/>
<arg value="${version}"/>
</exec>
<exec executable="git" dir=".">
<arg value="push"/>
<arg value="--tags"/>
<arg value="origin"/>
</exec>
</target>
</project>

View File

@ -1,41 +0,0 @@
{
"name" : "org_heigl/authLdap",
"type" : "library",
"description": "Enables wordpress-authentication via LDAP",
"keywords": ["ldap","authenticate", "auth", "wordpress"],
"homepage": "http://github.com/heiglandreas/authLdap",
"license": "MIT",
"authors": [{
"name": "Andreas Heigl",
"email": "andreas@heigl.org",
"homepage": "http://andreas.heigl.org",
"role": "Developer"
}],
"require" : {
"php": ">=5.4",
"phing/phing": "^2.16"
},
"require-dev": {
"php-mock/php-mock": "^1.0",
"phpunit/phpunit": "~4.5",
"mockery/mockery": "0.9.*",
"codeclimate/php-test-reporter": "0.1.*",
"squizlabs/php_codesniffer": "~2.3",
"pear/versioncontrol_svn": "^0.5.2",
"pear/pear": "dev-master"
},
"autoload" : {
"classmap" : [
"ldap.php",
"authLdap.php"
],
"psr-4" : {
"Org_Heigl\\AuthLdap\\" : "src/"
}
},
"autoload-dev" : {
"psr-4" : {
"Org_Heigl\\AuthLdapTest\\" : "tests/"
}
}
}

View File

@ -1,67 +0,0 @@
version: "3.5"
services:
wp:
# image: authldap:latest
build:
context: dockersetup
dockerfile: Dockerfile_wordpress
ports:
- 80:80 # change ip if required
volumes:
- ./config/php.conf.ini:/usr/local/etc/php/conf.d/conf.ini
- ./wp-app:/var/www/html # Full wordpress project
- .:/var/www/html/wp-content/plugins/authldap # Plugin development
#- ./theme-name/trunk/:/var/www/html/wp-content/themes/theme-name # Theme development
environment:
WORDPRESS_DB_HOST: db
WORDPRESS_DB_NAME: "wordpress"
WORDPRESS_DB_USER: root
WORDPRESS_DB_PASSWORD: "wppasswd"
depends_on:
- db
links:
- db
wpcli:
image: wordpress:cli
volumes:
- ./config/php.conf.ini:/usr/local/etc/php/conf.d/conf.ini
- ./wp-app:/var/www/html
depends_on:
- db
- wp
db:
image: mysql:latest # https://hub.docker.com/_/mysql/ - or mariadb https://hub.docker.com/_/mariadb
ports:
- 3306:3306 # change ip if required
command: [
'--default_authentication_plugin=mysql_native_password',
'--character-set-server=utf8mb4',
'--collation-server=utf8mb4_unicode_ci'
]
volumes:
- ./wp-data:/docker-entrypoint-initdb.d
- db_data:/var/lib/mysql
environment:
MYSQL_DATABASE: "wordpress"
MYSQL_ROOT_PASSWORD: "wppasswd"
openldap:
image: osixia/openldap:latest
# build:
# context: dockersetup
# dockerfile: Dockerfile_ldap
ports:
- 389:389
volumes:
- ./.ci/50-init.ldif:/container/service/slapd/assets/config/bootstrap/ldif/custom/50-bootstrap.ldif
command: "--copy-service --loglevel debug"
restart: always
environment:
LDAP_LOG_LEVEL: "0"
LDAP_TLS: "false"
volumes:
db_data:

View File

@ -1,9 +0,0 @@
FROM wordpress:latest
RUN set -x \
&& apt-get update \
&& apt-get install -y libldap2-dev \
&& rm -rf /var/lib/apt/lists/* \
&& docker-php-ext-configure ldap --with-libdir=lib/x86_64-linux-gnu/ \
&& docker-php-ext-install ldap \
&& apt-get purge -y --auto-remove libldap2-dev

View File

@ -1,280 +0,0 @@
<?php
/**
* $Id: ldap.php 381646 2011-05-06 09:37:31Z heiglandreas $
*
* authLdap - Authenticate Wordpress against an LDAP-Backend.
* Copyright (c) 2008 Andreas Heigl<andreas@heigl.org>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* This file handles the basic LDAP-Tasks
*
* @author Andreas Heigl<andreas@heigl.org>
* @package authLdap
* @category authLdap
* @since 2008
*/
namespace Org_Heigl\AuthLdap;
use Exception;
class LDAP
{
private $_server = '';
private $_scheme = 'ldap';
private $_port = 389;
private $_baseDn = '';
private $_debug = false;
/**
* This property contains the connection handle to the ldap-server
*
* @var Ressource
*/
private $_ch = null;
private $_username = '';
private $_password = '';
private $_starttls = false;
public function __construct($URI, $debug = false, $starttls = false)
{
$this->_debug=$debug;
$array = parse_url($URI);
if (! is_array($array)) {
throw new Exception($URI . ' seems not to be a valid URI');
}
$url = array_map(function ($item) {
return urldecode($item);
}, $array);
if (false === $url) {
throw new Exception($URI . ' is an invalid URL');
}
if (! isset ( $url['scheme'] )) {
throw new Exception($URI . ' does not provide a scheme');
}
if (0 !== strpos($url['scheme'], 'ldap')) {
throw new Exception($URI . ' is an invalid LDAP-URI');
}
if (! isset ( $url['host'] )) {
throw new Exception($URI . ' does not provide a server');
}
if (! isset ( $url['path'] )) {
throw new Exception($URI . ' does not provide a search-base');
}
if (1 == strlen($url['path'])) {
throw new Exception($URI . ' does not provide a valid search-base');
}
$this -> _server = $url['host'];
$this -> _scheme = $url['scheme'];
$this -> _baseDn = substr($url['path'], 1);
if (isset ( $url['user'] )) {
$this -> _username = $url['user'];
}
if ('' == trim($this -> _username)) {
$this -> _username = 'anonymous';
}
if (isset ( $url['pass'] )) {
$this -> _password = $url['pass'];
}
if (isset ( $url['port'] )) {
$this -> _port = $url['port'];
}
$this->_starttls = $starttls;
}
/**
* Connect to the given LDAP-Server
*
* @return LDAP
* @throws AuthLdap_Exception
*/
public function connect()
{
$this -> disconnect();
if ('ldaps' == $this->_scheme && 389 == $this->_port) {
$this->_port = 636;
}
$this->_ch = @ldap_connect($this->_scheme . '://' . $this->_server . ':' . $this -> _port);
if (! $this->_ch) {
throw new AuthLDAP_Exception('Could not connect to the server');
}
ldap_set_option($this->_ch, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($this->_ch, LDAP_OPT_REFERRALS, 0);
//if configured try to upgrade encryption to tls for ldap connections
if ($this->_starttls) {
ldap_start_tls($this->_ch);
}
return $this;
}
/**
* Disconnect from a resource if one is available
*
* @return LDAP
*/
public function disconnect()
{
if (is_resource($this->_ch)) {
@ldap_unbind($this->_ch);
}
$this->_ch = null;
return $this;
}
/**
* Bind to an LDAP-Server with the given credentials
*
* @return LDAP
* @throw AuthLdap_Exception
*/
public function bind()
{
if (! $this->_ch) {
$this->connect();
}
if (! is_resource($this->_ch)) {
throw new AuthLDAP_Exception('No Resource-handle given');
}
$bind = false;
if (( ( $this->_username )
&& ( $this->_username != 'anonymous') )
&& ( $this->_password != '' ) ) {
$bind = @ldap_bind($this->_ch, $this->_username, $this->_password);
} else {
$bind = @ldap_bind($this->_ch);
}
if (! $bind) {
throw new AuthLDAP_Exception('bind was not successfull: ' . ldap_error($this->_ch));
}
return $this;
}
public function getErrorNumber()
{
return @ldap_errno($this->_ch);
}
public function getErrorText()
{
return @ldap_error($this->_ch);
}
/**
* This method does the actual ldap-serch.
*
* This is using the filter <var>$filter</var> for retrieving the attributes
* <var>$attributes</var>
*
*
* @param string $filter
* @param array $attributes
* @param string $base
* @return array
*/
public function search($filter, $attributes = array('uid'), $base = '' )
{
if (! is_Resource($this->_ch)) {
throw new AuthLDAP_Exception('No resource handle avbailable');
}
if (! $base) {
$base = $this->_baseDn;
}
$result = ldap_search($this->_ch, $base, $filter, $attributes);
if ($result === false) {
throw new AuthLDAP_Exception('no result found');
}
$this->_info = @ldap_get_entries($this->_ch, $result);
if ($this->_info === false) {
throw new AuthLDAP_Exception('invalid results found');
}
return $this -> _info;
}
/**
* This method sets debugging to ON
*/
public function debugOn()
{
$this->_debug = true;
return $this;
}
/**
* This method sets debugging to OFF
*/
public function debugOff()
{
$this->_debug = false;
return $this;
}
/**
* This method authenticates the user <var>$username</var> using the
* password <var>$password</var>
*
* @param string $username
* @param string $password
* @param string $filter OPTIONAL This parameter defines the Filter to be used
* when searchin for the username. This MUST contain the string '%s' which
* will be replaced by the vaue given in <var>$username</var>
* @return boolean true or false depending on successfull authentication or not
*/
public function authenticate($username, $password, $filter = '(uid=%s)')
{
//return true;
$this->connect();
$this->bind();
$res = $this->search(sprintf($filter, $username));
if (! $res || ! is_array($res) || ( $res ['count'] != 1 )) {
return false;
}
$dn = $res[0]['dn'];
if ($username && $password) {
if (@ldap_bind($this->_ch, $dn, $password)) {
return true;
}
}
return false;
}
/**
* $this method loggs errors if debugging is set to ON
*/
public function logError()
{
if ($this->_debug) {
$_v = debug_backtrace();
throw new AuthLDAP_Exception('[LDAP_ERROR]' . ldap_errno($this->_ch) . ':' . ldap_error($this->_ch), $_v[0]['line']);
}
}
}
class AuthLDAP_Exception extends Exception
{
public function __construct($message, $line = null)
{
parent :: __construct($message);
if ($line) {
$this -> line = $line;
}
}
}

View File

@ -1,28 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php">
<testsuite name="authLdap Test-Suite">
<directory>tests</directory>
</testsuite>
<groups>
<exclude>
<group>disable</group>
</exclude>
</groups>
<listeners>
<listener class="\Mockery\Adapter\Phpunit\TestListener"></listener>
</listeners>
<filter>
<whitelist>
<directory suffix=".php">src</directory>
</whitelist>
</filter>
<logging>
<!--
Adapt these paths to your special needs
-->
<log type="coverage-text" target="php://stdout" showUncoveredFiles="false"/>
<log type="coverage-clover" target="build/logs/clover.xml" />
</logging>
</phpunit>

View File

@ -1,42 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Document : phpunit.xml
Created on : 21.09.2010
Author : heiglandreas
-->
<phpunit bootstrap="vendor/autoload.php">
<testsuite name="authLdap Test-Suite">
<directory>tests</directory>
</testsuite>
<groups>
<exclude>
<group>disable</group>
</exclude>
</groups>
<listeners>
<!--listener class="\Mockery\Adapter\Phpunit\TestListener"></listener-->
</listeners>
<filter>
<whitelist>
<directory suffix=".php">src</directory>
</whitelist>
</filter>
<logging>
<log type="coverage-html" target="build/coverage" charset="UTF-8"
yui="true" highlight="false"
lowUpperBound="35" highLowerBound="70" />
<!--log type="coverage-xml" target="../report/coverage.xml"/-->
<!--log type="graphviz" target="../report/logfile.dot"/-->
<!--log type="json" target="../report/logfile.json"/-->
<!--log type="metrics-xml" target="../report/metrics.xml"/-->
<!--log type="plain" target="../report/logfile.txt"/-->
<!--log type="pmd-xml" target="../report/pmd.xml" cpdMinLines="5" cpdMinMatches="70"/-->
<!--log type="tap" target="../report/logfile.tap"/-->
<!--log type="test-xml" target="../report/logfile.xml" logIncompleteSkipped="false"/-->
<!--log type="testdox-html" target="../report/testdox.html"/-->
<!--log type="testdox-text" target="../report/testdox.txt"/-->
</logging>
</phpunit>

View File

@ -1,111 +0,0 @@
=== authLdap ===
Contributors: heiglandreas
Tags: ldap, auth, authentication, active directory, AD, openLDAP, Open Directory
Requires at least: 2.5.0
Tested up to: 5.2.0
Requires PHP: 5.6
Stable tag: trunk
License: MIT
License URI: https://opensource.org/licenses/MIT
Use your existing LDAP flexible as authentication backend for WordPress
== Description ==
Use your existing LDAP as authentication-backend for your wordpress!
So what are the differences to other Wordpress-LDAP-Authentication-Plugins?
* Flexible: You are totaly free in which LDAP-backend to use. Due to the extensive configuration you can freely decide how to do the authentication of your users. It simply depends on your filters
* Independent: As soon as a user logs in, it is added/updated to the Wordpress' user-database to allow wordpress to always use the correct data. You only have to administer your users once.
* Failsafe: Due to the users being created in Wordpress' User-database they can also log in when the LDAP-backend currently is gone.
* Role-Aware: You can map Wordpress' roles to values of an existing LDAP-attribute.
For more Information on the configuration have a look at https://github.com/heiglandreas/authLdap
== Installation ==
1. Upload the extracted folder `authLdap` to the `/wp-content/plugins/` directory
2. Activate the plugin through the 'Plugins' menu in WordPress
3. Configure the Plugin via the 'authLdap'-Configuration-Page.
== Frequently Asked Questions ==
= Where can I find more Informations about the plugin? =
Go to https://github.com/heiglandreas/authLdap
= Where can I report issues with the plugin? =
Please use the issuetracker at https://github.com/heiglandreas/authLdap/issues
== Changelog ==
= 2.3.0 =
* Allow to not overwrite existing WordPress-Users with LDAP-Users as that can be a security issue.
= 2.1.0 =
* Add search-base for groups. This might come in handy for multisite-instances
= 2.0.0 =
* This new release adds Multi-Site support. It will no longer be possible to use this plugin just in one subsite of a multisite installation!
* Adds a warning screen to the config-section when no LDAPextension could be found
* Fixes an issue with the max-length of the username
= 1.5.1 =
* Fixes an issue with escaped backslashes and quotes
= 1.5.0 =
* Allows parts of the LDAP-URI to be URLEncoded
* Drops support for PHP 5.4
= 1.4.20 =
* Allows multiple LDAP-servers to be queried (given that they use the same attributes)
* Fixes issue with URL-Encoded informations (see https://github.com/heiglandreas/authLdap/issues/108)
= 1.4.19 =
* Adds support for TLS
= 1.4.14 =
* Update to showing password-fields check (thanks to @chaplina)
= 1.4.13 =
* Removed generation of default email-address (thanks to @henryk)
* Fixes password-hashing when caching passwords (thanks to @litinoveweedle)
* Removes the possibility to reset a password for LDAP-based users (thanks to @chaplina)
* Removes the password-change-Email from 4.3 on (thanks to @litinoveweedle)
* Fixes double authentication-attempt (that resulted in failed authentication) (thanks to @litinoveweedle)
= 1.4.10 =
* Cleanup by removing deprecated code
* Fixes issues with undefined variables
* Enables internal option-versioning
* Setting users nickname initially to the realname instead of the uid
* Fixes display of password-change possibility in users profile-page
= 1.4.9 =
* Fixed an issue with changing display name on every login
* Use proper way of looking up user-roles in setups w/o DB-prefix
= 1.4.8 =
* Updated version string
= 1.4.7 =
* Use default user to retrieve group menberships and not logging in user.
* return the UID from the LDAP instead of the value given by the user
* remove unnecessary checkbox
* Adds a testsuite
* Fixes PSR2 violations
[…]
= 1.2.1 =
* Fixed an issue with group-ids
* Moved the code to GitHub (https://github.com/heiglandreas/authLdap)
= 1.1.0 =
* Changed the login-process. Now users that are not allowed to login due to
missing group-memberships are not created within your blog as was the standard
until Version 1.0.3 - Thanks to alex@tayts.com
* Changed the default mail-address that is created when no mail-address can be
retrieved from the LDAP from me@example.com to $username@example.com so that
a new user can be created even though the mail address already exists in your
blog - Also thanks to alex@tayts.com
* Added support for WordPress-Table-prefixes as the capabilities of a user
are interlany stored in a field that is named "$tablePrefix_capabilities" -
again thanks to alex@tayts.com and also to sim0n of silicium.mine.nu

View File

@ -1,87 +0,0 @@
<?php
/**
* Copyright (c) Andreas Heigl<andreas@heigl.org>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author Andreas Heigl<andreas@heigl.org>
* @copyright Andreas Heigl
* @license http://www.opensource.org/licenses/mit-license.php MIT-License
* @since 07.07.2016
* @link http://github.com/heiglandreas/authLDAP
*/
namespace Org_Heigl\AuthLdap;
class LdapList
{
/**
* @var \LDAP[]
*/
protected $items = [];
public function addLdap(LDAP $ldap)
{
$this->items[] = $ldap;
}
public function authenticate($username, $password, $filter = '(uid=%s)')
{
foreach ($this->items as $key => $item) {
if (! $item->authenticate($username, $password, $filter)) {
unset ($this->items[$key]);
continue;
}
return true;
}
return false;
}
public function bind()
{
$allFailed = true;
foreach ($this->items as $key => $item) {
try {
$item->bind();
} catch (\Exception $e) {
unset($this->items[$key]);
continue;
}
$allFailed = false;
}
if ($allFailed) {
throw new AuthLDAP_Exception('No bind successfull');
}
return true;
}
public function search($filter, $attributes = array('uid'), $base = '')
{
foreach ($this->items as $item) {
try {
$result = $item->search($filter, $attributes, $base);
return $result;
} catch (Exception $e) {
throw $e;
}
}
throw new \AuthLDAP_Exception('No Results found');
}
}

View File

@ -1,134 +0,0 @@
<?php
/**
* Copyright (c) 2016-2016} Andreas Heigl<andreas@heigl.org>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author Andreas Heigl<andreas@heigl.org>
* @copyright 2016-2016 Andreas Heigl
* @license http://www.opensource.org/licenses/mit-license.php MIT-License
* @version 0.0
* @since 07.06.2016
* @link http://github.com/heiglandreas/authLDAP
*/
namespace Org_Heigl\AuthLdapTest;
use Org_Heigl\AuthLdap\LDAP;
use Org_Heigl\AuthLdap\LdapList;
use phpmock\spy\Spy;
use PHPUnit_Framework_TestCase;
class LDAPBaseTest extends PHPUnit_Framework_TestCase
{
public function setUp()
{
$this->ldap_connect_spy = new Spy('Org_Heigl\AuthLdap', 'ldap_connect');
$this->ldap_connect_spy->enable();
}
public function tearDown()
{
$this->ldap_connect_spy->disable();
}
/** @dataProvider bindingWithPasswordProvider */
public function testThatBindingWithPasswordWorks($user, $password, $filter, $uri)
{
$ldap = new LDAP($uri);
$this->assertTrue($ldap->authenticate($user, $password, $filter));
}
public function bindingWithPasswordProvider()
{
return [
['user3', 'user!"', 'uid=%s', 'ldap://cn=Manager,dc=example,dc=com:insecure@127.0.0.1:3890/dc=example,dc=com'],
['Manager', 'insecure', 'cn=%s', 'ldap://cn=Manager,dc=example,dc=com:insecure@127.0.0.1:3890/dc=example,dc=com'],
['user1', 'user1', 'uid=%s', 'ldap://cn=Manager,dc=example,dc=com:insecure@127.0.0.1:3890/dc=example,dc=com'],
['user 4', 'user!"', 'uid=%s', 'ldap://cn=Manager,dc=example,dc=com:insecure@127.0.0.1:3890/dc=example,dc=com'],
['user 5', 'user!"', 'uid=%s', 'ldap://cn=Manager,dc=example,dc=com:insecure@127.0.0.1:3890/dc=test%20space,dc=example,dc=com'],
];
}
/**
* @param $uri
* @dataProvider initialBindingToLdapServerWorksProvider
*/
public function testThatInitialBindingWorks($uri)
{
$ldap = new LDAP($uri);
$this->assertInstanceof(LDAP::class, $ldap->bind());
}
/**
* @param $uri
* @dataProvider initialBindingToLdapServerWorksProvider
*/
public function testThatInitialBindingToMultipleLdapsWorks($uri)
{
$list = new LdapList();
$list->addLDAP(new LDAP($uri));
$this->assertTrue($list->bind());
}
public function initialBindingToLdapServerWorksProvider()
{
return [
['ldap://uid=user%205,dc=test%20space,dc=example,dc=com:user!"@localhost:3890/dc=test%20space,dc=example,dc=com'],
];
}
/** @dataProvider bindingWithPasswordProvider */
public function testThatBindingWithAddedSlashesFailsWorks($user, $password, $filter)
{
$newpassword = addslashes($password);
$ldap = new LDAP('ldap://cn=Manager,dc=example,dc=com:insecure@127.0.0.1:3890/dc=example,dc=com');
if ($newpassword === $password) {
$this->assertTrue($ldap->authenticate($user, $password, $filter));
} else {
$this->assertFalse($ldap->authenticate($user, $newpassword, $filter));
}
}
/** @dataProvider serchingForGroupsProvider */
public function testThatSearchingForGoupsWorks($filter, $user, $groups)
{
// (&(objectCategory=group)(member=<USER_DN>))
$ldap = new LDAP('ldap://cn=Manager,dc=example,dc=com:insecure@127.0.0.1:3890/dc=example,dc=com');
$ldap->bind();
$this->assertContains($groups, $ldap->search(sprintf($filter, $user), ['cn'])[0]);
}
public function serchingForGroupsProvider()
{
return [
[
'(&(objectclass=groupOfUniqueNames)(uniqueMember=%s))',
'uid=user 4,dc=example,dc=com',
['count' => 1, 0 => 'group4'],
],
];
}
public function testThatSettingLDAPSActuallyGivesTheCorrectPort()
{
$ldap = new LDAP('ldaps://cn=Manager,dc=example,dc=com:insecure@127.0.0.1/dc=example,dc=com');
$ldap->connect();
$this->assertEquals('ldaps://127.0.0.1:636', $this->ldap_connect_spy->getInvocations()[0]->getArguments()[0]);
}
}

View File

@ -1,66 +0,0 @@
<?php
/**
* Copyright (c) 2016-2016} Andreas Heigl<andreas@heigl.org>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author Andreas Heigl<andreas@heigl.org>
* @copyright 2016-2016 Andreas Heigl
* @license http://www.opensource.org/licenses/mit-license.php MIT-License
* @version 0.0
* @since 07.06.2016
* @link http://github.com/heiglandreas/authLDAP
*/
namespace Org_Heigl\AuthLdapTest;
use Org_Heigl\AuthLdap\LDAP;
use PHPUnit_Framework_TestCase;
class LDAPListBaseTest extends PHPUnit_Framework_TestCase
{
/** @dataProvider bindingWithPasswordProvider */
public function testThatBindingWithPasswordWorks($user, $password, $filter)
{
require_once __DIR__ . '/../src/LdapList.php';
$ldaplist = new \Org_Heigl\AuthLdap\LdapList();
$ldaplist->addLdap(new LDAP('ldap://cn=Manager,dc=example,dc=com:insecure@127.0.0.1:3890/dc=example,dc=com'));
$this->assertTrue($ldaplist->authenticate($user, $password, $filter));
}
public function bindingWithPasswordProvider()
{
return [
['user3', 'user!"', 'uid=%s'],
['Manager', 'insecure', 'cn=%s'],
['user1', 'user1', 'uid=%s'],
];
}
/** @dataProvider bindingWithPasswordProvider */
public function testThatBindingWithAddedSlashesFailsWorks($user, $password, $filter)
{
$newpassword = addslashes($password);
require_once __DIR__ . '/../src/LdapList.php';
$ldaplist = new \Org_Heigl\AuthLdap\LdapList();
$ldaplist->addLdap(new LDAP('ldap://cn=Manager,dc=example,dc=com:insecure@127.0.0.1:3890/dc=example,dc=com'));
if ($newpassword === $password) {
$this->assertTrue($ldaplist->authenticate($user, $password, $filter));
} else {
$this->assertFalse($ldaplist->authenticate($user, $newpassword, $filter));
}
}
}

View File

@ -1,183 +0,0 @@
<?php
/**
* $Id: LdapTest.php 292156 2010-09-21 19:32:01Z heiglandreas $
*
* authLdap - Authenticate Wordpress against an LDAP-Backend.
* Copyright (c) 2008 Andreas Heigl<andreas@heigl.org>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* This file tests the basic LDAP-Tasks
*
* @category authLdap
* @package authLdap
* @subpackage UnitTests
* @author Andreas Heigl<andreas@heigl.org>
* @copyright 2010 Andreas Heigl<andreas@heigl.org>
* @license GPL
* @since 21.09.2010
*/
namespace Org_Heigl\AuthLdapTest;
use PHPUnit_Framework_TestCase;
use Org_Heigl\AuthLdap\LDAP;
class LdapTest extends PHPUnit_Framework_TestCase
{
/**
*
* @dataProvider dpInstantiateLdapClass
* @param array $expected
* @param array $given
*/
public function testInstantiateLdapClass($expected, $given)
{
$ldap = new LDAP($expected[0], $expected[1]);
foreach ($given as $key => $value) {
$this -> assertAttributeEquals($value, '_' . $key, $ldap);
}
}
/**
* @dataProvider dpExceptionsWhenInstantiatingLdapClass
* @expectedException Exception
* @param array $expected
*/
public function testExceptionsWhenInstantiatingLdapClass($expected)
{
new LDAP($expected);
}
public function dpInstantiateLdapClass()
{
return array (
array (
array ('ldap://uid=jondoe,cn=users,cn=example,c=org:secret@ldap.example.org/cn=example,c=org', true),
array (
'username' => 'uid=jondoe,cn=users,cn=example,c=org',
'password' => 'secret',
'server' => 'ldap.example.org',
'baseDn' => 'cn=example,c=org',
'debug' => true
)
),
array (
array ('ldap://uid=jondoe,cn=users,cn=example,c=org@ldap.example.org/cn=example,c=org', true),
array (
'username' => 'uid=jondoe,cn=users,cn=example,c=org',
'password' => '',
'server' => 'ldap.example.org',
'baseDn' => 'cn=example,c=org',
'debug' => true
)
),
array(
array ('ldap://ldap.example.org/cn=example,c=org', true),
array (
'username' => 'anonymous',
'password' => '',
'server' => 'ldap.example.org',
'baseDn' => 'cn=example,c=org',
'debug' => true
)
),
// array(
// array ('ldap://ldap.example.org', true),
// array (
// 'username' => 'anonymous',
// 'password' => '',
// 'server' => 'ldap.example.org',
// 'baseDn' => '',
// 'debug' => true
// )
// ),
array(
array ('ldap://uid=jondoe,cn=users,cn=example,c=org:secret@ldap.example.org/cn=example,c=org', false),
array (
'username' => 'uid=jondoe,cn=users,cn=example,c=org',
'password' => 'secret',
'server' => 'ldap.example.org',
'baseDn' => 'cn=example,c=org',
'debug' => false
)
),
array(
array ('ldap://ldap.example.org/cn=test%20example,c=org', false),
array (
'username' => 'anonymous',
'password' => '',
'server' => 'ldap.example.org',
'baseDn' => 'cn=test example,c=org',
'debug' => false
)
),
);
}
public function dpExceptionsWhenInstantiatingLdapClass()
{
return array (
array('ldap://ldap.example.org'),
array('ldap://foo:bar@/cn=example,c=org'),
array('http://ldap.example.org'),
array('fooBar'),
array('ldap://ldap.example.org/'),
array('()123üäö'),
);
}
public function testThatGroupMappingWorks()
{
$groups = [
'count' => 1,
0 => [
'dn' => 'dn-1',
'count' => 1,
0 => 'group',
'group' => [
'count' => 2,
0 => '7310T270:Překladatelství:čeština - angličtina@ff.cuni.cz',
1 => '7310T033:Český jazyk a literatura@ff.cuni.cz',
]
]
];
$grp = array();
for ($i = 0; $i < $groups ['count']; $i++) {
for ($k = 0; $k < $groups[$i][strtolower('group')]['count']; $k++) {
$grp[] = $groups[$i][strtolower('group')][$k];
}
}
$this->assertEquals([
'7310T270:Překladatelství:čeština - angličtina@ff.cuni.cz',
'7310T033:Český jazyk a literatura@ff.cuni.cz',
], $grp);
$role = '';
foreach (['testrole' => '7310T031:Český jazyk a literatura@ff.cuni.cz,7310T033:Český jazyk a literatura@ff.cuni.cz'] as $key => $val) {
$currentGroup = explode(',', $val);
// Remove whitespaces around the group-ID
$currentGroup = array_map('trim', $currentGroup);
if (0 < count(array_intersect($currentGroup, $grp))) {
$role = $key;
break;
}
}
$this->assertEquals('testrole', $role);
}
}

View File

@ -1,420 +0,0 @@
<?php
/**
* Copyright (c)2014-2014 heiglandreas
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIBILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @category
* @author Andreas Heigl<andreas@heigl.org>
* @copyright ©2014-2014 Andreas Heigl
* @license http://www.opesource.org/licenses/mit-license.php MIT-License
* @version 0.0
* @since 19.12.14
* @link https://github.com/heiglandreas/authLdap
*/
?><div class="wrap">
<?php if (! extension_loaded('ldap')) : ?>
<div class="error"><strong>Caveat:</strong> The LDAP-extension is not loaded!
Without that extension it is not possible to query an LDAP-Server! Please have a look
at <a href="http://php.net/manual/install.php">the PHP-Installation page</a>
</div>
<?php endif ?>
<h2>AuthLDAP Options</h2>
<form method="post" id="authLDAP_options" action="<?php echo $action;?>">
<h3 class="title">General Usage of authLDAP</h3>
<fieldset class="options">
<table class="form-table">
<tr>
<th>
<label for="authLDAPAuth">Enable Authentication via LDAP?</label>
</th>
<td>
<input type="checkbox" name="authLDAPAuth" id="authLDAPAuth" value="1"<?php echo $tChecked; ?>/>
</td>
</tr>
<tr>
<th>
<label for="authLDAPDebug">Debug AuthLDAP?</label>
</th>
<td>
<input type="checkbox" name="authLDAPDebug" id="authLDAPDebug" value="1"<?php echo $tDebugChecked; ?>/>
</td>
</tr>
<tr>
<th>
<label for="authLDAPDoNotOverwriteNonLdapUsers">Do not authenticate existing WordPress-Users</label>
</th>
<td>
<input type="checkbox" name="authLDAPDoNotOverwriteNonLdapUsers" id="authLDAPDoNotOverwriteNonLdapUsers" value="1"<?php echo $tDoNotOverwriteNonLdapUsers; ?>/>
<p class="description">
Shall we prohibit authenticating already in WordPress created users using LDAP? If you enable this, LDAP-Users with the same user-ID
as existing WordPress-Users can no longer take over the WordPress-Users account. This also means that LDAP-Users with the same User-ID as existing
WordPress-Users will <strong>not</strong> be able to authenticate anymore! Accounts that have been taken over already will not be affected by this setting.
</p>
<p class="description">This should only be checked if you know what you are doing!</p>
</td>
</tr>
<tr>
<th>
<label for="authLDAPCachePW">Save entered passwords in the wordpress user table?</label>
</th>
<td>
<input type="checkbox" name="authLDAPCachePW" id="authLDAPCachePW" value="1"<?php echo $tPWChecked; ?>/>
</td>
</tr>
<tr>
<th>
<label for="authLDAPGroupEnable">Map LDAP Groups to wordpress Roles?</label>
</th>
<td>
<input type="checkbox" name="authLDAPGroupEnable" id="authLDAPGroupEnable" value="1"<?php echo $tGroupChecked; ?>/>
<p class="description">
Search LDAP for user's groups and map to Wordpress Roles.
</p>
</td>
</tr>
</table>
</fieldset>
<h3 class="title">General Server Settings</h3>
<fieldset class="options">
<table class="form-table">
<tr>
<th>
<label for="authLDAPURI">LDAP URI</label>
</th>
<td>
<input type="text" name="authLDAPURI" id="authLDAPURI" placeholder="LDAP-URI"
class="regular-text" value="<?php echo $authLDAPURI; ?>"/>
<p class="description">
The <abbr title="Uniform Ressource Identifier">URI</abbr>
for connecting to the LDAP-Server. This usualy takes the form
<var>&lt;scheme&gt;://&lt;user&gt;:&lt;password&gt;@&lt;server&gt;/&lt;path&gt;</var>
according to RFC 1738.</p>
<p class="description">
In this case it schould be something like
<var>ldap://uid=adminuser,dc=example,c=com:secret@ldap.example.com/dc=basePath,dc=example,c=com</var>.
</p>
<p class="description">
If your LDAP accepts anonymous login, you can ommit the user and
password-Part of the URI
</p>
</td>
</tr>
<tr>
<th>
<label for="authLDAPURISeparator">LDAP URI-Separator</label>
</th>
<td>
<input type="text" name="authLDAPURISeparator" id="authLDAPURISeparator" placeholder="LDAP-URI Separator"
class="regular-text" value="<?php echo $authLDAPURISeparator; ?>"/>
<p class="description">
A separator that separates multiple LDAP-URIs from one another.
You can use that feature to try to authenticate against multiple LDAP-Servers
as long as they all have the same attribute-settings. The first LDAP-Server the user can
authenticate against will be used to handle the user.
</td>
</tr>
<tr>
<th>
<label for="authLDAPStartTLS" class="description">StartTLS</label>
</th>
<td>
<input type="checkbox" name="authLDAPStartTLS" id="authLDAPStartTLS" value="1"<?php echo $tStartTLSChecked; ?>/>
<p class="description">
Use StartTLS for encryption of ldap connections. This setting is not to be used in combination with ldaps connections (ldap:// only).
</p>
</td>
<tr>
<th scope="row">
<label for="authLDAPFilter" class="description">Filter</label>
</th>
<td>
<input type="text" name="authLDAPFilter" id="authLDAPFilter" placeholder="(uid=%s)"
class="regular-text" value="<?php echo $authLDAPFilter; ?>"/>
<p class="description">
Please provide a valid filter that can be used for querying the
<abbr title="Lightweight Directory Access Protocol">LDAP</abbr>
for the correct user. For more information on this
feature have a look at <a href="http://andreas.heigl.org/cat/dev/wp/authldap">http://andreas.heigl.org/cat/dev/wp/authldap</a>
</p>
<p class="description">
This field <strong>should</strong> include the string <code>%s</code>
that will be replaced with the username provided during log-in
</p>
<p class="description">
If you leave this field empty it defaults to <strong>(uid=%s)</strong>
</p>
</td>
</tr>
</table>
</fieldset>
<h3 class="title">Settings for creating new Users</h3>
<fieldset class="options">
<table class="form-table">
<tr>
<th scope="row">
<label for="authLDAPNameAttr">Name-Attribute</label>
</th>
<td>
<input type="text" name="authLDAPNameAttr" id="authLDAPNameAttr" placeholder="name"
class="regular-text" value="<?php echo $authLDAPNameAttr; ?>"/><br />
<p class="description">
Which Attribute from the LDAP contains the Full or the First name
of the user trying to log in.
</p>
<p class="description">
This defaults to <strong>name</strong>
</p>
</td>
</tr>
<tr>
<th scope="row">
<label for="authLDAPSecName">Second Name Attribute</label>
</th>
<td>
<input type="text" name="authLDAPSecName" id="authLDAPSecName" placeholder=""
class="regular-text" value="<?php echo $authLDAPSecName; ?>" />
<p class="description">
If the above Name-Attribute only contains the First Name of the
user you can here specify an Attribute that contains the second name.
</p>
<p class="description">
This field is empty by default
</p>
</td>
</tr>
<tr>
<th scope="row">
<label for="authLDAPUidAttr">User-ID Attribute</label>
</th>
<td>
<input type="text" name="authLDAPUidAttr" id="authLDAPUidAttr" placeholder="uid"
class="regular-text" value="<?php echo $authLDAPUidAttr; ?>" />
<p class="description">
Please give the Attribute, that is used to identify the user. This
should be the same as you used in the above <em>Filter</em>-Option
</p>
<p class="description">
This field defaults to <strong>uid</strong>
</p>
</td>
</tr>
<tr>
<th scope="row">
<label for="authLDAPMailAttr">Mail Attribute</label>
</th>
<td>
<input type="text" name="authLDAPMailAttr" id="authLDAPMailAttr" placeholder="mail"
class="regular-text" value="<?php echo $authLDAPMailAttr; ?>" />
<p class="description">
Which Attribute holds the eMail-Address of the user?
</p>
<p class="description">
If more than one eMail-Address are stored in the LDAP, only the first given is used
</p>
<p class="description">
This field defaults to <strong>mail</strong>
</p>
</td>
</tr>
<tr>
<th scope="row">
<label for="authLDAPWebAttr">Web-Attribute</label>
</th>
<td>
<input type="text" name="authLDAPWebAttr" id="authLDAPWebAttr" placeholder=""
class="regular-text" value="<?php echo $authLDAPWebAttr; ?>" />
<p class="description">
If your users have a personal page (URI) stored in the LDAP, it can
be provided here.
</p>
<p class="description">
This field is empty by default
</p>
</td>
</tr>
<tr>
<th scope="row">
<label for="authLDAPDefaultRole">Default Role</label>
</th>
<td>
<select name="authLDAPDefaultRole" id="authLDAPDefaultRole">
<option value="" <?php echo ( $authLDAPDefaultRole == '' ? 'selected="selected"' : '' ); ?>>
None (deny access)
</option>
<?php foreach ($roles->get_names() as $group => $vals) : ?>
<option value="<?php echo $group; ?>" <?php echo ( $authLDAPDefaultRole == $group ? 'selected="selected"' : '' ); ?>>
<?php echo $vals; ?>
</option>
<?php endforeach; ?>
</select>
<p class="description">
Here you can select the default role for users.
If you enable LDAP Groups below, they will take precedence over the Default Role.
</p>
<p class="description">
Existing users will retain their roles unless overriden by LDAP Groups below.
</p>
</td>
</tr>
</table>
</fieldset>
<div id="authldaprolemapping">
<h3 class="title">Groups for Roles</h3>
<fieldset class="options">
<table class="form-table">
<tr>
<th>
<label for="authLDAPGroupOverUser">LDAP Groups override role of existing users?</label>
</th>
<td>
<input type="checkbox" name="authLDAPGroupOverUser" id="authLDAPGroupOverUser" value="1"<?php echo $tGroupOverUserChecked; ?>/>
<p class="description">
If role determined by LDAP Group differs from existing Wordpress User's role, use LDAP Group.
</p>
</td>
</tr>
<tr>
<th scope="row">
<label for="authLDAPGroupBase">Group-Base</label>
</th>
<td>
<input type="text" name="authLDAPGroupBase" id="authLDAPGroupBase" placeholder=""
class="regular-text" value="<?php echo $authLDAPGroupBase; ?>" />
<p class="description">
This is the base dn to lookup groups.
</p>
<p class="description">
If empty the base dn of the LDAP URI will be used
</p>
</td>
</tr>
<tr>
<th scope="row">
<label for="authLDAPGroupAttr">Group-Attribute</label>
</th>
<td>
<input type="text" name="authLDAPGroupAttr" id="authLDAPGroupAttr" placeholder="gidNumber"
class="regular-text" value="<?php echo $authLDAPGroupAttr; ?>" />
<p class="description">
This is the attribute that defines the Group-ID that can be matched
against the Groups defined further down
</p>
<p class="description">
This field defaults to <strong>gidNumber</strong>
</p>
</td>
</tr>
<tr>
<th scope="row">
<label for="authLDAPGroupSeparator">Group-Separator</label>
</th>
<td>
<input type="text" name="authLDAPGroupSeparator" id="authLDAPGroupSeparator" placeholder=","
class="regular-text" value="<?php echo $authLDAPGroupSeparator; ?>" />
<p class="description">
This attribute defines the separator used for the Group-IDs listed in the
Groups defined further down. This is useful if the value of Group-Attribute
listed above can contain a comma (for example, when using the memberof attribute)
</p>
<p class="description">
This field defaults to <strong>, (comma)</strong>
</p>
</td>
</tr>
<tr>
<th scope="row">
<label for="authLDAPGroupFilter">Group-Filter</label>
</th>
<td>
<input type="text" name="authLDAPGroupFilter" id="authLDAPGroupFilter"
placeholder="(&amp;(objectClass=posixGroup)(memberUid=%s))"
class="regular-text" value="<?php echo $authLDAPGroupFilter; ?>" />
<p class="description">
Here you can add the filter for selecting groups for ther
currentlly logged in user
</p>
<p class="description">
The Filter should contain the string <code>%s</code> which will be replaced by
the login-name of the currently logged in user
</p>
<p class="description">
Alternatively the string <code>%dn%</code> will be replaced by the
DN of the currently logged in user. This can be helpfull if
group-memberships are defined with DNs rather than UIDs
</p>
<p class="description">This field defaults to
<strong>(&amp;(objectClass=posixGroup)(memberUid=%s))</strong>
</p>
</td>
</tr>
</table>
</fieldset>
<h3 class="title">Role - group mapping</h3>
<fieldset class="options">
<table class="form-table">
<?php
foreach ($roles->get_names() as $group => $vals) :
$aGroup=$authLDAPGroups[$group]; ?>
<tr>
<th scope="row">
<label for="authLDAPGroups[<?php echo $group; ?>]">
<?php echo $vals; ?>
</label>
</th>
<td>
<input type="text" name="authLDAPGroups[<?php echo $group; ?>]" id="authLDAPGroups[<?php echo $group; ?>]"
value="<?php echo $aGroup; ?>" />
<p class="description">What LDAP-Groups shall be matched to the <?php echo $vals; ?>-Role?</p>
<p class="description">Please provide a coma-separated list of values</p>
<p class="description">This field is empty by default</p>
</td>
</tr>
<?php endforeach; ?>
</table>
</fieldset>
</div>
<fieldset class="buttons">
<p class="submit">
<input type="submit" name="ldapOptionsSave" class="button button-primary" value="Save Changes" />
</p>
</fieldset>
</form>
</div>
<script type="text/javascript">
elem = document.getElementById('authLDAPGroupEnable');
if(! elem.checked) {
document.getElementById('authldaprolemapping').setAttribute('style', 'display:none;');
}
elem.addEventListener('change', function(e){
if(! e.target.checked) {
document.getElementById('authldaprolemapping').setAttribute('style', 'display:none;');
} else {
document.getElementById('authldaprolemapping').removeAttribute('style');
}
});
</script>