Document how to limit the attributes returned from the LDAP search
[catagits/Catalyst-Authentication-Store-LDAP.git] / lib / Catalyst / Authentication / Store / LDAP / Backend.pm
CommitLineData
f66d606b 1
2=pod
3
4=head1 NAME
5
6Catalyst::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))',
57d476f1 34 'user_scope' => 'one', # or 'sub' for Active Directory
f66d606b 35 'user_field' => 'uid',
36 'user_search_options' => {
37 'deref' => 'always',
a03db022 38 'attrs' => [qw( distinguishedname name mail )],
f66d606b 39 },
1647b33a 40 'user_results_filter' => sub { return shift->pop_entry },
f66d606b 41 'entry_class' => 'MyApp::LDAP::Entry',
405489b5 42 'user_class' => 'MyUser',
f66d606b 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 },
405489b5 52 'role_search_as_user' => 0,
f66d606b 53 );
54
55 our $users = Catalyst::Authentication::Store::LDAP::Backend->new(\%config);
56
f66d606b 57=head1 DESCRIPTION
58
afb8e81c 59You probably want L<Catalyst::Authentication::Store::LDAP>.
f66d606b 60
afb8e81c 61Otherwise, this lets you create a store manually.
f66d606b 62
63See the L<Catalyst::Authentication::Store::LDAP> documentation for
64an explanation of the configuration options.
65
66=head1 METHODS
67
68=cut
69
70package Catalyst::Authentication::Store::LDAP::Backend;
71use base qw( Class::Accessor::Fast );
72
73use strict;
74use warnings;
75
dfead577 76our $VERSION = '1.015';
f66d606b 77
78use Catalyst::Authentication::Store::LDAP::User;
79use Net::LDAP;
405489b5 80use Catalyst::Utils ();
f66d606b 81
82BEGIN {
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
405489b5 90 user_results_filter user_class role_search_as_user
f66d606b 91 )
92 );
93}
94
95=head2 new($config)
96
97Creates a new L<Catalyst::Authentication::Store::LDAP::Backend> object.
98$config should be a hashref, which should contain the configuration options
99listed in L<Catalyst::Authentication::Store::LDAP>'s documentation.
100
101Also sets a few sensible defaults.
102
103=cut
104
105sub 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';
d05c83dd 124 $config_hash{'user_class'}
125 ||= 'Catalyst::Authentication::Store::LDAP::User';
405489b5 126 $config_hash{'role_search_as_user'} ||= 0;
f66d606b 127
d05c83dd 128 Catalyst::Utils::ensure_class_loaded( $config_hash{'user_class'} );
f66d606b 129 my $self = \%config_hash;
130 bless( $self, $class );
131 return $self;
132}
133
52a972a4 134=head2 find_user( I<authinfo>, $c )
f66d606b 135
136Creates a L<Catalyst::Authentication::Store::LDAP::User> object
137for the given User ID. This is the preferred mechanism for getting a
138given User out of the Store.
139
140I<authinfo> should be a hashref with a key of either C<id> or
141C<username>. The value will be compared against the LDAP C<user_field> field.
142
143=cut
144
145sub find_user {
146 my ( $self, $authinfo, $c ) = @_;
52a972a4 147 return $self->get_user( $authinfo->{id} || $authinfo->{username}, $c );
f66d606b 148}
149
5faab354 150=head2 get_user( I<id>, $c)
f66d606b 151
152Creates a L<Catalyst::Authentication::Store::LDAP::User> object
52a972a4 153for the given User ID, or calls C<new> on the class specified in
154C<user_class>. This instance of the store object, the results of
155C<lookup_user> and $c are passed as arguments (in that order) to C<new>.
156This is the preferred mechanism for getting a given User out of the Store.
f66d606b 157
158=cut
159
160sub get_user {
52a972a4 161 my ( $self, $id, $c ) = @_;
d05c83dd 162 my $user = $self->user_class->new( $self, $self->lookup_user($id), $c );
f66d606b 163 return $user;
164}
165
166=head2 ldap_connect
167
168Returns a L<Net::LDAP> object, connected to your LDAP server. (According
169to how you configured the Backend, of course)
170
171=cut
172
173sub 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
203Bind's to the directory. If $ldap is undef, it will connect to the
204LDAP server first. $binddn should be the DN of the object you wish
205to bind as, and $bindpw the password.
206
207If $binddn is "anonymous", an anonymous bind will be performed.
208
209=cut
210
211sub ldap_bind {
238a096f 212 my ( $self, $ldap, $binddn, $bindpw ) = @_;
d05c83dd 213 $ldap ||= $self->ldap_connect;
f66d606b 214 if ( !defined($ldap) ) {
215 Catalyst::Exception->throw("LDAP Server undefined!");
216 }
50f88c5d 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
f66d606b 225 if ( $binddn eq "anonymous" ) {
405489b5 226 $self->_ldap_bind_anon($ldap);
f66d606b 227 }
228 else {
238a096f 229 if ($bindpw) {
f66d606b 230 my $mesg = $ldap->bind( $binddn, 'password' => $bindpw );
231 if ( $mesg->is_error ) {
238a096f 232 Catalyst::Exception->throw(
233 "Error on Initial Bind: " . $mesg->error );
f66d606b 234 }
235 }
236 else {
d05c83dd 237 $self->_ldap_bind_anon( $ldap, $binddn );
f66d606b 238 }
239 }
240 return $ldap;
241}
242
405489b5 243sub _ldap_bind_anon {
d05c83dd 244 my ( $self, $ldap, $dn ) = @_;
405489b5 245 my $mesg = $ldap->bind($dn);
246 if ( $mesg->is_error ) {
247 Catalyst::Exception->throw( "Error on Bind: " . $mesg->error );
248 }
249}
250
238a096f 251=head2 ldap_auth( $binddn, $bindpw )
252
253Connect to the LDAP server and do an authenticated bind against the
254directory. Throws an exception if connecting to the LDAP server fails.
255Returns 1 if binding succeeds, 0 if it fails.
256
257=cut
258
259sub 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
f66d606b 269=head2 lookup_user($id)
270
271Given 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.
d94851da 276 C) Assuming we found the object, we will walk it's attributes
f66d606b 277 using L<Net::LDAP::Entry>'s get_value method. We store the
d94851da 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
f66d606b 282 $results = {
283 'ldap_entry' => $entry, # The Net::LDAP::Entry object
284 'attributes' => $attributes,
285 }
286
1647b33a 287This method is usually only called by find_user().
f66d606b 288
289=cut
290
291sub lookup_user {
292 my ( $self, $id ) = @_;
293
02f3c071 294 # Trim trailing space or we confuse ourselves
295 $id =~ s/\s+$//;
f66d606b 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);
d94851da 312
a2f66fa8 313 return undef if ( $usersearch->is_error );
d94851da 314
f66d606b 315 my $userentry;
1647b33a 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.
5772b468 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().
1647b33a 336 if ( defined($entry) ) {
5772b468 337 unless ( lc( $entry->get_value($user_field) ) eq lc($id) ) {
1647b33a 338 Catalyst::Exception->throw(
339 "LDAP claims '$user_field' equals '$id' but results entry does not match."
340 );
f66d606b 341 }
1647b33a 342 $userentry = $entry;
f66d606b 343 }
1647b33a 344
f66d606b 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 }
d05c83dd 360
361 eval { Catalyst::Utils::ensure_class_loaded( $self->entry_class ) };
f66d606b 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
405489b5 373=head2 lookup_roles($userobj, [$ldap])
f66d606b 374
375This method looks up the roles for a given user. It takes a
376L<Catalyst::Authentication::Store::LDAP::User> object
405489b5 377as it's first argument, and can optionally take a I<Net::LDAP> object which
378is used rather than the default binding if supplied.
f66d606b 379
380It returns an array containing the role_field attribute from all the
381objects that match it's criteria.
382
383=cut
384
385sub lookup_roles {
405489b5 386 my ( $self, $userobj, $ldap ) = @_;
f66d606b 387 if ( $self->use_roles == 0 || $self->use_roles =~ /^false$/i ) {
388 return undef;
389 }
5a9aba6e 390 $ldap ||= $self->role_search_as_user
391 ? $userobj->ldap_connection : $self->ldap_bind;
f66d606b 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;
ab62b426 417RESULT: foreach my $entry ( $rolesearch->entries ) {
418 push( @roles, $entry->get_value( $self->role_field ) );
f66d606b 419 }
420 return @roles;
421}
422
423sub _replace_filter {
424 my $self = shift;
425 my $filter = shift;
426 my $replace = shift;
18d41a8f 427 $replace =~ s/([*()\\\x{0}])/sprintf '\\%02x', ord($1)/ge;
f66d606b 428 $filter =~ s/\%s/$replace/g;
429 return $filter;
430}
431
432=head2 user_supports
433
434Returns the value of
435Catalyst::Authentication::Store::LDAP::User->supports(@_).
436
437=cut
438
439sub user_supports {
440 my $self = shift;
441
442 # this can work as a class method
443 Catalyst::Authentication::Store::LDAP::User->supports(@_);
444}
445
5faab354 446=head2 from_session( I<id>, I<$c> )
f66d606b 447
448Returns get_user() for I<id>.
449
450=cut
451
452sub from_session {
453 my ( $self, $c, $id ) = @_;
d05c83dd 454 $self->get_user( $id, $c );
f66d606b 455}
456
4571;
458
459__END__
460
461=head1 AUTHORS
462
463Adam Jacob <holoway@cpan.org>
464
465Some parts stolen shamelessly and entirely from
466L<Catalyst::Plugin::Authentication::Store::Htpasswd>.
467
468Currently maintained by Peter Karman <karman@cpan.org>.
469
470=head1 THANKS
471
472To nothingmuch, ghenry, castaway and the rest of #catalyst for the help. :)
473
474=head1 SEE ALSO
475
476L<Catalyst::Authentication::Store::LDAP>, L<Catalyst::Authentication::Store::LDAP::User>, L<Catalyst::Plugin::Authentication>, L<Net::LDAP>
477
478=head1 COPYRIGHT & LICENSE
479
480Copyright (c) 2005 the aforementioned authors. All rights
481reserved. This program is free software; you can redistribute
482it and/or modify it under the same terms as Perl itself.
483
484=cut
485