b8977040f4b18588048c78a60b28c3ab499d594b
[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.1002';
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     if ( defined($entry) ) {
318         unless ( $entry->get_value($user_field) eq $id ) {
319             Catalyst::Exception->throw(
320                 "LDAP claims '$user_field' equals '$id' but results entry does not match."
321             );
322         }
323         $userentry = $entry;
324     }
325
326     $ldap->unbind;
327     $ldap->disconnect;
328     unless ($userentry) {
329         return undef;
330     }
331     my $attrhash;
332     foreach my $attr ( $userentry->attributes ) {
333         my @attrvalues = $userentry->get_value($attr);
334         if ( scalar(@attrvalues) == 1 ) {
335             $attrhash->{ lc($attr) } = $attrvalues[0];
336         }
337         else {
338             $attrhash->{ lc($attr) } = \@attrvalues;
339         }
340     }
341     my $load_class = $self->entry_class . ".pm";
342     $load_class =~ s|::|/|g;
343
344     eval { require $load_class };
345     if ( !$@ ) {
346         bless( $userentry, $self->entry_class );
347         $userentry->{_use_unicode}++;
348     }
349     my $rv = {
350         'ldap_entry' => $userentry,
351         'attributes' => $attrhash,
352     };
353     return $rv;
354 }
355
356 =head2 lookup_roles($userobj)
357
358 This method looks up the roles for a given user.  It takes a 
359 L<Catalyst::Authentication::Store::LDAP::User> object
360 as it's sole argument.
361
362 It returns an array containing the role_field attribute from all the
363 objects that match it's criteria.
364
365 =cut
366
367 sub lookup_roles {
368     my ( $self, $userobj ) = @_;
369     if ( $self->use_roles == 0 || $self->use_roles =~ /^false$/i ) {
370         return undef;
371     }
372     my $ldap = $self->ldap_bind;
373     my @searchopts;
374     if ( defined( $self->role_basedn ) ) {
375         push( @searchopts, 'base' => $self->role_basedn );
376     }
377     else {
378         Catalyst::Exception->throw(
379             "You must set up role_basedn before looking up roles!");
380     }
381     my $filter_value = $userobj->has_attribute( $self->role_value );
382     if ( !defined($filter_value) ) {
383         Catalyst::Exception->throw( "User object "
384                 . $userobj->username
385                 . " has no "
386                 . $self->role_value
387                 . " attribute, so I can't look up it's roles!" );
388     }
389     my $filter = $self->_replace_filter( $self->role_filter, $filter_value );
390     push( @searchopts, 'filter' => $filter );
391     push( @searchopts, 'scope'  => $self->role_scope );
392     push( @searchopts, 'attrs'  => [ $self->role_field ] );
393     if ( defined( $self->role_search_options ) ) {
394         push( @searchopts, %{ $self->role_search_options } );
395     }
396     my $rolesearch = $ldap->search(@searchopts);
397     my @roles;
398 RESULT: foreach my $entry ( $rolesearch->entries ) {
399         push( @roles, $entry->get_value( $self->role_field ) );
400     }
401     return @roles;
402 }
403
404 sub _replace_filter {
405     my $self    = shift;
406     my $filter  = shift;
407     my $replace = shift;
408     $filter =~ s/\%s/$replace/g;
409     return $filter;
410 }
411
412 =head2 user_supports
413
414 Returns the value of 
415 Catalyst::Authentication::Store::LDAP::User->supports(@_).
416
417 =cut
418
419 sub user_supports {
420     my $self = shift;
421
422     # this can work as a class method
423     Catalyst::Authentication::Store::LDAP::User->supports(@_);
424 }
425
426 =head2 from_session( I<id> )
427
428 Returns get_user() for I<id>.
429
430 =cut
431
432 sub from_session {
433     my ( $self, $c, $id ) = @_;
434     $self->get_user($id);
435 }
436
437 1;
438
439 __END__
440
441 =head1 AUTHORS
442
443 Adam Jacob <holoway@cpan.org>
444
445 Some parts stolen shamelessly and entirely from
446 L<Catalyst::Plugin::Authentication::Store::Htpasswd>.
447
448 Currently maintained by Peter Karman <karman@cpan.org>.
449
450 =head1 THANKS
451
452 To nothingmuch, ghenry, castaway and the rest of #catalyst for the help. :)
453
454 =head1 SEE ALSO
455
456 L<Catalyst::Authentication::Store::LDAP>, L<Catalyst::Authentication::Store::LDAP::User>, L<Catalyst::Plugin::Authentication>, L<Net::LDAP>
457
458 =head1 COPYRIGHT & LICENSE
459
460 Copyright (c) 2005 the aforementioned authors. All rights
461 reserved. This program is free software; you can redistribute
462 it and/or modify it under the same terms as Perl itself.
463
464 =cut
465