1 package Catalyst::Authentication::Realm;
5 use String::RewritePrefix;
7 use base qw/Class::Accessor::Fast/;
10 __PACKAGE__->mk_accessors(qw/store credential name config/);
13 ## Add use_session config item to realm.
16 my ($class, $realmname, $config, $app) = @_;
18 my $self = { config => $config };
21 $self->name($realmname);
23 if (!exists($self->config->{'use_session'})) {
24 if (exists($app->config->{'Plugin::Authentication'}{'use_session'})) {
25 $self->config->{'use_session'} = $app->config->{'Plugin::Authentication'}{'use_session'};
27 $self->config->{'use_session'} = 1;
31 $app->log->debug("Setting up auth realm $realmname") if $app->debug;
33 # use the Null store as a default - Don't complain if the realm class is being overridden,
34 # as the new realm may behave differently.
35 if( ! exists($config->{store}{class}) ) {
36 $config->{store}{class} = '+Catalyst::Authentication::Store::Null';
37 if (! exists($config->{class})) {
38 $app->log->debug( qq(No Store specified for realm "$realmname", using the Null store.) );
41 my $storeclass = $config->{'store'}{'class'};
43 ## follow catalyst class naming - a + prefix means a fully qualified class, otherwise it's
44 ## taken to mean C::P::A::Store::(specifiedclass)
45 $storeclass = String::RewritePrefix->rewrite({
46 '' => 'Catalyst::Authentication::Store::',
50 # a little niceness - since most systems seem to use the password credential class,
51 # if no credential class is specified we use password.
52 $config->{credential}{class} ||= '+Catalyst::Authentication::Credential::Password';
54 my $credentialclass = $config->{'credential'}{'class'};
56 ## follow catalyst class naming - a + prefix means a fully qualified class, otherwise it's
57 ## taken to mean C::A::Credential::(specifiedclass)
58 $credentialclass = String::RewritePrefix->rewrite({
59 '' => 'Catalyst::Authentication::Credential::',
63 # if we made it here - we have what we need to load the classes
65 ### BACKWARDS COMPATIBILITY - DEPRECATION WARNING:
66 ### we must eval the ensure_class_loaded - because we might need to try the old-style
67 ### ::Plugin:: module naming if the standard method fails.
69 ## Note to self - catch second exception and bitch in detail?
72 Catalyst::Utils::ensure_class_loaded( $credentialclass );
76 # If the file is missing, then try the old-style fallback,
77 # but re-throw anything else for the user to deal with.
78 die unless $@ =~ /^Can't locate/;
79 $app->log->warn( qq(Credential class "$credentialclass" not found, trying deprecated ::Plugin:: style naming. ) );
80 my $origcredentialclass = $credentialclass;
81 $credentialclass =~ s/Catalyst::Authentication/Catalyst::Plugin::Authentication/;
83 eval { Catalyst::Utils::ensure_class_loaded( $credentialclass ); };
85 # Likewise this croak is useful if the second exception is also "not found",
86 # but would be confusing if it's anything else.
87 die unless $@ =~ /^Can't locate/;
88 Carp::croak "Unable to load credential class, " . $origcredentialclass . " OR " . $credentialclass .
89 " in realm " . $self->name;
94 Catalyst::Utils::ensure_class_loaded( $storeclass );
98 # If the file is missing, then try the old-style fallback,
99 # but re-throw anything else for the user to deal with.
100 die unless $@ =~ /^Can't locate/;
101 $app->log->warn( qq(Store class "$storeclass" not found, trying deprecated ::Plugin:: style naming. ) );
102 my $origstoreclass = $storeclass;
103 $storeclass =~ s/Catalyst::Authentication/Catalyst::Plugin::Authentication/;
104 eval { Catalyst::Utils::ensure_class_loaded( $storeclass ); };
106 # Likewise this croak is useful if the second exception is also "not found",
107 # but would be confusing if it's anything else.
108 die unless $@ =~ /^Can't locate/;
109 Carp::croak "Unable to load store class, " . $origstoreclass . " OR " . $storeclass .
110 " in realm " . $self->name;
114 # BACKWARDS COMPATIBILITY - if the store class does not define find_user, we define it in terms
115 # of get_user and add it to the class. this is because the auth routines use find_user,
116 # and rely on it being present. (this avoids per-call checks)
117 if (!$storeclass->can('find_user')) {
119 *{"${storeclass}::find_user"} = sub {
120 my ($self, $info) = @_;
121 my @rest = @{$info->{rest}} if exists($info->{rest});
122 $self->get_user($info->{id}, @rest);
126 ## a little cruft to stay compatible with some poorly written stores / credentials
127 ## we'll remove this soon.
128 if ($storeclass->can('new')) {
129 $self->store($storeclass->new($config->{'store'}, $app, $self));
131 $app->log->error("THIS IS DEPRECATED: $storeclass has no new() method - Attempting to use uninstantiated");
132 $self->store($storeclass);
134 if ($credentialclass->can('new')) {
135 $self->credential($credentialclass->new($config->{'credential'}, $app, $self));
137 $app->log->error("THIS IS DEPRECATED: $credentialclass has no new() method - Attempting to use uninstantiated");
138 $self->credential($credentialclass);
145 my ( $self, $authinfo, $c ) = @_;
147 my $res = $self->store->find_user($authinfo, $c);
150 if ($self->config->{'auto_create_user'} && $self->store->can('auto_create_user') ) {
151 $res = $self->store->auto_create_user($authinfo, $c);
153 } elsif ($self->config->{'auto_update_user'} && $self->store->can('auto_update_user')) {
154 $res = $self->store->auto_update_user($authinfo, $c, $res);
161 my ($self, $c, $authinfo) = @_;
163 my $user = $self->credential->authenticate($c, $self, $authinfo);
165 $c->set_authenticated($user, $self->name);
172 sub user_is_restorable {
177 and $self->config->{'use_session'}
178 and $c->session_is_valid;
180 return $c->session->{__user};
184 my ($self, $c, $frozen_user) = @_;
186 $frozen_user ||= $self->user_is_restorable($c);
187 return unless defined($frozen_user);
189 my $user = $self->from_session( $c, $frozen_user );
194 # this sets the realm the user originated in.
195 $user->auth_realm($self->name);
198 $self->failed_user_restore($c) ||
199 $c->error("Store claimed to have a restorable user, but restoration failed. Did you change the user's id_field?");
205 ## this occurs if there is a session but the thing the session refers to
206 ## can not be found. Do what you must do here.
207 ## Return true if you can fix the situation and find a user, false otherwise
208 sub failed_user_restore {
211 $self->remove_persisted_user($c);
216 my ($self, $c, $user) = @_;
220 and $self->config->{'use_session'}
221 and $user->supports("session")
223 $c->session->{__user_realm} = $self->name;
225 # we want to ask the store for a user prepared for the session.
226 # but older modules split this functionality between the user and the
227 # store. We try the store first. If not, we use the old method.
228 if ($self->store->can('for_session')) {
229 $c->session->{__user} = $self->store->for_session($c, $user);
231 $c->session->{__user} = $user->for_session;
237 sub remove_persisted_user {
242 and $self->config->{'use_session'}
243 and $c->session_is_valid
245 delete @{ $c->session }{qw/__user __user_realm/};
249 ## backwards compatibility - I don't think many people wrote realms since they
250 ## have only existed for a short time - but just in case.
251 sub save_user_in_session {
252 my ( $self, $c, $user ) = @_;
254 return $self->persist_user($c, $user);
258 my ($self, $c, $frozen_user) = @_;
260 return $self->store->from_session($c, $frozen_user);
272 Catalyst::Authentication::Realm - Base class for realm objects.
282 By default this class is used by
283 L<Catalyst::Plugin::Authentication|Catalyst::Plugin::Authentication> for all
284 realms. The class parameter allows you to choose a different class to use for
285 this realm. Creating a new Realm class can allow for authentication methods
286 that fall outside the normal credential/store methodology.
288 =item auto_create_user
290 Set this to true if you wish this realm to auto-create user accounts when the
291 user doesn't exist (most useful for remote authentication schemes).
293 =item auto_update_user
295 Set this to true if you wish this realm to auto-update user accounts after
296 authentication (most useful for remote authentication schemes).
300 Sets session usage for this particular realm - overriding the global use_sesion setting.
307 =head2 new( $realmname, $config, $app )
309 Instantiantes this realm, plus the specified store and credential classes.
313 Returns an instance of the store object for this realm.
317 Returns an instance of the credential object for this realm.
319 =head2 find_user( $authinfo, $c )
321 Retrieves the user given the authentication information provided. This
322 is most often called from the credential. The default realm class simply
323 delegates this call the store object. If enabled, auto-creation and
324 auto-updating of users is also handled here.
326 =head2 authenticate( $c, $authinfo)
328 Performs the authentication process for the current realm. The default
329 realm class simply delegates this to the credential and sets
330 the authenticated user on success. Returns the authenticated user object;
332 =head1 USER PERSISTENCE
334 The Realm class allows complete control over the persistance of users
335 between requests. By default the realm attempts to use the Catalyst
336 session system to accomplish this. By overriding the methods below
337 in a custom Realm class, however, you can handle user persistance in
340 =head2 persist_user($c, $user)
342 persist_user is the entry point for saving user information between requests
343 in most cases this will utilize the session. By default this uses the
344 catalyst session system to store the user by calling for_session on the
345 active store. The user object must be a subclass of
346 Catalyst::Authentication::User. If you have updated the user object, you
347 must call persist_user again to ensure that the persisted user object reflects
350 =head2 remove_persisted_user($c)
352 Removes any persisted user data. By default, removes the user from the session.
354 =head2 user_is_restorable( $c )
356 Returns whether there is a persisted user that may be restored. Returns
357 a token used to restore the user. With the default session persistance
358 it returns the raw frozen user information.
360 =head2 restore_user($c, [$frozen_user])
362 Restores the user from the given frozen_user parameter, or if not provided,
363 using the response from $self->user_is_restorable(); Uses $self->from_session()
364 to decode the frozen user.
366 =head2 failed_user_restore($c)
368 If there is a session to restore, but the restore fails for any reason then this method
369 is called. This method supplied just removes the persisted user, but can be overridden
370 if required to have more complex logic (e.g. finding a the user by their 'old' username).
372 =head2 from_session($c, $frozenuser )
374 Decodes the frozenuser information provided and returns an instantiated
375 user object. By default, this call is delegated to $store->from_session().
377 =head2 save_user_in_session($c, $user)
379 DEPRECATED. Use persist_user instead. (this simply calls persist_user)