packages/ssoinabox-webui/root/usr/local/share/ssoinabox/bin/ldap-groups-to-dbm
author Dan Fuhry <dan@fuhry.us>
Fri, 11 Jan 2013 00:32:54 -0500
changeset 3 a044870a9d3d
parent 2 700d61d93b1b
permissions -rwxr-xr-x
Added password reset function

#!/usr/bin/perl

use strict;
use warnings;
use DB_File;
use Net::LDAP;
use YAML;

open my $fp, "<", "/usr/local/etc/ssoinabox/webcreds.yml" or die "failed to open yaml";
my $config = YAML::LoadFile $fp;
close $fp;

# connect to LDAP
my $ldap = Net::LDAP->new($config->{'ldap_server'})
	or die "Failed to connect to LDAP: $!";

$ldap->bind($config->{'ldap_manager'}->{'dn'}, password => $config->{'ldap_manager'}->{'password'})
	or die "Failed to bind to LDAP: $!";

# search for POSIX groups
my $lr = $ldap->search(
		base => $config->{'LDAP_BASEDN'}
		, filter => '(objectClass=posixGroup)'
	);

die "Failed to search LDAP..." if ( $lr->code );

# Fetch each group from LDAP...
my %users;

foreach my $entry ($lr->entries)
{
	my $groupname = $entry->get_value('cn');
	my $attrs = $entry->get_value('memberUID', asref => 1);
	foreach my $member (@$attrs)
	{
		# Make this a user-based map, as that is what the DBM uses.
		$users{$member} = [] if !defined($users{$member});
		push @{$users{$member}}, $groupname;
	}
}

# We're done with LDAP
$ldap->unbind;

# Prepare to write database file
my $dbm_file = "/etc/apache2/ldap-groups";
my %dbm_hash;
my ($key, $value);

# Open database file
tie %dbm_hash, "DB_File", $dbm_file, O_WRONLY or
	die "Unable to open DBM file $dbm_file: $!";

# write everything out
while ( ($key, $value) = each(%users) )
{
	$dbm_hash{$key} = sprintf('*:%s', join(',', @{$users{$key}}));
}

# Save and close database
untie %dbm_hash;

exit 0;

# debug - for viewing contents of the map

tie %dbm_hash, "DB_File", $dbm_file, O_RDONLY or
	die "Unable to open DBM file $dbm_file: $!";

while ( ($key, $value) = each(%dbm_hash) )
{
	print "$key => $value\n";
}