e8f29c97509f9fda4768ef1a9232655d2af97b66
[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             '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 = '0.1005';
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'}  ||= 'Catalyst::Authentication::Store::LDAP::User';
124     $config_hash{'role_search_as_user'} ||= 0;
125
126     Catalyst::Utils::ensure_class_loaded($config_hash{'user_class'});
127     my $self = \%config_hash;
128     bless( $self, $class );
129     return $self;
130 }
131
132 =head2 find_user( I<authinfo>, $c )
133
134 Creates a L<Catalyst::Authentication::Store::LDAP::User> object
135 for the given User ID.  This is the preferred mechanism for getting a 
136 given User out of the Store.
137
138 I<authinfo> should be a hashref with a key of either C<id> or
139 C<username>. The value will be compared against the LDAP C<user_field> field.
140
141 =cut
142
143 sub find_user {
144     my ( $self, $authinfo, $c ) = @_;
145     return $self->get_user( $authinfo->{id} || $authinfo->{username}, $c );
146 }
147
148 =head2 get_user($id)
149
150 Creates a L<Catalyst::Authentication::Store::LDAP::User> object
151 for the given User ID, or calls C<new> on the class specified in
152 C<user_class>.  This instance of the store object, the results of
153 C<lookup_user> and $c are passed as arguments (in that order) to C<new>.
154 This is the preferred mechanism for getting a given User out of the Store.
155
156 =cut
157
158 sub get_user {
159     my ( $self, $id, $c ) = @_;
160     my $user = $self->user_class->new( $self,
161         $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     $binddn ||= $self->binddn;
218     $bindpw ||= $self->bindpw;
219     if ( $binddn eq "anonymous" ) {
220         $self->_ldap_bind_anon($ldap);
221     }
222     else {
223         if ($bindpw) {
224             my $mesg = $ldap->bind( $binddn, 'password' => $bindpw );
225             if ( $mesg->is_error ) {
226
227                 # If we're not checking this bind for authentication purposes
228                 # Go ahead an blow up if we fail.
229                 if ( $forauth ne 'forauth' ) {
230                     Catalyst::Exception->throw(
231                         "Error on Initial Bind: " . $mesg->error );
232                 }
233                 else {
234                     return undef;
235                 }
236             }
237         }
238         else {
239             $self->_ldap_bind_anon($ldap, $binddn);
240         }
241     }
242     return $ldap;
243 }
244
245 sub _ldap_bind_anon {
246     my ($self, $ldap, $dn) = @_;
247     my $mesg = $ldap->bind($dn);
248     if ( $mesg->is_error ) {
249         Catalyst::Exception->throw( "Error on Bind: " . $mesg->error );
250     }
251 }
252
253 =head2 lookup_user($id)
254
255 Given a User ID, this method will:
256
257   A) Bind to the directory using the configured binddn and bindpw
258   B) Perform a search for the User Object in the directory, using
259      user_basedn, user_filter, and user_scope.
260   C) Assuming we found the object, we will walk it's attributes
261      using L<Net::LDAP::Entry>'s get_value method.  We store the
262      results in a hashref. If we do not find the object, then
263      undef is returned.
264   D) Return a hashref that looks like:
265
266      $results = {
267         'ldap_entry' => $entry, # The Net::LDAP::Entry object
268         'attributes' => $attributes,
269      }
270
271 This method is usually only called by find_user().
272
273 =cut
274
275 sub lookup_user {
276     my ( $self, $id ) = @_;
277
278     # No sneaking in wildcards!
279     if ( $id =~ /\*/ ) {
280         Catalyst::Exception->throw("ID $id contains wildcards!");
281     }
282     # Trim trailing space or we confuse ourselves
283     $id =~ s/\s+$//;
284     my $ldap = $self->ldap_bind;
285     my @searchopts;
286     if ( defined( $self->user_basedn ) ) {
287         push( @searchopts, 'base' => $self->user_basedn );
288     }
289     else {
290         Catalyst::Exception->throw(
291             "You must set user_basedn before looking up users!");
292     }
293     my $filter = $self->_replace_filter( $self->user_filter, $id );
294     push( @searchopts, 'filter' => $filter );
295     push( @searchopts, 'scope'  => $self->user_scope );
296     if ( defined( $self->user_search_options ) ) {
297         push( @searchopts, %{ $self->user_search_options } );
298     }
299     my $usersearch = $ldap->search(@searchopts);
300
301     return undef if ( $usersearch->is_error );
302
303     my $userentry;
304     my $user_field     = $self->user_field;
305     my $results_filter = $self->user_results_filter;
306     my $entry;
307     if ( defined($results_filter) ) {
308         $entry = &$results_filter($usersearch);
309     }
310     else {
311         $entry = $usersearch->pop_entry;
312     }
313     if ( $usersearch->pop_entry ) {
314         Catalyst::Exception->throw(
315                   "More than one entry matches user search.\n"
316                 . "Consider defining a user_results_filter sub." );
317     }
318
319     # a little extra sanity check with the 'eq' since LDAP already
320     # says it matches.
321     # NOTE that Net::LDAP returns exactly what you asked for, but
322     # because LDAP is often case insensitive, FoO can match foo
323     # and so we normalize with lc().
324     if ( defined($entry) ) {
325         unless ( lc( $entry->get_value($user_field) ) eq lc($id) ) {
326             Catalyst::Exception->throw(
327                 "LDAP claims '$user_field' equals '$id' but results entry does not match."
328             );
329         }
330         $userentry = $entry;
331     }
332
333     $ldap->unbind;
334     $ldap->disconnect;
335     unless ($userentry) {
336         return undef;
337     }
338     my $attrhash;
339     foreach my $attr ( $userentry->attributes ) {
340         my @attrvalues = $userentry->get_value($attr);
341         if ( scalar(@attrvalues) == 1 ) {
342             $attrhash->{ lc($attr) } = $attrvalues[0];
343         }
344         else {
345             $attrhash->{ lc($attr) } = \@attrvalues;
346         }
347     }
348     
349     eval { Catalyst::Utils::ensure_class_loaded($self->entry_class) };
350     if ( !$@ ) {
351         bless( $userentry, $self->entry_class );
352         $userentry->{_use_unicode}++;
353     }
354     my $rv = {
355         'ldap_entry' => $userentry,
356         'attributes' => $attrhash,
357     };
358     return $rv;
359 }
360
361 =head2 lookup_roles($userobj, [$ldap])
362
363 This method looks up the roles for a given user.  It takes a 
364 L<Catalyst::Authentication::Store::LDAP::User> object
365 as it's first argument, and can optionally take a I<Net::LDAP> object which
366 is used rather than the default binding if supplied.
367
368 It returns an array containing the role_field attribute from all the
369 objects that match it's criteria.
370
371 =cut
372
373 sub lookup_roles {
374     my ( $self, $userobj, $ldap ) = @_;
375     if ( $self->use_roles == 0 || $self->use_roles =~ /^false$/i ) {
376         return undef;
377     }
378     $ldap ||= $self->ldap_bind;
379     my @searchopts;
380     if ( defined( $self->role_basedn ) ) {
381         push( @searchopts, 'base' => $self->role_basedn );
382     }
383     else {
384         Catalyst::Exception->throw(
385             "You must set up role_basedn before looking up roles!");
386     }
387     my $filter_value = $userobj->has_attribute( $self->role_value );
388     if ( !defined($filter_value) ) {
389         Catalyst::Exception->throw( "User object "
390                 . $userobj->username
391                 . " has no "
392                 . $self->role_value
393                 . " attribute, so I can't look up it's roles!" );
394     }
395     my $filter = $self->_replace_filter( $self->role_filter, $filter_value );
396     push( @searchopts, 'filter' => $filter );
397     push( @searchopts, 'scope'  => $self->role_scope );
398     push( @searchopts, 'attrs'  => [ $self->role_field ] );
399     if ( defined( $self->role_search_options ) ) {
400         push( @searchopts, %{ $self->role_search_options } );
401     }
402     my $rolesearch = $ldap->search(@searchopts);
403     my @roles;
404 RESULT: foreach my $entry ( $rolesearch->entries ) {
405         push( @roles, $entry->get_value( $self->role_field ) );
406     }
407     return @roles;
408 }
409
410 sub _replace_filter {
411     my $self    = shift;
412     my $filter  = shift;
413     my $replace = shift;
414     $filter =~ s/\%s/$replace/g;
415     return $filter;
416 }
417
418 =head2 user_supports
419
420 Returns the value of 
421 Catalyst::Authentication::Store::LDAP::User->supports(@_).
422
423 =cut
424
425 sub user_supports {
426     my $self = shift;
427
428     # this can work as a class method
429     Catalyst::Authentication::Store::LDAP::User->supports(@_);
430 }
431
432 =head2 from_session( I<id> )
433
434 Returns get_user() for I<id>.
435
436 =cut
437
438 sub from_session {
439     my ( $self, $c, $id ) = @_;
440     $self->get_user($id);
441 }
442
443 1;
444
445 __END__
446
447 =head1 AUTHORS
448
449 Adam Jacob <holoway@cpan.org>
450
451 Some parts stolen shamelessly and entirely from
452 L<Catalyst::Plugin::Authentication::Store::Htpasswd>.
453
454 Currently maintained by Peter Karman <karman@cpan.org>.
455
456 =head1 THANKS
457
458 To nothingmuch, ghenry, castaway and the rest of #catalyst for the help. :)
459
460 =head1 SEE ALSO
461
462 L<Catalyst::Authentication::Store::LDAP>, L<Catalyst::Authentication::Store::LDAP::User>, L<Catalyst::Plugin::Authentication>, L<Net::LDAP>
463
464 =head1 COPYRIGHT & LICENSE
465
466 Copyright (c) 2005 the aforementioned authors. All rights
467 reserved. This program is free software; you can redistribute
468 it and/or modify it under the same terms as Perl itself.
469
470 =cut
471