fix rt bug 339113
[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',
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             'use_roles' => 1,
42             'role_basedn' => 'ou=groups,dc=yourcompany,dc=com',
43             'role_filter' => '(&(objectClass=posixGroup)(member=%s))',
44             'role_scope' => 'one',
45             'role_field' => 'cn',
46             'role_value' => 'dn',
47             'role_search_options' => {
48                 'deref' => 'always',
49             },
50     );
51     
52     our $users = Catalyst::Authentication::Store::LDAP::Backend->new(\%config);
53
54     sub action : Local {
55         my ( $self, $c ) = @_;
56
57         $c->login( $users->get_user( $c->req->param("login") ),
58             $c->req->param("password") );
59     }
60
61 =head1 DESCRIPTION
62
63 You probably want L<Catalyst::Authentication::Store::LDAP>, unless
64 you are mixing several stores in a single app and one of them is LDAP.
65
66 Otherwise, this lets you create a store manually. 
67
68 See the L<Catalyst::Authentication::Store::LDAP> documentation for
69 an explanation of the configuration options.
70
71 =head1 METHODS
72
73 =cut
74
75 package Catalyst::Authentication::Store::LDAP::Backend;
76 use base qw( Class::Accessor::Fast );
77
78 use strict;
79 use warnings;
80
81 our $VERSION = '0.1003_01';
82
83 use Catalyst::Authentication::Store::LDAP::User;
84 use Net::LDAP;
85
86 BEGIN {
87     __PACKAGE__->mk_accessors(
88         qw( ldap_server ldap_server_options binddn
89             bindpw entry_class user_search_options
90             user_filter user_basedn user_scope
91             user_attrs user_field use_roles role_basedn
92             role_filter role_scope role_field role_value
93             role_search_options start_tls start_tls_options
94             user_results_filter
95             )
96     );
97 }
98
99 =head2 new($config)
100
101 Creates a new L<Catalyst::Authentication::Store::LDAP::Backend> object.
102 $config should be a hashref, which should contain the configuration options
103 listed in L<Catalyst::Authentication::Store::LDAP>'s documentation.
104
105 Also sets a few sensible defaults.
106
107 =cut
108
109 sub new {
110     my ( $class, $config ) = @_;
111
112     unless ( defined($config) && ref($config) eq "HASH" ) {
113         Catalyst::Exception->throw(
114             "Catalyst::Authentication::Store::LDAP::Backend needs to be configured with a hashref."
115         );
116     }
117     my %config_hash = %{$config};
118     $config_hash{'binddn'}      ||= 'anonymous';
119     $config_hash{'user_filter'} ||= '(uid=%s)';
120     $config_hash{'user_scope'}  ||= 'sub';
121     $config_hash{'user_field'}  ||= 'uid';
122     $config_hash{'role_filter'} ||= '(memberUid=%s)';
123     $config_hash{'role_scope'}  ||= 'sub';
124     $config_hash{'role_field'}  ||= 'cn';
125     $config_hash{'use_roles'}   ||= '1';
126     $config_hash{'start_tls'}   ||= '0';
127     $config_hash{'entry_class'} ||= 'Catalyst::Model::LDAP::Entry';
128
129     my $self = \%config_hash;
130     bless( $self, $class );
131     return $self;
132 }
133
134 =head2 find_user( I<authinfo> )
135
136 Creates a L<Catalyst::Authentication::Store::LDAP::User> object
137 for the given User ID.  This is the preferred mechanism for getting a 
138 given User out of the Store.
139
140 I<authinfo> should be a hashref with a key of either C<id> or
141 C<username>. The value will be compared against the LDAP C<user_field> field.
142
143 =cut
144
145 sub find_user {
146     my ( $self, $authinfo, $c ) = @_;
147     return $self->get_user( $authinfo->{id} || $authinfo->{username} );
148 }
149
150 =head2 get_user($id)
151
152 Creates a L<Catalyst::Authentication::Store::LDAP::User> object
153 for the given User ID.  This is the preferred mechanism for getting a 
154 given User out of the Store.
155
156 =cut
157
158 sub get_user {
159     my ( $self, $id ) = @_;
160     my $user = Catalyst::Authentication::Store::LDAP::User->new( $self,
161         $self->lookup_user($id) );
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     $binddn ||= $self->binddn;
218     $bindpw ||= $self->bindpw;
219     if ( $binddn eq "anonymous" ) {
220         my $mesg = $ldap->bind;
221         if ( $mesg->is_error ) {
222             Catalyst::Exception->throw( "Error on Bind: " . $mesg->error );
223         }
224     }
225     else {
226         if ($bindpw) {
227             my $mesg = $ldap->bind( $binddn, 'password' => $bindpw );
228             if ( $mesg->is_error ) {
229
230                 # If we're not checking this bind for authentication purposes
231                 # Go ahead an blow up if we fail.
232                 if ( $forauth ne 'forauth' ) {
233                     Catalyst::Exception->throw(
234                         "Error on Initial Bind: " . $mesg->error );
235                 }
236                 else {
237                     return undef;
238                 }
239             }
240         }
241         else {
242             my $mesg = $ldap->bind($binddn);
243             if ( $mesg->is_error ) {
244                 return undef;
245             }
246         }
247     }
248     return $ldap;
249 }
250
251 =head2 lookup_user($id)
252
253 Given a User ID, this method will:
254
255   A) Bind to the directory using the configured binddn and bindpw
256   B) Perform a search for the User Object in the directory, using
257      user_basedn, user_filter, and user_scope.
258   C) Assuming we found the object, we will walk it's attributes 
259      using L<Net::LDAP::Entry>'s get_value method.  We store the
260      results in a hashref.
261   D) Return a hashref that looks like: 
262      
263      $results = {
264         'ldap_entry' => $entry, # The Net::LDAP::Entry object
265         'attributes' => $attributes,
266      }
267
268 This method is usually only called by find_user().
269
270 =cut
271
272 sub lookup_user {
273     my ( $self, $id ) = @_;
274
275     # No sneaking in wildcards!
276     if ( $id =~ /\*/ ) {
277         Catalyst::Exception->throw("ID $id contains wildcards!");
278     }
279     my $ldap = $self->ldap_bind;
280     my @searchopts;
281     if ( defined( $self->user_basedn ) ) {
282         push( @searchopts, 'base' => $self->user_basedn );
283     }
284     else {
285         Catalyst::Exception->throw(
286             "You must set user_basedn before looking up users!");
287     }
288     my $filter = $self->_replace_filter( $self->user_filter, $id );
289     push( @searchopts, 'filter' => $filter );
290     push( @searchopts, 'scope'  => $self->user_scope );
291     if ( defined( $self->user_search_options ) ) {
292         push( @searchopts, %{ $self->user_search_options } );
293     }
294     my $usersearch = $ldap->search(@searchopts);
295     if ( $usersearch->is_error ) {
296         Catalyst::Exception->throw(
297             "LDAP Error while searching for user: " . $usersearch->error );
298     }
299     my $userentry;
300     my $user_field     = $self->user_field;
301     my $results_filter = $self->user_results_filter;
302     my $entry;
303     if ( defined($results_filter) ) {
304         $entry = &$results_filter($usersearch);
305     }
306     else {
307         $entry = $usersearch->pop_entry;
308     }
309     if ( $usersearch->pop_entry ) {
310         Catalyst::Exception->throw(
311                   "More than one entry matches user search.\n"
312                 . "Consider defining a user_results_filter sub." );
313     }
314
315     # a little extra sanity check with the 'eq' since LDAP already
316     # says it matches.
317     # NOTE that Net::LDAP returns exactly what you asked for, but
318     # because LDAP is often case insensitive, FoO can match foo
319     # and so we normalize with lc().
320     if ( defined($entry) ) {
321         unless ( lc( $entry->get_value($user_field) ) eq lc($id) ) {
322             Catalyst::Exception->throw(
323                 "LDAP claims '$user_field' equals '$id' but results entry does not match."
324             );
325         }
326         $userentry = $entry;
327     }
328
329     $ldap->unbind;
330     $ldap->disconnect;
331     unless ($userentry) {
332         return undef;
333     }
334     my $attrhash;
335     foreach my $attr ( $userentry->attributes ) {
336         my @attrvalues = $userentry->get_value($attr);
337         if ( scalar(@attrvalues) == 1 ) {
338             $attrhash->{ lc($attr) } = $attrvalues[0];
339         }
340         else {
341             $attrhash->{ lc($attr) } = \@attrvalues;
342         }
343     }
344     my $load_class = $self->entry_class . ".pm";
345     $load_class =~ s|::|/|g;
346
347     eval { require $load_class };
348     if ( !$@ ) {
349         bless( $userentry, $self->entry_class );
350         $userentry->{_use_unicode}++;
351     }
352     my $rv = {
353         'ldap_entry' => $userentry,
354         'attributes' => $attrhash,
355     };
356     return $rv;
357 }
358
359 =head2 lookup_roles($userobj)
360
361 This method looks up the roles for a given user.  It takes a 
362 L<Catalyst::Authentication::Store::LDAP::User> object
363 as it's sole argument.
364
365 It returns an array containing the role_field attribute from all the
366 objects that match it's criteria.
367
368 =cut
369
370 sub lookup_roles {
371     my ( $self, $userobj ) = @_;
372     if ( $self->use_roles == 0 || $self->use_roles =~ /^false$/i ) {
373         return undef;
374     }
375     my $ldap = $self->ldap_bind;
376     my @searchopts;
377     if ( defined( $self->role_basedn ) ) {
378         push( @searchopts, 'base' => $self->role_basedn );
379     }
380     else {
381         Catalyst::Exception->throw(
382             "You must set up role_basedn before looking up roles!");
383     }
384     my $filter_value = $userobj->has_attribute( $self->role_value );
385     if ( !defined($filter_value) ) {
386         Catalyst::Exception->throw( "User object "
387                 . $userobj->username
388                 . " has no "
389                 . $self->role_value
390                 . " attribute, so I can't look up it's roles!" );
391     }
392     my $filter = $self->_replace_filter( $self->role_filter, $filter_value );
393     push( @searchopts, 'filter' => $filter );
394     push( @searchopts, 'scope'  => $self->role_scope );
395     push( @searchopts, 'attrs'  => [ $self->role_field ] );
396     if ( defined( $self->role_search_options ) ) {
397         push( @searchopts, %{ $self->role_search_options } );
398     }
399     my $rolesearch = $ldap->search(@searchopts);
400     my @roles;
401 RESULT: foreach my $entry ( $rolesearch->entries ) {
402         push( @roles, $entry->get_value( $self->role_field ) );
403     }
404     return @roles;
405 }
406
407 sub _replace_filter {
408     my $self    = shift;
409     my $filter  = shift;
410     my $replace = shift;
411     $filter =~ s/\%s/$replace/g;
412     return $filter;
413 }
414
415 =head2 user_supports
416
417 Returns the value of 
418 Catalyst::Authentication::Store::LDAP::User->supports(@_).
419
420 =cut
421
422 sub user_supports {
423     my $self = shift;
424
425     # this can work as a class method
426     Catalyst::Authentication::Store::LDAP::User->supports(@_);
427 }
428
429 =head2 from_session( I<id> )
430
431 Returns get_user() for I<id>.
432
433 =cut
434
435 sub from_session {
436     my ( $self, $c, $id ) = @_;
437     $self->get_user($id);
438 }
439
440 1;
441
442 __END__
443
444 =head1 AUTHORS
445
446 Adam Jacob <holoway@cpan.org>
447
448 Some parts stolen shamelessly and entirely from
449 L<Catalyst::Plugin::Authentication::Store::Htpasswd>.
450
451 Currently maintained by Peter Karman <karman@cpan.org>.
452
453 =head1 THANKS
454
455 To nothingmuch, ghenry, castaway and the rest of #catalyst for the help. :)
456
457 =head1 SEE ALSO
458
459 L<Catalyst::Authentication::Store::LDAP>, L<Catalyst::Authentication::Store::LDAP::User>, L<Catalyst::Plugin::Authentication>, L<Net::LDAP>
460
461 =head1 COPYRIGHT & LICENSE
462
463 Copyright (c) 2005 the aforementioned authors. All rights
464 reserved. This program is free software; you can redistribute
465 it and/or modify it under the same terms as Perl itself.
466
467 =cut
468