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