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