I think this actually works
[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))',
34 'user_scope' => 'one',
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;
b48d15e5 74use Scalar::Util qw/refaddr/;
f66d606b 75
2d7fcdde 76our $VERSION = '1.011';
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';
405489b5 124 $config_hash{'user_class'} ||= 'Catalyst::Authentication::Store::LDAP::User';
125 $config_hash{'role_search_as_user'} ||= 0;
f66d606b 126
405489b5 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 ) = @_;
405489b5 161 my $user = $self->user_class->new( $self,
52a972a4 162 $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 {
212 my ( $self, $ldap, $binddn, $bindpw, $forauth ) = @_;
213 $forauth ||= 0;
214 $ldap ||= $self->ldap_connect;
215 if ( !defined($ldap) ) {
216 Catalyst::Exception->throw("LDAP Server undefined!");
217 }
218 $binddn ||= $self->binddn;
219 $bindpw ||= $self->bindpw;
220 if ( $binddn eq "anonymous" ) {
405489b5 221 $self->_ldap_bind_anon($ldap);
f66d606b 222 }
223 else {
224 if ($bindpw) {
225 my $mesg = $ldap->bind( $binddn, 'password' => $bindpw );
226 if ( $mesg->is_error ) {
227
228 # If we're not checking this bind for authentication purposes
229 # Go ahead an blow up if we fail.
230 if ( $forauth ne 'forauth' ) {
231 Catalyst::Exception->throw(
232 "Error on Initial Bind: " . $mesg->error );
233 }
234 else {
235 return undef;
236 }
237 }
238 }
239 else {
405489b5 240 $self->_ldap_bind_anon($ldap, $binddn);
f66d606b 241 }
242 }
243 return $ldap;
244}
245
405489b5 246sub _ldap_bind_anon {
247 my ($self, $ldap, $dn) = @_;
248 my $mesg = $ldap->bind($dn);
249 if ( $mesg->is_error ) {
250 Catalyst::Exception->throw( "Error on Bind: " . $mesg->error );
251 }
252}
253
f66d606b 254=head2 lookup_user($id)
255
256Given a User ID, this method will:
257
258 A) Bind to the directory using the configured binddn and bindpw
259 B) Perform a search for the User Object in the directory, using
260 user_basedn, user_filter, and user_scope.
d94851da 261 C) Assuming we found the object, we will walk it's attributes
f66d606b 262 using L<Net::LDAP::Entry>'s get_value method. We store the
d94851da 263 results in a hashref. If we do not find the object, then
264 undef is returned.
265 D) Return a hashref that looks like:
266
f66d606b 267 $results = {
268 'ldap_entry' => $entry, # The Net::LDAP::Entry object
269 'attributes' => $attributes,
270 }
271
1647b33a 272This method is usually only called by find_user().
f66d606b 273
274=cut
275
276sub lookup_user {
277 my ( $self, $id ) = @_;
278
279 # No sneaking in wildcards!
280 if ( $id =~ /\*/ ) {
281 Catalyst::Exception->throw("ID $id contains wildcards!");
282 }
02f3c071 283 # Trim trailing space or we confuse ourselves
284 $id =~ s/\s+$//;
f66d606b 285 my $ldap = $self->ldap_bind;
286 my @searchopts;
287 if ( defined( $self->user_basedn ) ) {
288 push( @searchopts, 'base' => $self->user_basedn );
289 }
290 else {
291 Catalyst::Exception->throw(
292 "You must set user_basedn before looking up users!");
293 }
294 my $filter = $self->_replace_filter( $self->user_filter, $id );
295 push( @searchopts, 'filter' => $filter );
296 push( @searchopts, 'scope' => $self->user_scope );
297 if ( defined( $self->user_search_options ) ) {
298 push( @searchopts, %{ $self->user_search_options } );
299 }
300 my $usersearch = $ldap->search(@searchopts);
d94851da 301
a2f66fa8 302 return undef if ( $usersearch->is_error );
d94851da 303
f66d606b 304 my $userentry;
1647b33a 305 my $user_field = $self->user_field;
306 my $results_filter = $self->user_results_filter;
307 my $entry;
308 if ( defined($results_filter) ) {
309 $entry = &$results_filter($usersearch);
310 }
311 else {
312 $entry = $usersearch->pop_entry;
313 }
314 if ( $usersearch->pop_entry ) {
315 Catalyst::Exception->throw(
316 "More than one entry matches user search.\n"
317 . "Consider defining a user_results_filter sub." );
318 }
319
320 # a little extra sanity check with the 'eq' since LDAP already
321 # says it matches.
5772b468 322 # NOTE that Net::LDAP returns exactly what you asked for, but
323 # because LDAP is often case insensitive, FoO can match foo
324 # and so we normalize with lc().
1647b33a 325 if ( defined($entry) ) {
5772b468 326 unless ( lc( $entry->get_value($user_field) ) eq lc($id) ) {
1647b33a 327 Catalyst::Exception->throw(
328 "LDAP claims '$user_field' equals '$id' but results entry does not match."
329 );
f66d606b 330 }
1647b33a 331 $userentry = $entry;
f66d606b 332 }
1647b33a 333
f66d606b 334 $ldap->unbind;
335 $ldap->disconnect;
336 unless ($userentry) {
337 return undef;
338 }
339 my $attrhash;
340 foreach my $attr ( $userentry->attributes ) {
341 my @attrvalues = $userentry->get_value($attr);
342 if ( scalar(@attrvalues) == 1 ) {
343 $attrhash->{ lc($attr) } = $attrvalues[0];
344 }
345 else {
346 $attrhash->{ lc($attr) } = \@attrvalues;
347 }
348 }
405489b5 349
350 eval { Catalyst::Utils::ensure_class_loaded($self->entry_class) };
f66d606b 351 if ( !$@ ) {
352 bless( $userentry, $self->entry_class );
353 $userentry->{_use_unicode}++;
354 }
355 my $rv = {
356 'ldap_entry' => $userentry,
357 'attributes' => $attrhash,
358 };
359 return $rv;
360}
361
405489b5 362=head2 lookup_roles($userobj, [$ldap])
f66d606b 363
364This method looks up the roles for a given user. It takes a
365L<Catalyst::Authentication::Store::LDAP::User> object
405489b5 366as it's first argument, and can optionally take a I<Net::LDAP> object which
367is used rather than the default binding if supplied.
f66d606b 368
369It returns an array containing the role_field attribute from all the
370objects that match it's criteria.
371
372=cut
373
374sub lookup_roles {
405489b5 375 my ( $self, $userobj, $ldap ) = @_;
f66d606b 376 if ( $self->use_roles == 0 || $self->use_roles =~ /^false$/i ) {
377 return undef;
378 }
405489b5 379 $ldap ||= $self->ldap_bind;
f66d606b 380 my @searchopts;
381 if ( defined( $self->role_basedn ) ) {
382 push( @searchopts, 'base' => $self->role_basedn );
383 }
384 else {
385 Catalyst::Exception->throw(
386 "You must set up role_basedn before looking up roles!");
387 }
388 my $filter_value = $userobj->has_attribute( $self->role_value );
389 if ( !defined($filter_value) ) {
390 Catalyst::Exception->throw( "User object "
391 . $userobj->username
392 . " has no "
393 . $self->role_value
394 . " attribute, so I can't look up it's roles!" );
395 }
396 my $filter = $self->_replace_filter( $self->role_filter, $filter_value );
397 push( @searchopts, 'filter' => $filter );
398 push( @searchopts, 'scope' => $self->role_scope );
399 push( @searchopts, 'attrs' => [ $self->role_field ] );
400 if ( defined( $self->role_search_options ) ) {
401 push( @searchopts, %{ $self->role_search_options } );
402 }
403 my $rolesearch = $ldap->search(@searchopts);
404 my @roles;
ab62b426 405RESULT: foreach my $entry ( $rolesearch->entries ) {
406 push( @roles, $entry->get_value( $self->role_field ) );
f66d606b 407 }
408 return @roles;
409}
410
411sub _replace_filter {
412 my $self = shift;
413 my $filter = shift;
414 my $replace = shift;
415 $filter =~ s/\%s/$replace/g;
416 return $filter;
417}
418
419=head2 user_supports
420
421Returns the value of
422Catalyst::Authentication::Store::LDAP::User->supports(@_).
423
424=cut
425
426sub user_supports {
427 my $self = shift;
428
429 # this can work as a class method
430 Catalyst::Authentication::Store::LDAP::User->supports(@_);
431}
432
5faab354 433=head2 from_session( I<id>, I<$c> )
f66d606b 434
435Returns get_user() for I<id>.
436
437=cut
438
439sub from_session {
440 my ( $self, $c, $id ) = @_;
fe96afce 441 my $pass;
b48d15e5 442 ($id, $pass) = split /,/, $id;
fe96afce 443 my $user = $self->get_user($id, $c);
444 if ($pass) {
445 $Catalyst::Authentication::Store::LDAP::User::_ldap_connection_passwords{refaddr($user)} = $pass;
b48d15e5 446 warn("SET PASS FOR RESTORED USER TO $pass");
fe96afce 447 }
448 return $user;
f66d606b 449}
450
4511;
452
453__END__
454
455=head1 AUTHORS
456
457Adam Jacob <holoway@cpan.org>
458
459Some parts stolen shamelessly and entirely from
460L<Catalyst::Plugin::Authentication::Store::Htpasswd>.
461
462Currently maintained by Peter Karman <karman@cpan.org>.
463
464=head1 THANKS
465
466To nothingmuch, ghenry, castaway and the rest of #catalyst for the help. :)
467
468=head1 SEE ALSO
469
470L<Catalyst::Authentication::Store::LDAP>, L<Catalyst::Authentication::Store::LDAP::User>, L<Catalyst::Plugin::Authentication>, L<Net::LDAP>
471
472=head1 COPYRIGHT & LICENSE
473
474Copyright (c) 2005 the aforementioned authors. All rights
475reserved. This program is free software; you can redistribute
476it and/or modify it under the same terms as Perl itself.
477
478=cut
479