Class::Inspector is no longer used
[catagits/Catalyst-Plugin-Authentication.git] / lib / Catalyst / Plugin / Authentication.pm
CommitLineData
06675d2e 1package Catalyst::Plugin::Authentication;
2
8d5a01fc 3use Moose;
4use namespace::clean -except => 'meta';
47cede3d 5use MRO::Compat;
96777f3a 6use Tie::RefHash;
5c5af345 7use Catalyst::Authentication::Realm;
96777f3a 8
8d5a01fc 9with 'MooseX::Emulate::Class::Accessor::Fast';
10
11__PACKAGE__->mk_accessors(qw/_user/);
12
d613a372 13our $VERSION = "0.10023";
b8b7f68e 14
06675d2e 15sub set_authenticated {
54c8dc06 16 my ( $c, $user, $realmname ) = @_;
06675d2e 17
18 $c->user($user);
e300c5b6 19 $c->request->{user} = $user; # compatibility kludge
06675d2e 20
54c8dc06 21 if (!$realmname) {
22 $realmname = 'default';
06675d2e 23 }
646ea5b1 24 my $realm = $c->get_auth_realm($realmname);
c7b6526a 25
646ea5b1 26 if (!$realm) {
27 Catalyst::Exception->throw(
28 "set_authenticated called with nonexistant realm: '$realmname'.");
29 }
646ea5b1 30 $user->auth_realm($realm->name);
8a7bd676 31
c7b6526a 32 $c->persist_user();
33
47cede3d 34 $c->maybe::next::method($user, $realmname);
06675d2e 35}
36
7bb06c91 37sub user {
e300c5b6 38 my $c = shift;
7bb06c91 39
e300c5b6 40 if (@_) {
41 return $c->_user(@_);
42 }
7bb06c91 43
45c7644b 44 if ( defined($c->_user) ) {
45 return $c->_user;
56e23e7a 46 } else {
47c6643f 47 return $c->auth_restore_user;
e300c5b6 48 }
7bb06c91 49}
50
54c8dc06 51# change this to allow specification of a realm - to verify the user is part of that realm
8a7bd676 52# in addition to verifying that they exist.
ce0b058d 53sub user_exists {
99747fe1 54 my $c = shift;
55 return defined($c->_user) || defined($c->find_realm_for_persisted_user);
56e23e7a 56}
57
c7b6526a 58# works like user_exists - except only returns true if user
45c7644b 59# exists AND is in the realm requested.
60sub user_in_realm {
61 my ($c, $realmname) = @_;
62
63 if (defined($c->_user)) {
64 return ($c->_user->auth_realm eq $realmname);
45c7644b 65 } else {
bf4d93a4 66 my $realm = $c->find_realm_for_persisted_user;
8a7bd676 67 if ($realm) {
68 return ($realm->name eq $realmname);
69 } else {
70 return undef;
71 }
45c7644b 72 }
73}
54c8dc06 74
646ea5b1 75sub __old_save_user_in_session {
e8919861 76 my ( $c, $user, $realmname ) = @_;
12dae309 77
54c8dc06 78 $c->session->{__user_realm} = $realmname;
c7b6526a 79
45c7644b 80 # we want to ask the store for a user prepared for the session.
54c8dc06 81 # but older modules split this functionality between the user and the
45c7644b 82 # store. We try the store first. If not, we use the old method.
54c8dc06 83 my $realm = $c->get_auth_realm($realmname);
84 if ($realm->{'store'}->can('for_session')) {
85 $c->session->{__user} = $realm->{'store'}->for_session($c, $user);
86 } else {
87 $c->session->{__user} = $user->for_session;
88 }
12dae309 89}
90
8a7bd676 91sub persist_user {
92 my $c = shift;
93
94 if ($c->user_exists) {
c7b6526a 95
96 ## if we have a valid session handler - we store the
97 ## realm in the session. If not - we have to hope that
5812e0a3 98 ## the realm can recognize its frozen user somehow.
c7b6526a 99 if ($c->can('session') &&
100 $c->config->{'Plugin::Authentication'}{'use_session'} &&
8a7bd676 101 $c->session_is_valid) {
c7b6526a 102
103 $c->session->{'__user_realm'} = $c->_user->auth_realm;
8a7bd676 104 }
c7b6526a 105
8a7bd676 106 my $realm = $c->get_auth_realm($c->_user->auth_realm);
c7b6526a 107
8a7bd676 108 # used to call $realm->save_user_in_session
109 $realm->persist_user($c, $c->user);
110 }
111}
112
113
c7b6526a 114## this was a short lived method to update user information -
8a7bd676 115## you should use persist_user instead.
116sub update_user_in_session {
117 my $c = shift;
118
119 return $c->persist_user;
120}
121
06675d2e 122sub logout {
123 my $c = shift;
124
125 $c->user(undef);
b003080b 126
bf4d93a4 127 my $realm = $c->find_realm_for_persisted_user;
8a7bd676 128 if ($realm) {
129 $realm->remove_persisted_user($c);
b003080b 130 }
c7b6526a 131
47cede3d 132 $c->maybe::next::method(@_);
06675d2e 133}
134
54c8dc06 135sub find_user {
136 my ( $c, $userinfo, $realmname ) = @_;
c7b6526a 137
54c8dc06 138 $realmname ||= 'default';
139 my $realm = $c->get_auth_realm($realmname);
c7b6526a 140
646ea5b1 141 if (!$realm) {
142 Catalyst::Exception->throw(
143 "find_user called with nonexistant realm: '$realmname'.");
7d0922d8 144 }
646ea5b1 145 return $realm->find_user($userinfo, $c);
7d0922d8 146}
147
c7b6526a 148## Consider making this a public method. - would make certain things easier when
bf4d93a4 149## dealing with things pre-auth restore.
150sub find_realm_for_persisted_user {
47c6643f 151 my $c = shift;
c7b6526a 152
8a7bd676 153 my $realm;
622e71d9 154 if ($c->can('session')
7c4d44af 155 and $c->config->{'Plugin::Authentication'}{'use_session'}
c7b6526a 156 and $c->session_is_valid
8a7bd676 157 and exists($c->session->{'__user_realm'})) {
c7b6526a 158
8a7bd676 159 $realm = $c->auth_realms->{$c->session->{'__user_realm'}};
160 if ($realm->user_is_restorable($c)) {
c7b6526a 161 return $realm;
8a7bd676 162 }
163 } else {
164 ## we have no choice but to ask each realm whether it has a persisted user.
165 foreach my $realmname (@{$c->_auth_realm_restore_order}) {
9172af6d 166 my $realm = $c->auth_realms->{$realmname}
167 || Catalyst::Exception->throw("Could not find authentication realm '$realmname'");
168 return $realm
169 if $realm->user_is_restorable($c);
8a7bd676 170 }
171 }
172 return undef;
488433fd 173}
47c6643f 174
7bb06c91 175sub auth_restore_user {
54c8dc06 176 my ( $c, $frozen_user, $realmname ) = @_;
7bb06c91 177
8a7bd676 178 my $realm;
179 if (defined($realmname)) {
c7b6526a 180 $realm = $c->get_auth_realm($realmname);
8a7bd676 181 } else {
bf4d93a4 182 $realm = $c->find_realm_for_persisted_user;
8a7bd676 183 }
bf4d93a4 184 return undef unless $realm; # FIXME die unless? This is an internal inconsistency
c7b6526a 185
8a7bd676 186 $c->_user( my $user = $realm->restore_user( $c, $frozen_user ) );
c7b6526a 187
54c8dc06 188 # this sets the realm the user originated in.
9c469e37 189 $user->auth_realm($realm->name) if $user;
c7b6526a 190
e300c5b6 191 return $user;
7bb06c91 192
193}
194
c7b6526a 195# we can't actually do our setup in setup because the model has not yet been loaded.
54c8dc06 196# So we have to trigger off of setup_finished. :-(
06675d2e 197sub setup {
c5fbff80 198 my $app = shift;
06675d2e 199
c5fbff80 200 $app->_authentication_initialize();
47cede3d 201 $app->next::method(@_);
54c8dc06 202}
203
204## the actual initialization routine. whee.
205sub _authentication_initialize {
c5fbff80 206 my $app = shift;
54c8dc06 207
d6209239 208 ## let's avoid recreating / configuring everything if we have already done it, eh?
209 if ($app->can('_auth_realms')) { return };
c5fbff80 210
c7b6526a 211 ## make classdata where it is used.
d6209239 212 $app->mk_classdata( '_auth_realms' => {});
c7b6526a 213
214 ## the order to attempt restore in - If we don't have session - we have
215 ## no way to be sure where a frozen user came from - so we have to
216 ## ask each realm if it can restore the user. Unfortunately it is possible
217 ## that multiple realms could restore the user from the data we have -
218 ## So we have to determine at setup time what order to ask the realms in.
8a7bd676 219 ## The default is to use the user_restore_priority values defined in the realm
c7b6526a 220 ## config. if they are not defined - we go by alphabetical order. Note that
8a7bd676 221 ## the 'default' realm always gets first chance at it unless it is explicitly
222 ## placed elsewhere by user_restore_priority. Remember this only comes
c7b6526a 223 ## into play if session is disabled.
224
8a7bd676 225 $app->mk_classdata( '_auth_realm_restore_order' => []);
bf4d93a4 226
7c4d44af 227 my $cfg = $app->config->{'Plugin::Authentication'};
99747fe1 228 my $realmshash;
7c4d44af 229 if (!defined($cfg)) {
230 if (exists($app->config->{'authentication'})) {
231 $cfg = $app->config->{'authentication'};
232 $app->config->{'Plugin::Authentication'} = $app->config->{'authentication'};
233 } else {
234 $cfg = {};
235 }
bf4d93a4 236 } else {
99747fe1 237 # the realmshash contains the various configured realms. By default this is
238 # the main $app->config->{'Plugin::Authentication'} hash - but if that is
239 # not defined, or there is a subkey {'realms'} then we use that.
240 $realmshash = $cfg;
241 }
c7b6526a 242
99747fe1 243 ## If we have a sub-key of {'realms'} then we use that for realm configuration
244 if (exists($cfg->{'realms'})) {
245 $realmshash = $cfg->{'realms'};
246 }
06675d2e 247
7c4d44af 248 # old default was to force use_session on. This must remain for that
5812e0a3 249 # reason - but if use_session is already in the config, we respect its setting.
7c4d44af 250 if (!exists($cfg->{'use_session'})) {
251 $cfg->{'use_session'} = 1;
252 }
c7b6526a 253
254 ## if we have a realms hash
bf4d93a4 255 if (ref($realmshash) eq 'HASH') {
c7b6526a 256
8a7bd676 257 my %auth_restore_order;
258 my $authcount = 2;
259 my $defaultrealm = 'default';
c7b6526a 260
bf4d93a4 261 foreach my $realm (sort keys %{$realmshash}) {
262 if (ref($realmshash->{$realm}) eq 'HASH' &&
99747fe1 263 (exists($realmshash->{$realm}{credential}) || exists($realmshash->{$realm}{class}))) {
c7b6526a 264
99747fe1 265 $app->setup_auth_realm($realm, $realmshash->{$realm});
c7b6526a 266
99747fe1 267 if (exists($realmshash->{$realm}{'user_restore_priority'})) {
268 $auth_restore_order{$realm} = $realmshash->{$realm}{'user_restore_priority'};
269 } else {
270 $auth_restore_order{$realm} = $authcount++;
271 }
272 }
54c8dc06 273 }
c7b6526a 274
275 # if we have a 'default_realm' in the config hash and we don't already
54c8dc06 276 # have a realm called 'default', we point default at the realm specified
c5fbff80 277 if (exists($cfg->{'default_realm'}) && !$app->get_auth_realm('default')) {
8a7bd676 278 if ($app->_set_default_auth_realm($cfg->{'default_realm'})) {
279 $defaultrealm = $cfg->{'default_realm'};
280 $auth_restore_order{'default'} = $auth_restore_order{$cfg->{'default_realm'}};
281 delete($auth_restore_order{$cfg->{'default_realm'}});
282 }
54c8dc06 283 }
c7b6526a 284
5812e0a3 285 ## if the default realm did not have a defined priority in its config - we put it at the front.
bf4d93a4 286 if (!exists($realmshash->{$defaultrealm}{'user_restore_priority'})) {
8a7bd676 287 $auth_restore_order{'default'} = 1;
288 }
c7b6526a 289
8a7bd676 290 @{$app->_auth_realm_restore_order} = sort { $auth_restore_order{$a} <=> $auth_restore_order{$b} } keys %auth_restore_order;
c7b6526a 291
54c8dc06 292 } else {
c7b6526a 293
58db3441 294 ## BACKWARDS COMPATIBILITY - if realms is not defined - then we are probably dealing
c5fbff80 295 ## with an old-school config. The only caveat here is that we must add a classname
c7b6526a 296
297 ## also - we have to treat {store} as {stores}{default} - because
298 ## while it is not a clear as a valid config in the docs, it
58db3441 299 ## is functional with the old api. Whee!
300 if (exists($cfg->{'store'}) && !exists($cfg->{'stores'}{'default'})) {
301 $cfg->{'stores'}{'default'} = $cfg->{'store'};
302 }
303
8a7bd676 304 push @{$app->_auth_realm_restore_order}, 'default';
54c8dc06 305 foreach my $storename (keys %{$cfg->{'stores'}}) {
306 my $realmcfg = {
58db3441 307 store => { class => $cfg->{'stores'}{$storename} },
54c8dc06 308 };
c5fbff80 309 $app->setup_auth_realm($storename, $realmcfg);
54c8dc06 310 }
c7b6526a 311 }
312
06675d2e 313}
314
54c8dc06 315# set up realmname.
316sub setup_auth_realm {
317 my ($app, $realmname, $config) = @_;
c7b6526a 318
e05c457e 319 my $realmclass = $config->{class};
320
321 if( !$realmclass ) {
5c5af345 322 $realmclass = 'Catalyst::Authentication::Realm';
e05c457e 323 } elsif ($realmclass !~ /^\+(.*)$/ ) {
5c5af345 324 $realmclass = "Catalyst::Authentication::Realm::${realmclass}";
e05c457e 325 } else {
326 $realmclass = $1;
54c8dc06 327 }
e05c457e 328
329 Catalyst::Utils::ensure_class_loaded( $realmclass );
330
646ea5b1 331 my $realm = $realmclass->new($realmname, $config, $app);
332 if ($realm) {
333 $app->auth_realms->{$realmname} = $realm;
58db3441 334 } else {
646ea5b1 335 $app->log->debug("realm initialization for '$realmname' failed.");
58db3441 336 }
646ea5b1 337 return $realm;
96777f3a 338}
339
54c8dc06 340sub auth_realms {
341 my $self = shift;
3fd45491 342 $self->_authentication_initialize(); # Ensure _auth_realms created!
54c8dc06 343 return($self->_auth_realms);
96777f3a 344}
345
54c8dc06 346sub get_auth_realm {
347 my ($app, $realmname) = @_;
348 return $app->auth_realms->{$realmname};
349}
96777f3a 350
e8919861 351
352# Very internal method. Vital Valuable Urgent, Do not touch on pain of death.
353# Using this method just assigns the default realm to be the value associated
354# with the realmname provided. It WILL overwrite any real realm called 'default'
c7b6526a 355# so can be very confusing if used improperly. It's used properly already.
e8919861 356# Translation: don't use it.
357sub _set_default_auth_realm {
54c8dc06 358 my ($app, $realmname) = @_;
c7b6526a 359
54c8dc06 360 if (exists($app->auth_realms->{$realmname})) {
361 $app->auth_realms->{'default'} = $app->auth_realms->{$realmname};
12dae309 362 }
54c8dc06 363 return $app->get_auth_realm('default');
96777f3a 364}
365
54c8dc06 366sub authenticate {
367 my ($app, $userinfo, $realmname) = @_;
c7b6526a 368
54c8dc06 369 if (!$realmname) {
370 $realmname = 'default';
371 }
c7b6526a 372
54c8dc06 373 my $realm = $app->get_auth_realm($realmname);
c7b6526a 374
45c7644b 375 ## note to self - make authenticate throw an exception if realm is invalid.
c7b6526a 376
646ea5b1 377 if ($realm) {
378 return $realm->authenticate($app, $userinfo);
54c8dc06 379 } else {
646ea5b1 380 Catalyst::Exception->throw(
381 "authenticate called with nonexistant realm: '$realmname'.");
382
54c8dc06 383 }
0cc778ab 384 return undef;
96777f3a 385}
386
54c8dc06 387## BACKWARDS COMPATIBILITY -- Warning: Here be monsters!
388#
389# What follows are backwards compatibility routines - for use with Stores and Credentials
c7b6526a 390# that have not been updated to work with C::P::Authentication v0.10.
54c8dc06 391# These are here so as to not break people's existing installations, but will go away
392# in a future version.
393#
394# The old style of configuration only supports a single store, as each store module
c7b6526a 395# sets itself as the default store upon being loaded. This is the only supported
396# 'compatibility' mode.
54c8dc06 397#
398
399sub get_user {
400 my ( $c, $uid, @rest ) = @_;
96777f3a 401
54c8dc06 402 return $c->find_user( {'id' => $uid, 'rest'=>\@rest }, 'default' );
96777f3a 403}
404
e8919861 405
54c8dc06 406## this should only be called when using old-style authentication plugins. IF this gets
407## called in a new-style config - it will OVERWRITE the store of your default realm. Don't do it.
408## also - this is a partial setup - because no credential is instantiated... in other words it ONLY
409## works with old-style auth plugins and C::P::Authentication in compatibility mode. Trying to combine
410## this with a realm-type config will probably crash your app.
96777f3a 411sub default_auth_store {
12dae309 412 my $self = shift;
96777f3a 413
646ea5b1 414 my $realm = $self->get_auth_realm('default');
415 if (!$realm) {
e05c457e 416 $realm = $self->setup_auth_realm('default', { class => 'Compatibility' });
646ea5b1 417 }
12dae309 418 if ( my $new = shift ) {
646ea5b1 419 $realm->store($new);
c7b6526a 420
58db3441 421 my $storeclass;
422 if (ref($new)) {
423 $storeclass = ref($new);
424 } else {
425 $storeclass = $new;
426 }
c7b6526a 427
428 # BACKWARDS COMPATIBILITY - if the store class does not define find_user, we define it in terms
429 # of get_user and add it to the class. this is because the auth routines use find_user,
54c8dc06 430 # and rely on it being present. (this avoids per-call checks)
431 if (!$storeclass->can('find_user')) {
432 no strict 'refs';
433 *{"${storeclass}::find_user"} = sub {
434 my ($self, $info) = @_;
435 my @rest = @{$info->{rest}} if exists($info->{rest});
436 $self->get_user($info->{id}, @rest);
437 };
438 }
12dae309 439 }
96777f3a 440
646ea5b1 441 return $self->get_auth_realm('default')->store;
96777f3a 442}
443
54c8dc06 444## BACKWARDS COMPATIBILITY
445## this only ever returns a hash containing 'default' - as that is the only
446## supported mode of calling this.
447sub auth_store_names {
448 my $self = shift;
449
646ea5b1 450 my %hash = ( $self->get_auth_realm('default')->store => 'default' );
54c8dc06 451}
452
453sub get_auth_store {
454 my ( $self, $name ) = @_;
c7b6526a 455
54c8dc06 456 if ($name ne 'default') {
c7b6526a 457 Carp::croak "get_auth_store called on non-default realm '$name'. Only default supported in compatibility mode";
54c8dc06 458 } else {
459 $self->default_auth_store();
460 }
461}
462
463sub get_auth_store_name {
464 my ( $self, $store ) = @_;
465 return 'default';
466}
467
468# sub auth_stores is only used internally - here for completeness
469sub auth_stores {
470 my $self = shift;
471
646ea5b1 472 my %hash = ( 'default' => $self->get_auth_realm('default')->store);
54c8dc06 473}
474
8d5a01fc 475__PACKAGE__->meta->make_immutable;
06675d2e 476__PACKAGE__;
477
478__END__
479
480=pod
481
482=head1 NAME
483
798af89b 484Catalyst::Plugin::Authentication - Infrastructure plugin for the Catalyst authentication framework.
06675d2e 485
486=head1 SYNOPSIS
487
189b5b0c 488 use Catalyst qw/
489 Authentication
189b5b0c 490 /;
491
492 # later on ...
c7b6526a 493 $c->authenticate({ username => 'myusername',
c5fbff80 494 password => 'mypassword' });
54c8dc06 495 my $age = $c->user->get('age');
189b5b0c 496 $c->logout;
06675d2e 497
498=head1 DESCRIPTION
499
16ef3eb8 500The authentication plugin provides generic user support for Catalyst apps. It
501is the basis for both authentication (checking the user is who they claim to
502be), and authorization (allowing the user to do what the system authorises
503them to do).
504
505Using authentication is split into two parts. A Store is used to actually
506store the user information, and can store any amount of data related to the
507user. Credentials are used to verify users, using information from the store,
508given data from the frontend. A Credential and a Store are paired to form a
e8919861 509'Realm'. A Catalyst application using the authentication framework must have
510at least one realm, and may have several.
189b5b0c 511
c7b6526a 512To implement authentication in a Catalyst application you need to add this
513module, and specify at least one realm in the configuration.
189b5b0c 514
c7b6526a 515Authentication data can also be stored in a session, if the application
e7522758 516is using the L<Catalyst::Plugin::Session> module.
06675d2e 517
30e90c6f 518B<NOTE> in version 0.10 of this module, the interface to this module changed.
519Please see L</COMPATIBILITY ROUTINES> for more information.
e8919861 520
4bb9b01c 521=head1 INTRODUCTION
522
523=head2 The Authentication/Authorization Process
524
525Web applications typically need to identify a user - to tell the user apart
526from other users. This is usually done in order to display private information
527that is only that user's business, or to limit access to the application so
528that only certain entities can access certain parts.
529
530This process is split up into several steps. First you ask the user to identify
531themselves. At this point you can't be sure that the user is really who they
532claim to be.
533
6a36933d 534Then the user tells you who they are, and backs this claim with some piece of
4bb9b01c 535information that only the real user could give you. For example, a password is
536a secret that is known to both the user and you. When the user tells you this
537password you can assume they're in on the secret and can be trusted (ignore
538identity theft for now). Checking the password, or any other proof is called
539B<credential verification>.
540
541By this time you know exactly who the user is - the user's identity is
16ef3eb8 542B<authenticated>. This is where this module's job stops, and your application
c7b6526a 543or other plugins step in.
16ef3eb8 544
545The next logical step is B<authorization>, the process of deciding what a user
546is (or isn't) allowed to do. For example, say your users are split into two
547main groups - regular users and administrators. You want to verify that the
4bb9b01c 548currently logged in user is indeed an administrator before performing the
c5fbff80 549actions in an administrative part of your application. These decisions may be
16ef3eb8 550made within your application code using just the information available after
c7b6526a 551authentication, or it may be facilitated by a number of plugins.
4bb9b01c 552
553=head2 The Components In This Framework
554
62f27384 555=head3 Realms
556
557Configuration of the Catalyst::Plugin::Authentication framework is done in
558terms of realms. In simplest terms, a realm is a pairing of a Credential
5afc0dde 559verifier and a User storage (Store) backend. As of version 0.10003, realms are
560now objects that you can create and customize.
62f27384 561
562An application can have any number of Realms, each of which operates
34088132 563independent of the others. Each realm has a name, which is used to identify it
62f27384 564as the target of an authentication request. This name can be anything, such as
565'users' or 'members'. One realm must be defined as the default_realm, which is
16ef3eb8 566used when no realm name is specified. More information about configuring
567realms is available in the configuration section.
62f27384 568
4bb9b01c 569=head3 Credential Verifiers
570
4e86cf54 571When user input is transferred to the L<Catalyst> application
572(typically via form inputs) the application may pass this information
e979170b 573into the authentication system through the C<< $c->authenticate() >>
4e86cf54 574method. From there, it is passed to the appropriate Credential
575verifier.
4bb9b01c 576
577These plugins check the data, and ensure that it really proves the user is who
578they claim to be.
579
4e86cf54 580Credential verifiers compatible with versions of this module 0.10x and
581upwards should be in the namespace
582C<Catalyst::Authentication::Credential>.
583
4bb9b01c 584=head3 Storage Backends
585
45c7644b 586The authentication data also identifies a user, and the Storage backend modules
62f27384 587use this data to locate and return a standardized object-oriented
588representation of a user.
4bb9b01c 589
590When a user is retrieved from a store it is not necessarily authenticated.
62f27384 591Credential verifiers accept a set of authentication data and use this
592information to retrieve the user from the store they are paired with.
4bb9b01c 593
34088132 594Storage backends compatible with versions of this module 0.10x and
4e86cf54 595upwards should be in the namespace
596C<Catalyst::Authentication::Store>.
597
4bb9b01c 598=head3 The Core Plugin
599
62f27384 600This plugin on its own is the glue, providing realm configuration, session
4bb9b01c 601integration, and other goodness for the other plugins.
602
603=head3 Other Plugins
604
605More layers of plugins can be stacked on top of the authentication code. For
606example, L<Catalyst::Plugin::Session::PerUser> provides an abstraction of
4e86cf54 607browser sessions that is more persistent per user.
4bb9b01c 608L<Catalyst::Plugin::Authorization::Roles> provides an accepted way to separate
609and group users into categories, and then check which categories the current
610user belongs to.
611
5e91c057 612=head1 EXAMPLE
613
34088132 614Let's say we were storing users in a simple Perl hash. Users are
16ef3eb8 615verified by supplying a password which is matched within the hash.
5e91c057 616
617This means that our application will begin like this:
618
619 package MyApp;
620
621 use Catalyst qw/
622 Authentication
5e91c057 623 /;
624
c7b6526a 625 __PACKAGE__->config( 'Plugin::Authentication' =>
626 {
bf4d93a4 627 default => {
628 credential => {
629 class => 'Password',
630 password_field => 'password',
631 password_type => 'clear'
632 },
633 store => {
634 class => 'Minimal',
99747fe1 635 users => {
636 bob => {
637 password => "s00p3r",
638 editor => 'yes',
639 roles => [qw/edit delete/],
640 },
641 william => {
642 password => "s3cr3t",
643 roles => [qw/comment/],
644 }
645 }
646 }
647 }
c83ea211 648 }
649 );
5e91c057 650
16ef3eb8 651This tells the authentication plugin what realms are available, which
652credential and store modules are used, and the configuration of each. With
653this code loaded, we can now attempt to authenticate users.
5e91c057 654
62f27384 655To show an example of this, let's create an authentication controller:
5e91c057 656
657 package MyApp::Controller::Auth;
658
659 sub login : Local {
660 my ( $self, $c ) = @_;
661
4e143b06 662 if ( my $user = $c->req->params->{user}
34088132 663 and my $password = $c->req->params->{password} )
5e91c057 664 {
c7b6526a 665 if ( $c->authenticate( { username => $user,
62f27384 666 password => $password } ) ) {
667 $c->res->body( "hello " . $c->user->get("name") );
5e91c057 668 } else {
669 # login incorrect
670 }
671 }
672 else {
673 # invalid form input
674 }
675 }
676
4e86cf54 677This code should be self-explanatory. If all the necessary fields are supplied,
c7b6526a 678call the C<authenticate> method on the context object. If it succeeds the
c5fbff80 679user is logged in.
5e91c057 680
4e86cf54 681The credential verifier will attempt to retrieve the user whose
682details match the authentication information provided to
e979170b 683C<< $c->authenticate() >>. Once it fetches the user the password is
4e86cf54 684checked and if it matches the user will be B<authenticated> and
e979170b 685C<< $c->user >> will contain the user object retrieved from the store.
5e91c057 686
62f27384 687In the above case, the default realm is checked, but we could just as easily
688check an alternate realm. If this were an admin login, for example, we could
e979170b 689authenticate on the admin realm by simply changing the C<< $c->authenticate() >>
62f27384 690call:
5e91c057 691
c7b6526a 692 if ( $c->authenticate( { username => $user,
4e86cf54 693 password => $password }, 'admin' ) ) {
62f27384 694 $c->res->body( "hello " . $c->user->get("name") );
695 } ...
5e91c057 696
5e91c057 697
c7b6526a 698Now suppose we want to restrict the ability to edit to a user with an
c5fbff80 699'editor' value of yes.
5e91c057 700
62f27384 701The restricted action might look like this:
5e91c057 702
62f27384 703 sub edit : Local {
5e91c057 704 my ( $self, $c ) = @_;
705
706 $c->detach("unauthorized")
707 unless $c->user_exists
c5fbff80 708 and $c->user->get('editor') eq 'yes';
5e91c057 709
710 # do something restricted here
711 }
712
4e86cf54 713(Note that if you have multiple realms, you can use
e979170b 714C<< $c->user_in_realm('realmname') >> in place of
715C<< $c->user_exists(); >> This will essentially perform the same
4e86cf54 716verification as user_exists, with the added requirement that if there
717is a user, it must have come from the realm specified.)
c5fbff80 718
c7b6526a 719The above example is somewhat similar to role based access control.
5c5af345 720L<Catalyst::Authentication::Store::Minimal> treats the roles field as
62f27384 721an array of role names. Let's leverage this. Add the role authorization
722plugin:
5e91c057 723
724 use Catalyst qw/
725 ...
726 Authorization::Roles
727 /;
728
62f27384 729 sub edit : Local {
5e91c057 730 my ( $self, $c ) = @_;
731
128321cc 732 $c->detach("unauthorized") unless $c->check_user_roles("edit");
5e91c057 733
734 # do something restricted here
735 }
736
737This is somewhat simpler and will work if you change your store, too, since the
738role interface is consistent.
739
34088132 740Let's say your app grows, and you now have 10,000 users. It's no longer
0cc778ab 741efficient to maintain a hash of users, so you move this data to a database.
4e86cf54 742You can accomplish this simply by installing the L<DBIx::Class|Catalyst::Authentication::Store::DBIx::Class> Store and
0cc778ab 743changing your config:
5e91c057 744
47074ecb 745 __PACKAGE__->config( 'Plugin::Authentication' =>
c7b6526a 746 {
0cc778ab 747 default_realm => 'members',
0cc778ab 748 members => {
749 credential => {
c5fbff80 750 class => 'Password',
751 password_field => 'password',
752 password_type => 'clear'
0cc778ab 753 },
754 store => {
755 class => 'DBIx::Class',
99747fe1 756 user_model => 'MyApp::Users',
757 role_column => 'roles',
758 }
759 }
c83ea211 760 }
761 );
bf4d93a4 762
763The authentication system works behind the scenes to load your data from the
764new source. The rest of your application is completely unchanged.
765
766
767=head1 CONFIGURATION
768
769 # example
c7b6526a 770 __PACKAGE__->config( 'Plugin::Authentication' =>
771 {
bf4d93a4 772 default_realm => 'members',
773
774 members => {
775 credential => {
776 class => 'Password',
777 password_field => 'password',
778 password_type => 'clear'
779 },
780 store => {
781 class => 'DBIx::Class',
99747fe1 782 user_model => 'MyApp::Users',
783 role_column => 'roles',
784 }
785 },
786 admins => {
787 credential => {
788 class => 'Password',
789 password_field => 'password',
bf4d93a4 790 password_type => 'clear'
99747fe1 791 },
792 store => {
793 class => '+MyApp::Authentication::Store::NetAuth',
794 authserver => '192.168.10.17'
795 }
796 }
c83ea211 797 }
798 );
0cc778ab 799
03a89311 800NOTE: Until version 0.10008 of this module, you would need to put all the
c7b6526a 801realms inside a "realms" key in the configuration. Please see
ff87fb62 802L</COMPATIBILITY CONFIGURATION> for more information
03a89311 803
078c2289 804=over 4
805
189b5b0c 806=item use_session
807
808Whether or not to store the user's logged in state in the session, if the
0c4fbc79 809application is also using L<Catalyst::Plugin::Session>. This
e7522758 810value is set to true per default.
811
0c4fbc79 812However, even if use_session is disabled, if any code touches $c->session, a session
813object will be auto-vivified and session Cookies will be sent in the headers. To
814prevent accidental session creation, check if a session already exists with
815if ($c->sessionid) { ... }. If the session doesn't exist, then don't place
816anything in the session to prevent an unecessary session from being created.
817
0cc778ab 818=item default_realm
fe4cf44a 819
0cc778ab 820This defines which realm should be used as when no realm is provided to methods
821that require a realm such as authenticate or find_user.
7d0922d8 822
bf4d93a4 823=item realm refs
7d0922d8 824
c7b6526a 825The Plugin::Authentication config hash contains the series of realm
826configurations you want to use for your app. The only rule here is
827that there must be at least one. A realm consists of a name, which is used
828to reference the realm, a credential and a store. You may also put your
829realm configurations within a subelement called 'realms' if you desire to
bf4d93a4 830separate them from the remainder of your configuration. Note that if you use
c7b6526a 831a 'realms' subelement, you must put ALL of your realms within it.
4fbe2e14 832
7c3d201d 833You can also specify a realm class to instantiate instead of the default
834L<Catalyst::Authentication::Realm> class using the 'class' element within the
835realm config.
5afc0dde 836
c7b6526a 837Each realm config contains two hashes, one called 'credential' and one called
0cc778ab 838'store', each of which provide configuration details to the respective modules.
c7b6526a 839The contents of these hashes is specific to the module being used, with the
0cc778ab 840exception of the 'class' element, which tells the core Authentication module the
c7b6526a 841classname to instantiate.
4fbe2e14 842
0cc778ab 843The 'class' element follows the standard Catalyst mechanism of class
844specification. If a class is prefixed with a +, it is assumed to be a complete
845class name. Otherwise it is considered to be a portion of the class name. For
e8919861 846credentials, the classname 'B<Password>', for example, is expanded to
5c5af345 847Catalyst::Authentication::Credential::B<Password>. For stores, the
e8919861 848classname 'B<storename>' is expanded to:
5c5af345 849Catalyst::Authentication::Store::B<storename>.
4fbe2e14 850
fe4cf44a 851=back
852
e8919861 853=head1 METHODS
854
34088132 855=head2 $c->authenticate( $userinfo [, $realm ])
e8919861 856
857Attempts to authenticate the user using the information in the $userinfo hash
858reference using the realm $realm. $realm may be omitted, in which case the
859default realm is checked.
860
4e86cf54 861=head2 $c->user( )
e8919861 862
34088132 863Returns the currently logged in user, or undef if there is none.
c51e5a95 864Normally the user is re-retrieved from the store.
8f57bf96 865For L<Catalyst::Authentication::Store::DBIx::Class> the user is re-restored
866using the primary key of the user table.
c51e5a95 867Thus B<user> can throw an error even though B<user_exists>
868returned true.
e8919861 869
4e86cf54 870=head2 $c->user_exists( )
e8919861 871
872Returns true if a user is logged in right now. The difference between
c51e5a95 873B<user_exists> and B<user> is that user_exists will return true if a user is logged
45c7644b 874in, even if it has not been yet retrieved from the storage backend. If you only
e8919861 875need to know if the user is logged in, depending on the storage mechanism this
876can be much more efficient.
c51e5a95 877B<user_exists> only looks into the session while B<user> is trying to restore the user.
e8919861 878
4e86cf54 879=head2 $c->user_in_realm( $realm )
45c7644b 880
c7b6526a 881Works like user_exists, except that it only returns true if a user is both
882logged in right now and was retrieved from the realm provided.
45c7644b 883
4e86cf54 884=head2 $c->logout( )
e8919861 885
18b5ff80 886Logs the user out. Deletes the currently logged in user from C<< $c->user >>
887and the session. It does not delete the session.
e8919861 888
4e86cf54 889=head2 $c->find_user( $userinfo, $realm )
e8919861 890
c7b6526a 891Fetch a particular users details, matching the provided user info, from the realm
e8919861 892specified in $realm.
893
4b4bfe2f 894 $user = $c->find_user({ id => $id });
895 $c->set_authenticated($user); # logs the user in and calls persist_user
896
8a7bd676 897=head2 persist_user()
898
899Under normal circumstances the user data is only saved to the session during
c7b6526a 900initial authentication. This call causes the auth system to save the
34088132 901currently authenticated user's data across requests. Useful if you have
8a7bd676 902changed the user data and want to ensure that future requests reflect the
c7b6526a 903most current data. Assumes that at the time of this call, $c->user
8a7bd676 904contains the most current data.
905
95114c34 906=head2 find_realm_for_persisted_user()
907
908Private method, do not call from user code!
909
06675d2e 910=head1 INTERNAL METHODS
911
e8919861 912These methods are for Catalyst::Plugin::Authentication B<INTERNAL USE> only.
913Please do not use them in your own code, whether application or credential /
914store modules. If you do, you will very likely get the nasty shock of having
915to fix / rewrite your code when things change. They are documented here only
916for reference.
06675d2e 917
4e86cf54 918=head2 $c->set_authenticated( $user, $realmname )
06675d2e 919
e8919861 920Marks a user as authenticated. This is called from within the authenticate
4b4bfe2f 921routine when a credential returns a user. $realmname defaults to 'default'.
922You can use find_user to get $user
06675d2e 923
4e86cf54 924=head2 $c->auth_restore_user( $user, $realmname )
e300c5b6 925
e8919861 926Used to restore a user from the session. In most cases this is called without
927arguments to restore the user via the session. Can be called with arguments
928when restoring a user from some other method. Currently not used in this way.
e300c5b6 929
4e86cf54 930=head2 $c->auth_realms( )
06675d2e 931
e8919861 932Returns a hashref containing realmname -> realm instance pairs. Realm
933instances contain an instantiated store and credential object as the 'store'
934and 'credential' elements, respectively
06675d2e 935
4e86cf54 936=head2 $c->get_auth_realm( $realmname )
06675d2e 937
e8919861 938Retrieves the realm instance for the realmname provided.
06675d2e 939
96671824 940=head2 $c->update_user_in_session
941
34088132 942This was a short-lived method to update user information - you should use persist_user instead.
96671824 943
eda12589 944=head2 $c->setup_auth_realm( )
945
946=head1 OVERRIDDEN METHODS
947
948=head2 $c->setup( )
949
fbe577ac 950=head1 SEE ALSO
951
649de93b 952This list might not be up to date. Below are modules known to work with the updated
c7b6526a 953API of 0.10 and are therefore compatible with realms.
4bb9b01c 954
5afc0dde 955=head2 Realms
956
5c5af345 957L<Catalyst::Authentication::Realm>
5afc0dde 958
4bb9b01c 959=head2 User Storage Backends
960
eda12589 961=over
962
963=item L<Catalyst::Authentication::Store::Minimal>
964
965=item L<Catalyst::Authentication::Store::DBIx::Class>
966
967=item L<Catalyst::Authentication::Store::LDAP>
968
969=item L<Catalyst::Authentication::Store::RDBO>
970
971=item L<Catalyst::Authentication::Store::Model::KiokuDB>
972
973=item L<Catalyst::Authentication::Store::Jifty::DBI>
974
975=item L<Catalyst::Authentication::Store::Htpasswd>
976
977=back
4bb9b01c 978
979=head2 Credential verification
980
eda12589 981=over
982
983=item L<Catalyst::Authentication::Credential::Password>
984
985=item L<Catalyst::Authentication::Credential::HTTP>
986
987=item L<Catalyst::Authentication::Credential::OpenID>
988
989=item L<Catalyst::Authentication::Credential::Authen::Simple>
990
991=item L<Catalyst::Authentication::Credential::Flickr>
992
993=item L<Catalyst::Authentication::Credential::Testing>
994
995=item L<Catalyst::Authentication::Credential::AuthTkt>
996
997=item L<Catalyst::Authentication::Credential::Kerberos>
4bb9b01c 998
fdf33503 999=back
1000
4bb9b01c 1001=head2 Authorization
1002
fbe577ac 1003L<Catalyst::Plugin::Authorization::ACL>,
4bb9b01c 1004L<Catalyst::Plugin::Authorization::Roles>
1005
5e91c057 1006=head2 Internals Documentation
1007
649de93b 1008L<Catalyst::Plugin::Authentication::Internals>
5e91c057 1009
4bb9b01c 1010=head2 Misc
1011
1012L<Catalyst::Plugin::Session>,
1013L<Catalyst::Plugin::Session::PerUser>
fbe577ac 1014
93f08fb0 1015=head1 DON'T SEE ALSO
1016
1a05e6ed 1017This module along with its sub plugins deprecate a great number of other
1018modules. These include L<Catalyst::Plugin::Authentication::Simple>,
1019L<Catalyst::Plugin::Authentication::CDBI>.
93f08fb0 1020
649de93b 1021=head1 INCOMPATABILITIES
1022
c7b6526a 1023The realms-based configuration and functionality of the 0.10 update
649de93b 1024of L<Catalyst::Plugin::Authentication> required a change in the API used by
1025credentials and stores. It has a compatibility mode which allows use of
1026modules that have not yet been updated. This, however, completely mimics the
c7b6526a 1027older api and disables the new realm-based features. In other words you cannot
34088132 1028mix the older credential and store modules with realms, or realm-based
649de93b 1029configs. The changes required to update modules are relatively minor and are
1030covered in L<Catalyst::Plugin::Authentication::Internals>. We hope that most
1031modules will move to the compatible list above very quickly.
0cc778ab 1032
ff87fb62 1033=head1 COMPATIBILITY CONFIGURATION
1034
1035Until version 0.10008 of this module, you needed to put all the
c7b6526a 1036realms inside a "realms" key in the configuration.
ff87fb62 1037
1038 # example
47074ecb 1039 __PACKAGE__->config( 'Plugin::Authentication' =>
c7b6526a 1040 {
ff87fb62 1041 default_realm => 'members',
1042 realms => {
1043 members => {
1044 ...
1045 },
1046 },
c83ea211 1047 }
1048 );
ff87fb62 1049
c83ea211 1050If you use the old, deprecated C<< __PACKAGE__->config( 'authentication' ) >>
ff87fb62 1051configuration key, then the realms key is still required.
1052
0cc778ab 1053=head1 COMPATIBILITY ROUTINES
1054
e8919861 1055In version 0.10 of L<Catalyst::Plugin::Authentication>, the API
1056changed. For app developers, this change is fairly minor, but for
c7b6526a 1057Credential and Store authors, the changes are significant.
e8919861 1058
1059Please see the documentation in version 0.09 of
30e90c6f 1060Catalyst::Plugin::Authentication for a better understanding of how the old API
e8919861 1061functioned.
1062
1063The items below are still present in the plugin, though using them is
1064deprecated. They remain only as a transition tool, for those sites which can
30e90c6f 1065not yet be upgraded to use the new system due to local customizations or use
c7b6526a 1066of Credential / Store modules that have not yet been updated to work with the
45c7644b 1067new API.
e8919861 1068
1069These routines should not be used in any application using realms
1070functionality or any of the methods described above. These are for reference
1071purposes only.
0cc778ab 1072
4e86cf54 1073=head2 $c->login( )
e8919861 1074
1075This method is used to initiate authentication and user retrieval. Technically
649de93b 1076this is part of the old Password credential module and it still resides in the
1077L<Password|Catalyst::Plugin::Authentication::Credential::Password> class. It is
1078included here for reference only.
e8919861 1079
4e86cf54 1080=head2 $c->default_auth_store( )
0cc778ab 1081
1082Return the store whose name is 'default'.
1083
c83ea211 1084This is set to C<< $c->config( 'Plugin::Authentication' => { store => # Store} ) >> if that value exists,
0cc778ab 1085or by using a Store plugin:
1086
30e90c6f 1087 # load the Minimal authentication store.
99747fe1 1088 use Catalyst qw/Authentication Authentication::Store::Minimal/;
0cc778ab 1089
1090Sets the default store to
45c7644b 1091L<Catalyst::Plugin::Authentication::Store::Minimal>.
0cc778ab 1092
4e86cf54 1093=head2 $c->get_auth_store( $name )
0cc778ab 1094
1095Return the store whose name is $name.
1096
4e86cf54 1097=head2 $c->get_auth_store_name( $store )
0cc778ab 1098
1099Return the name of the store $store.
1100
4e86cf54 1101=head2 $c->auth_stores( )
0cc778ab 1102
1103A hash keyed by name, with the stores registered in the app.
1104
4e86cf54 1105=head2 $c->register_auth_stores( %stores_by_name )
0cc778ab 1106
1107Register stores into the application.
1108
4e86cf54 1109=head2 $c->auth_store_names( )
078c2289 1110
4e86cf54 1111=head2 $c->get_user( )
078c2289 1112
efea013f 1113=head1 SUPPORT
1114
1115Please use the rt.cpan.org bug tracker, and git patches are wecome.
1116
1117Questions on usage should be directed to the Catalyst mailing list
1118or the #catalyst irc channel.
fbe577ac 1119
efea013f 1120=head1 AUTHORS
2bcde605 1121
efea013f 1122Yuval Kogman, C<nothingmuch@woobling.org> - original author
649de93b 1123
efea013f 1124Jay Kuri, C<jayk@cpan.org> - Large rewrite
2bcde605 1125
efea013f 1126=head1 PRIMARY MAINTAINER
06675d2e 1127
7289cea0 1128Tomas Doran (t0m), C<bobtfish@bobtfish.net>
1129
83418d1e 1130=head1 ADDITIONAL CONTRIBUTORS
efea013f 1131
1132=over
7289cea0 1133
efea013f 1134=item Jess Robinson
36540b6c 1135
efea013f 1136=item David Kamholz
44bb43eb 1137
83418d1e 1138=item kmx
44bb43eb 1139
efea013f 1140=item Nigel Metheringham
8a31d23d 1141
efea013f 1142=item Florian Ragwitz C<rafl@debian.org>
1143
1144=item Stephan Jauernick C<stephanj@cpan.org>
1145
1146=item Oskari Ojala (Okko), C<perl@okko.net>
1147
1148=item John Napiorkowski (jnap) C<jjnapiork@cpan.org>
1149
1150=back
2ded293d 1151
ff46c00b 1152=head1 COPYRIGHT & LICENSE
fbe577ac 1153
2ded293d 1154Copyright (c) 2005 - 2012
efea013f 1155the Catalyst::Plugin::Authentication L</AUTHORS>,
1156L</PRIMARY MAINTAINER> and L</ADDITIONAL CONTRIBUTORS>
87d186b1 1157as listed above.
1158
1159This program is free software; you can redistribute
1160it and/or modify it under the same terms as Perl itself.
fbe577ac 1161
1162=cut
06675d2e 1163