36df48b96855a105b1db6a57693b7229dd1ed596
[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     sub action : Local {
57         my ( $self, $c ) = @_;
58
59         $c->login( $users->get_user( $c->req->param("login") ),
60             $c->req->param("password") );
61     }
62
63 =head1 DESCRIPTION
64
65 You probably want L<Catalyst::Authentication::Store::LDAP>, unless
66 you are mixing several stores in a single app and one of them is LDAP.
67
68 Otherwise, this lets you create a store manually. 
69
70 See the L<Catalyst::Authentication::Store::LDAP> documentation for
71 an explanation of the configuration options.
72
73 =head1 METHODS
74
75 =cut
76
77 package Catalyst::Authentication::Store::LDAP::Backend;
78 use base qw( Class::Accessor::Fast );
79
80 use strict;
81 use warnings;
82
83 our $VERSION = '0.1004';
84
85 use Catalyst::Authentication::Store::LDAP::User;
86 use Net::LDAP;
87 use Catalyst::Utils ();
88
89 BEGIN {
90     __PACKAGE__->mk_accessors(
91         qw( ldap_server ldap_server_options binddn
92             bindpw entry_class user_search_options
93             user_filter user_basedn user_scope
94             user_attrs user_field use_roles role_basedn
95             role_filter role_scope role_field role_value
96             role_search_options start_tls start_tls_options
97             user_results_filter user_class role_search_as_user
98             )
99     );
100 }
101
102 =head2 new($config)
103
104 Creates a new L<Catalyst::Authentication::Store::LDAP::Backend> object.
105 $config should be a hashref, which should contain the configuration options
106 listed in L<Catalyst::Authentication::Store::LDAP>'s documentation.
107
108 Also sets a few sensible defaults.
109
110 =cut
111
112 sub new {
113     my ( $class, $config ) = @_;
114
115     unless ( defined($config) && ref($config) eq "HASH" ) {
116         Catalyst::Exception->throw(
117             "Catalyst::Authentication::Store::LDAP::Backend needs to be configured with a hashref."
118         );
119     }
120     my %config_hash = %{$config};
121     $config_hash{'binddn'}      ||= 'anonymous';
122     $config_hash{'user_filter'} ||= '(uid=%s)';
123     $config_hash{'user_scope'}  ||= 'sub';
124     $config_hash{'user_field'}  ||= 'uid';
125     $config_hash{'role_filter'} ||= '(memberUid=%s)';
126     $config_hash{'role_scope'}  ||= 'sub';
127     $config_hash{'role_field'}  ||= 'cn';
128     $config_hash{'use_roles'}   ||= '1';
129     $config_hash{'start_tls'}   ||= '0';
130     $config_hash{'entry_class'} ||= 'Catalyst::Model::LDAP::Entry';
131     $config_hash{'user_class'}  ||= 'Catalyst::Authentication::Store::LDAP::User';
132     $config_hash{'role_search_as_user'} ||= 0;
133
134     Catalyst::Utils::ensure_class_loaded($config_hash{'user_class'});
135     my $self = \%config_hash;
136     bless( $self, $class );
137     return $self;
138 }
139
140 =head2 find_user( I<authinfo> )
141
142 Creates a L<Catalyst::Authentication::Store::LDAP::User> object
143 for the given User ID.  This is the preferred mechanism for getting a 
144 given User out of the Store.
145
146 I<authinfo> should be a hashref with a key of either C<id> or
147 C<username>. The value will be compared against the LDAP C<user_field> field.
148
149 =cut
150
151 sub find_user {
152     my ( $self, $authinfo, $c ) = @_;
153     return $self->get_user( $authinfo->{id} || $authinfo->{username} );
154 }
155
156 =head2 get_user($id)
157
158 Creates a L<Catalyst::Authentication::Store::LDAP::User> object
159 for the given User ID.  This is the preferred mechanism for getting a 
160 given User out of the Store.
161
162 =cut
163
164 sub get_user {
165     my ( $self, $id ) = @_;
166     my $user = $self->user_class->new( $self,
167         $self->lookup_user($id) );
168     return $user;
169 }
170
171 =head2 ldap_connect
172
173 Returns a L<Net::LDAP> object, connected to your LDAP server. (According
174 to how you configured the Backend, of course)
175
176 =cut
177
178 sub ldap_connect {
179     my ($self) = shift;
180     my $ldap;
181     if ( defined( $self->ldap_server_options() ) ) {
182         $ldap
183             = Net::LDAP->new( $self->ldap_server,
184             %{ $self->ldap_server_options } )
185             or Catalyst::Exception->throw($@);
186     }
187     else {
188         $ldap = Net::LDAP->new( $self->ldap_server )
189             or Catalyst::Exception->throw($@);
190     }
191     if ( defined( $self->start_tls ) && $self->start_tls =~ /(1|true)/i ) {
192         my $mesg;
193         if ( defined( $self->start_tls_options ) ) {
194             $mesg = $ldap->start_tls( %{ $self->start_tls_options } );
195         }
196         else {
197             $mesg = $ldap->start_tls;
198         }
199         if ( $mesg->is_error ) {
200             Catalyst::Exception->throw( "TLS Error: " . $mesg->error );
201         }
202     }
203     return $ldap;
204 }
205
206 =head2 ldap_bind($ldap, $binddn, $bindpw)
207
208 Bind's to the directory.  If $ldap is undef, it will connect to the
209 LDAP server first.  $binddn should be the DN of the object you wish
210 to bind as, and $bindpw the password.
211
212 If $binddn is "anonymous", an anonymous bind will be performed.
213
214 =cut
215
216 sub ldap_bind {
217     my ( $self, $ldap, $binddn, $bindpw, $forauth ) = @_;
218     $forauth ||= 0;
219     $ldap    ||= $self->ldap_connect;
220     if ( !defined($ldap) ) {
221         Catalyst::Exception->throw("LDAP Server undefined!");
222     }
223     $binddn ||= $self->binddn;
224     $bindpw ||= $self->bindpw;
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.
269   D) Return a hashref that looks like: 
270      
271      $results = {
272         'ldap_entry' => $entry, # The Net::LDAP::Entry object
273         'attributes' => $attributes,
274      }
275
276 This method is usually only called by find_user().
277
278 =cut
279
280 sub lookup_user {
281     my ( $self, $id ) = @_;
282
283     # No sneaking in wildcards!
284     if ( $id =~ /\*/ ) {
285         Catalyst::Exception->throw("ID $id contains wildcards!");
286     }
287     my $ldap = $self->ldap_bind;
288     my @searchopts;
289     if ( defined( $self->user_basedn ) ) {
290         push( @searchopts, 'base' => $self->user_basedn );
291     }
292     else {
293         Catalyst::Exception->throw(
294             "You must set user_basedn before looking up users!");
295     }
296     my $filter = $self->_replace_filter( $self->user_filter, $id );
297     push( @searchopts, 'filter' => $filter );
298     push( @searchopts, 'scope'  => $self->user_scope );
299     if ( defined( $self->user_search_options ) ) {
300         push( @searchopts, %{ $self->user_search_options } );
301     }
302     my $usersearch = $ldap->search(@searchopts);
303     if ( $usersearch->is_error ) {
304         Catalyst::Exception->throw(
305             "LDAP Error while searching for user: " . $usersearch->error );
306     }
307     my $userentry;
308     my $user_field     = $self->user_field;
309     my $results_filter = $self->user_results_filter;
310     my $entry;
311     if ( defined($results_filter) ) {
312         $entry = &$results_filter($usersearch);
313     }
314     else {
315         $entry = $usersearch->pop_entry;
316     }
317     if ( $usersearch->pop_entry ) {
318         Catalyst::Exception->throw(
319                   "More than one entry matches user search.\n"
320                 . "Consider defining a user_results_filter sub." );
321     }
322
323     # a little extra sanity check with the 'eq' since LDAP already
324     # says it matches.
325     # NOTE that Net::LDAP returns exactly what you asked for, but
326     # because LDAP is often case insensitive, FoO can match foo
327     # and so we normalize with lc().
328     if ( defined($entry) ) {
329         unless ( lc( $entry->get_value($user_field) ) eq lc($id) ) {
330             Catalyst::Exception->throw(
331                 "LDAP claims '$user_field' equals '$id' but results entry does not match."
332             );
333         }
334         $userentry = $entry;
335     }
336
337     $ldap->unbind;
338     $ldap->disconnect;
339     unless ($userentry) {
340         return undef;
341     }
342     my $attrhash;
343     foreach my $attr ( $userentry->attributes ) {
344         my @attrvalues = $userentry->get_value($attr);
345         if ( scalar(@attrvalues) == 1 ) {
346             $attrhash->{ lc($attr) } = $attrvalues[0];
347         }
348         else {
349             $attrhash->{ lc($attr) } = \@attrvalues;
350         }
351     }
352     
353     eval { Catalyst::Utils::ensure_class_loaded($self->entry_class) };
354     if ( !$@ ) {
355         bless( $userentry, $self->entry_class );
356         $userentry->{_use_unicode}++;
357     }
358     my $rv = {
359         'ldap_entry' => $userentry,
360         'attributes' => $attrhash,
361     };
362     return $rv;
363 }
364
365 =head2 lookup_roles($userobj, [$ldap])
366
367 This method looks up the roles for a given user.  It takes a 
368 L<Catalyst::Authentication::Store::LDAP::User> object
369 as it's first argument, and can optionally take a I<Net::LDAP> object which
370 is used rather than the default binding if supplied.
371
372 It returns an array containing the role_field attribute from all the
373 objects that match it's criteria.
374
375 =cut
376
377 sub lookup_roles {
378     my ( $self, $userobj, $ldap ) = @_;
379     if ( $self->use_roles == 0 || $self->use_roles =~ /^false$/i ) {
380         return undef;
381     }
382     $ldap ||= $self->ldap_bind;
383     my @searchopts;
384     if ( defined( $self->role_basedn ) ) {
385         push( @searchopts, 'base' => $self->role_basedn );
386     }
387     else {
388         Catalyst::Exception->throw(
389             "You must set up role_basedn before looking up roles!");
390     }
391     my $filter_value = $userobj->has_attribute( $self->role_value );
392     if ( !defined($filter_value) ) {
393         Catalyst::Exception->throw( "User object "
394                 . $userobj->username
395                 . " has no "
396                 . $self->role_value
397                 . " attribute, so I can't look up it's roles!" );
398     }
399     my $filter = $self->_replace_filter( $self->role_filter, $filter_value );
400     push( @searchopts, 'filter' => $filter );
401     push( @searchopts, 'scope'  => $self->role_scope );
402     push( @searchopts, 'attrs'  => [ $self->role_field ] );
403     if ( defined( $self->role_search_options ) ) {
404         push( @searchopts, %{ $self->role_search_options } );
405     }
406     my $rolesearch = $ldap->search(@searchopts);
407     my @roles;
408 RESULT: foreach my $entry ( $rolesearch->entries ) {
409         push( @roles, $entry->get_value( $self->role_field ) );
410     }
411     return @roles;
412 }
413
414 sub _replace_filter {
415     my $self    = shift;
416     my $filter  = shift;
417     my $replace = shift;
418     $filter =~ s/\%s/$replace/g;
419     return $filter;
420 }
421
422 =head2 user_supports
423
424 Returns the value of 
425 Catalyst::Authentication::Store::LDAP::User->supports(@_).
426
427 =cut
428
429 sub user_supports {
430     my $self = shift;
431
432     # this can work as a class method
433     Catalyst::Authentication::Store::LDAP::User->supports(@_);
434 }
435
436 =head2 from_session( I<id> )
437
438 Returns get_user() for I<id>.
439
440 =cut
441
442 sub from_session {
443     my ( $self, $c, $id ) = @_;
444     $self->get_user($id);
445 }
446
447 1;
448
449 __END__
450
451 =head1 AUTHORS
452
453 Adam Jacob <holoway@cpan.org>
454
455 Some parts stolen shamelessly and entirely from
456 L<Catalyst::Plugin::Authentication::Store::Htpasswd>.
457
458 Currently maintained by Peter Karman <karman@cpan.org>.
459
460 =head1 THANKS
461
462 To nothingmuch, ghenry, castaway and the rest of #catalyst for the help. :)
463
464 =head1 SEE ALSO
465
466 L<Catalyst::Authentication::Store::LDAP>, L<Catalyst::Authentication::Store::LDAP::User>, L<Catalyst::Plugin::Authentication>, L<Net::LDAP>
467
468 =head1 COPYRIGHT & LICENSE
469
470 Copyright (c) 2005 the aforementioned authors. All rights
471 reserved. This program is free software; you can redistribute
472 it and/or modify it under the same terms as Perl itself.
473
474 =cut
475