if username is passed to bind, assume password is passed too and do not default to...
[catagits/Catalyst-Authentication-Store-LDAP.git] / lib / Catalyst / Authentication / Store / LDAP / Backend.pm
1
2 =pod
3
4 =head1 NAME
5
6 Catalyst::Authentication::Store::LDAP::Backend 
7   - LDAP authentication storage backend.
8
9 =head1 SYNOPSIS
10
11     # you probably just want Store::LDAP under most cases,
12     # but if you insist you can instantiate your own store:
13
14     use Catalyst::Authentication::Store::LDAP::Backend;
15
16     use Catalyst qw/
17         Authentication
18         Authentication::Credential::Password
19     /;
20
21     my %config = (
22             'ldap_server' => 'ldap1.yourcompany.com',
23             'ldap_server_options' => {
24                 'timeout' => 30,
25             },
26             'binddn' => 'anonymous',
27             'bindpw' => 'dontcarehow',
28             'start_tls' => 1,
29             'start_tls_options' => {
30                 'verify' => 'none',
31             },
32             'user_basedn' => 'ou=people,dc=yourcompany,dc=com',
33             'user_filter' => '(&(objectClass=posixAccount)(uid=%s))',
34             'user_scope' => 'one',  # or 'sub' for Active Directory
35             'user_field' => 'uid',
36             'user_search_options' => {
37                 'deref' => 'always',
38             },
39             'user_results_filter' => sub { return shift->pop_entry },
40             'entry_class' => 'MyApp::LDAP::Entry',
41             'user_class' => 'MyUser',
42             'use_roles' => 1,
43             'role_basedn' => 'ou=groups,dc=yourcompany,dc=com',
44             'role_filter' => '(&(objectClass=posixGroup)(member=%s))',
45             'role_scope' => 'one',
46             'role_field' => 'cn',
47             'role_value' => 'dn',
48             'role_search_options' => {
49                 'deref' => 'always',
50             },
51             'role_search_as_user' => 0,
52     );
53     
54     our $users = Catalyst::Authentication::Store::LDAP::Backend->new(\%config);
55
56 =head1 DESCRIPTION
57
58 You probably want L<Catalyst::Authentication::Store::LDAP>.
59
60 Otherwise, this lets you create a store manually.
61
62 See the L<Catalyst::Authentication::Store::LDAP> documentation for
63 an explanation of the configuration options.
64
65 =head1 METHODS
66
67 =cut
68
69 package Catalyst::Authentication::Store::LDAP::Backend;
70 use base qw( Class::Accessor::Fast );
71
72 use strict;
73 use warnings;
74
75 our $VERSION = '1.012';
76
77 use Catalyst::Authentication::Store::LDAP::User;
78 use Net::LDAP;
79 use Catalyst::Utils ();
80
81 BEGIN {
82     __PACKAGE__->mk_accessors(
83         qw( ldap_server ldap_server_options binddn
84             bindpw entry_class user_search_options
85             user_filter user_basedn user_scope
86             user_attrs user_field use_roles role_basedn
87             role_filter role_scope role_field role_value
88             role_search_options start_tls start_tls_options
89             user_results_filter user_class role_search_as_user
90             )
91     );
92 }
93
94 =head2 new($config)
95
96 Creates a new L<Catalyst::Authentication::Store::LDAP::Backend> object.
97 $config should be a hashref, which should contain the configuration options
98 listed in L<Catalyst::Authentication::Store::LDAP>'s documentation.
99
100 Also sets a few sensible defaults.
101
102 =cut
103
104 sub new {
105     my ( $class, $config ) = @_;
106
107     unless ( defined($config) && ref($config) eq "HASH" ) {
108         Catalyst::Exception->throw(
109             "Catalyst::Authentication::Store::LDAP::Backend needs to be configured with a hashref."
110         );
111     }
112     my %config_hash = %{$config};
113     $config_hash{'binddn'}      ||= 'anonymous';
114     $config_hash{'user_filter'} ||= '(uid=%s)';
115     $config_hash{'user_scope'}  ||= 'sub';
116     $config_hash{'user_field'}  ||= 'uid';
117     $config_hash{'role_filter'} ||= '(memberUid=%s)';
118     $config_hash{'role_scope'}  ||= 'sub';
119     $config_hash{'role_field'}  ||= 'cn';
120     $config_hash{'use_roles'}   ||= '1';
121     $config_hash{'start_tls'}   ||= '0';
122     $config_hash{'entry_class'} ||= 'Catalyst::Model::LDAP::Entry';
123     $config_hash{'user_class'}
124         ||= 'Catalyst::Authentication::Store::LDAP::User';
125     $config_hash{'role_search_as_user'} ||= 0;
126
127     Catalyst::Utils::ensure_class_loaded( $config_hash{'user_class'} );
128     my $self = \%config_hash;
129     bless( $self, $class );
130     return $self;
131 }
132
133 =head2 find_user( I<authinfo>, $c )
134
135 Creates a L<Catalyst::Authentication::Store::LDAP::User> object
136 for the given User ID.  This is the preferred mechanism for getting a 
137 given User out of the Store.
138
139 I<authinfo> should be a hashref with a key of either C<id> or
140 C<username>. The value will be compared against the LDAP C<user_field> field.
141
142 =cut
143
144 sub find_user {
145     my ( $self, $authinfo, $c ) = @_;
146     return $self->get_user( $authinfo->{id} || $authinfo->{username}, $c );
147 }
148
149 =head2 get_user( I<id>, $c)
150
151 Creates a L<Catalyst::Authentication::Store::LDAP::User> object
152 for the given User ID, or calls C<new> on the class specified in
153 C<user_class>.  This instance of the store object, the results of
154 C<lookup_user> and $c are passed as arguments (in that order) to C<new>.
155 This is the preferred mechanism for getting a given User out of the Store.
156
157 =cut
158
159 sub get_user {
160     my ( $self, $id, $c ) = @_;
161     my $user = $self->user_class->new( $self, $self->lookup_user($id), $c );
162     return $user;
163 }
164
165 =head2 ldap_connect
166
167 Returns a L<Net::LDAP> object, connected to your LDAP server. (According
168 to how you configured the Backend, of course)
169
170 =cut
171
172 sub ldap_connect {
173     my ($self) = shift;
174     my $ldap;
175     if ( defined( $self->ldap_server_options() ) ) {
176         $ldap
177             = Net::LDAP->new( $self->ldap_server,
178             %{ $self->ldap_server_options } )
179             or Catalyst::Exception->throw($@);
180     }
181     else {
182         $ldap = Net::LDAP->new( $self->ldap_server )
183             or Catalyst::Exception->throw($@);
184     }
185     if ( defined( $self->start_tls ) && $self->start_tls =~ /(1|true)/i ) {
186         my $mesg;
187         if ( defined( $self->start_tls_options ) ) {
188             $mesg = $ldap->start_tls( %{ $self->start_tls_options } );
189         }
190         else {
191             $mesg = $ldap->start_tls;
192         }
193         if ( $mesg->is_error ) {
194             Catalyst::Exception->throw( "TLS Error: " . $mesg->error );
195         }
196     }
197     return $ldap;
198 }
199
200 =head2 ldap_bind($ldap, $binddn, $bindpw)
201
202 Bind's to the directory.  If $ldap is undef, it will connect to the
203 LDAP server first.  $binddn should be the DN of the object you wish
204 to bind as, and $bindpw the password.
205
206 If $binddn is "anonymous", an anonymous bind will be performed.
207
208 =cut
209
210 sub ldap_bind {
211     my ( $self, $ldap, $binddn, $bindpw, $forauth ) = @_;
212     $forauth ||= 0;
213     $ldap ||= $self->ldap_connect;
214     if ( !defined($ldap) ) {
215         Catalyst::Exception->throw("LDAP Server undefined!");
216     }
217
218     # if username is present, make sure password is present too.
219     # see https://rt.cpan.org/Ticket/Display.html?id=81908
220     if ( !defined $binddn ) {
221         $binddn = $self->binddn;
222         $bindpw = $self->bindpw;
223     }
224
225     if ( $binddn eq "anonymous" ) {
226         $self->_ldap_bind_anon($ldap);
227     }
228     else {
229         if ($bindpw) {
230             my $mesg = $ldap->bind( $binddn, 'password' => $bindpw );
231             if ( $mesg->is_error ) {
232
233                 # If we're not checking this bind for authentication purposes
234                 # Go ahead an blow up if we fail.
235                 if ( $forauth ne 'forauth' ) {
236                     Catalyst::Exception->throw(
237                         "Error on Initial Bind: " . $mesg->error );
238                 }
239                 else {
240                     return undef;
241                 }
242             }
243         }
244         else {
245             $self->_ldap_bind_anon( $ldap, $binddn );
246         }
247     }
248     return $ldap;
249 }
250
251 sub _ldap_bind_anon {
252     my ( $self, $ldap, $dn ) = @_;
253     my $mesg = $ldap->bind($dn);
254     if ( $mesg->is_error ) {
255         Catalyst::Exception->throw( "Error on Bind: " . $mesg->error );
256     }
257 }
258
259 =head2 lookup_user($id)
260
261 Given a User ID, this method will:
262
263   A) Bind to the directory using the configured binddn and bindpw
264   B) Perform a search for the User Object in the directory, using
265      user_basedn, user_filter, and user_scope.
266   C) Assuming we found the object, we will walk it's attributes
267      using L<Net::LDAP::Entry>'s get_value method.  We store the
268      results in a hashref. If we do not find the object, then
269      undef is returned.
270   D) Return a hashref that looks like:
271
272      $results = {
273         'ldap_entry' => $entry, # The Net::LDAP::Entry object
274         'attributes' => $attributes,
275      }
276
277 This method is usually only called by find_user().
278
279 =cut
280
281 sub lookup_user {
282     my ( $self, $id ) = @_;
283
284     # No sneaking in wildcards!
285     if ( $id =~ /\*/ ) {
286         Catalyst::Exception->throw("ID $id contains wildcards!");
287     }
288
289     # Trim trailing space or we confuse ourselves
290     $id =~ s/\s+$//;
291     my $ldap = $self->ldap_bind;
292     my @searchopts;
293     if ( defined( $self->user_basedn ) ) {
294         push( @searchopts, 'base' => $self->user_basedn );
295     }
296     else {
297         Catalyst::Exception->throw(
298             "You must set user_basedn before looking up users!");
299     }
300     my $filter = $self->_replace_filter( $self->user_filter, $id );
301     push( @searchopts, 'filter' => $filter );
302     push( @searchopts, 'scope'  => $self->user_scope );
303     if ( defined( $self->user_search_options ) ) {
304         push( @searchopts, %{ $self->user_search_options } );
305     }
306     my $usersearch = $ldap->search(@searchopts);
307
308     return undef if ( $usersearch->is_error );
309
310     my $userentry;
311     my $user_field     = $self->user_field;
312     my $results_filter = $self->user_results_filter;
313     my $entry;
314     if ( defined($results_filter) ) {
315         $entry = &$results_filter($usersearch);
316     }
317     else {
318         $entry = $usersearch->pop_entry;
319     }
320     if ( $usersearch->pop_entry ) {
321         Catalyst::Exception->throw(
322                   "More than one entry matches user search.\n"
323                 . "Consider defining a user_results_filter sub." );
324     }
325
326     # a little extra sanity check with the 'eq' since LDAP already
327     # says it matches.
328     # NOTE that Net::LDAP returns exactly what you asked for, but
329     # because LDAP is often case insensitive, FoO can match foo
330     # and so we normalize with lc().
331     if ( defined($entry) ) {
332         unless ( lc( $entry->get_value($user_field) ) eq lc($id) ) {
333             Catalyst::Exception->throw(
334                 "LDAP claims '$user_field' equals '$id' but results entry does not match."
335             );
336         }
337         $userentry = $entry;
338     }
339
340     $ldap->unbind;
341     $ldap->disconnect;
342     unless ($userentry) {
343         return undef;
344     }
345     my $attrhash;
346     foreach my $attr ( $userentry->attributes ) {
347         my @attrvalues = $userentry->get_value($attr);
348         if ( scalar(@attrvalues) == 1 ) {
349             $attrhash->{ lc($attr) } = $attrvalues[0];
350         }
351         else {
352             $attrhash->{ lc($attr) } = \@attrvalues;
353         }
354     }
355
356     eval { Catalyst::Utils::ensure_class_loaded( $self->entry_class ) };
357     if ( !$@ ) {
358         bless( $userentry, $self->entry_class );
359         $userentry->{_use_unicode}++;
360     }
361     my $rv = {
362         'ldap_entry' => $userentry,
363         'attributes' => $attrhash,
364     };
365     return $rv;
366 }
367
368 =head2 lookup_roles($userobj, [$ldap])
369
370 This method looks up the roles for a given user.  It takes a 
371 L<Catalyst::Authentication::Store::LDAP::User> object
372 as it's first argument, and can optionally take a I<Net::LDAP> object which
373 is used rather than the default binding if supplied.
374
375 It returns an array containing the role_field attribute from all the
376 objects that match it's criteria.
377
378 =cut
379
380 sub lookup_roles {
381     my ( $self, $userobj, $ldap ) = @_;
382     if ( $self->use_roles == 0 || $self->use_roles =~ /^false$/i ) {
383         return undef;
384     }
385     $ldap ||= $self->ldap_bind;
386     my @searchopts;
387     if ( defined( $self->role_basedn ) ) {
388         push( @searchopts, 'base' => $self->role_basedn );
389     }
390     else {
391         Catalyst::Exception->throw(
392             "You must set up role_basedn before looking up roles!");
393     }
394     my $filter_value = $userobj->has_attribute( $self->role_value );
395     if ( !defined($filter_value) ) {
396         Catalyst::Exception->throw( "User object "
397                 . $userobj->username
398                 . " has no "
399                 . $self->role_value
400                 . " attribute, so I can't look up it's roles!" );
401     }
402     my $filter = $self->_replace_filter( $self->role_filter, $filter_value );
403     push( @searchopts, 'filter' => $filter );
404     push( @searchopts, 'scope'  => $self->role_scope );
405     push( @searchopts, 'attrs'  => [ $self->role_field ] );
406     if ( defined( $self->role_search_options ) ) {
407         push( @searchopts, %{ $self->role_search_options } );
408     }
409     my $rolesearch = $ldap->search(@searchopts);
410     my @roles;
411 RESULT: foreach my $entry ( $rolesearch->entries ) {
412         push( @roles, $entry->get_value( $self->role_field ) );
413     }
414     return @roles;
415 }
416
417 sub _replace_filter {
418     my $self    = shift;
419     my $filter  = shift;
420     my $replace = shift;
421     $filter =~ s/\%s/$replace/g;
422     return $filter;
423 }
424
425 =head2 user_supports
426
427 Returns the value of 
428 Catalyst::Authentication::Store::LDAP::User->supports(@_).
429
430 =cut
431
432 sub user_supports {
433     my $self = shift;
434
435     # this can work as a class method
436     Catalyst::Authentication::Store::LDAP::User->supports(@_);
437 }
438
439 =head2 from_session( I<id>, I<$c> )
440
441 Returns get_user() for I<id>.
442
443 =cut
444
445 sub from_session {
446     my ( $self, $c, $id ) = @_;
447     $self->get_user( $id, $c );
448 }
449
450 1;
451
452 __END__
453
454 =head1 AUTHORS
455
456 Adam Jacob <holoway@cpan.org>
457
458 Some parts stolen shamelessly and entirely from
459 L<Catalyst::Plugin::Authentication::Store::Htpasswd>.
460
461 Currently maintained by Peter Karman <karman@cpan.org>.
462
463 =head1 THANKS
464
465 To nothingmuch, ghenry, castaway and the rest of #catalyst for the help. :)
466
467 =head1 SEE ALSO
468
469 L<Catalyst::Authentication::Store::LDAP>, L<Catalyst::Authentication::Store::LDAP::User>, L<Catalyst::Plugin::Authentication>, L<Net::LDAP>
470
471 =head1 COPYRIGHT & LICENSE
472
473 Copyright (c) 2005 the aforementioned authors. All rights
474 reserved. This program is free software; you can redistribute
475 it and/or modify it under the same terms as Perl itself.
476
477 =cut
478