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