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