App-Dochazka-REST

 view release on metacpan or  search on metacpan

lib/App/Dochazka/REST/LDAP.pm  view on Meta::CPAN

# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# *************************************************************************
#
# LDAP module
#

package App::Dochazka::REST::LDAP;

use 5.012;
use strict;
use warnings;

use App::CELL qw( $CELL $log $site );
use Params::Validate qw( :all );



=head1 NAME

App::Dochazka::REST::LDAP - LDAP module (for authentication)



=head1 DESCRIPTION

Container for LDAP-related stuff.

=cut



=head1 EXPORTS

=cut

use Exporter qw( import );
our @EXPORT_OK = qw(
    autocreate_employee
    ldap_exists
    ldap_auth
    ldap_search
);



=head1 METHODS


=head2 ldap_exists

Takes a nick. Returns true or false. Determines if the nick exists in the LDAP database.
Any errors in communication with the LDAP server are written to the log.

=cut

# $ldap and $dn are used by both 'ldap_exists' and 'ldap_search'
my ( $ldap, $dn );

sub ldap_exists {
    my ( $nick ) = validate_pos( @_, { type => SCALAR } );

    return 0 unless $site->DOCHAZKA_LDAP;

    require Net::LDAP; 

    my $server = $site->DOCHAZKA_LDAP_SERVER;
    $ldap = Net::LDAP->new( $server );
    $log->error("$@") unless $ldap;
    return 0 unless $ldap;

    $log->info( "Connected to LDAP server $server to look up $nick" );
    
    if ( ldap_search( $ldap, $nick, 'uid' ) ) {
        $log->info( "Found employee $nick in LDAP (DN $dn)" );
        return 1;
    }
    return 0;
}


=head2 ldap_search

Given Net::LDAP handle, LDAP field, and nick, search for the nick in
the given field (e.g. 'uid', 'cn' etc.). Returns value of LDAP property
specified in $prop.

=cut

sub ldap_search {
    my ( $ldap, $nick, $prop ) = @_;
    $nick = $nick || '';
    my $base = $site->DOCHAZKA_LDAP_BASE || '';
    my $field = $site->DOCHAZKA_LDAP_MAPPING->{nick} || '';
    my $filter = $site->DOCHAZKA_LDAP_FILTER || '';
    my $prop_value;

    require Net::LDAP::Filter;

    $filter = Net::LDAP::Filter->new( "(&" .
                                           $filter .
                                           "($field=$nick)" .
                                           ")"
                                    );

    my ($mesg, $entry, $count);

    $log->info( "Running LDAP search with filter " . $filter->as_string );

    $mesg = $ldap->search(
                           base => "$base",
                           scope => "sub",
                           filter => $filter
                         );

    # code == 0 is success, code >= 1 is failure
    die $mesg->error unless $mesg->code == 0;

    $count = 0;
    for $entry ($mesg->entries) {
        $count += 1;



( run in 0.928 second using v1.01-cache-2.11-cpan-df04353d9ac )