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