Add obj() as shorthand method for get_object()
[catagits/Catalyst-Plugin-Authentication.git] / lib / Catalyst / Authentication / Realm.pm
1 package Catalyst::Authentication::Realm;
2
3 use strict;
4 use warnings;
5
6 use base qw/Class::Accessor::Fast/;
7
8 BEGIN {
9     __PACKAGE__->mk_accessors(qw/store credential name config/);
10 };
11
12 ## Add use_session config item to realm.
13
14 sub new {
15     my ($class, $realmname, $config, $app) = @_;
16
17     my $self = { config => $config };
18     bless $self, $class;
19     
20     $self->name($realmname);
21     
22     if (!exists($self->config->{'use_session'})) {
23         if (exists($app->config->{'Plugin::Authentication'}{'use_session'})) {
24             $self->config->{'use_session'} = $app->config->{'Plugin::Authentication'}{'use_session'};
25         } else {
26             $self->config->{'use_session'} = 1;
27         }
28     }
29
30     $app->log->debug("Setting up auth realm $realmname") if $app->debug;
31
32     # use the Null store as a default - Don't complain if the realm class is being overridden, 
33     # as the new realm may behave differently.
34     if( ! exists($config->{store}{class}) && ! exists($config->{class}) ) {
35         $config->{store}{class} = '+Catalyst::Authentication::Store::Null';
36         $app->log->debug( qq(No Store specified for realm "$realmname", using the Null store.) );
37     } 
38     my $storeclass = $config->{'store'}{'class'};
39     
40     ## follow catalyst class naming - a + prefix means a fully qualified class, otherwise it's
41     ## taken to mean C::P::A::Store::(specifiedclass)
42     if ($storeclass !~ /^\+(.*)$/ ) {
43         $storeclass = "Catalyst::Authentication::Store::${storeclass}";
44     } else {
45         $storeclass = $1;
46     }
47
48     # a little niceness - since most systems seem to use the password credential class, 
49     # if no credential class is specified we use password.
50     $config->{credential}{class} ||= '+Catalyst::Authentication::Credential::Password';
51
52     my $credentialclass = $config->{'credential'}{'class'};
53     
54     ## follow catalyst class naming - a + prefix means a fully qualified class, otherwise it's
55     ## taken to mean C::A::Credential::(specifiedclass)
56     if ($credentialclass !~ /^\+(.*)$/ ) {
57         $credentialclass = "Catalyst::Authentication::Credential::${credentialclass}";
58     } else {
59         $credentialclass = $1;
60     }
61     
62     # if we made it here - we have what we need to load the classes
63     
64     ### BACKWARDS COMPATIBILITY - DEPRECATION WARNING:  
65     ###  we must eval the ensure_class_loaded - because we might need to try the old-style
66     ###  ::Plugin:: module naming if the standard method fails. 
67     
68     ## Note to self - catch second exception and bitch in detail?
69     
70     eval {
71         Catalyst::Utils::ensure_class_loaded( $credentialclass );
72     };
73     
74     if ($@) {
75         # If the file is missing, then try the old-style fallback, 
76         # but re-throw anything else for the user to deal with.
77         die unless $@ =~ /^Can't locate/;
78         $app->log->warn( qq(Credential class "$credentialclass" not found, trying deprecated ::Plugin:: style naming. ) );
79         my $origcredentialclass = $credentialclass;
80         $credentialclass =~ s/Catalyst::Authentication/Catalyst::Plugin::Authentication/;
81
82         eval { Catalyst::Utils::ensure_class_loaded( $credentialclass ); };
83         if ($@) {
84             # Likewise this croak is useful if the second exception is also "not found",
85             # but would be confusing if it's anything else.
86             die unless $@ =~ /^Can't locate/;
87             Carp::croak "Unable to load credential class, " . $origcredentialclass . " OR " . $credentialclass . 
88                         " in realm " . $self->name;
89         }
90     }
91     
92     eval {
93         Catalyst::Utils::ensure_class_loaded( $storeclass );
94     };
95     
96     if ($@) {
97         # If the file is missing, then try the old-style fallback, 
98         # but re-throw anything else for the user to deal with.
99         die unless $@ =~ /^Can't locate/;
100         $app->log->warn( qq(Store class "$storeclass" not found, trying deprecated ::Plugin:: style naming. ) );
101         my $origstoreclass = $storeclass;
102         $storeclass =~ s/Catalyst::Authentication/Catalyst::Plugin::Authentication/;
103         eval { Catalyst::Utils::ensure_class_loaded( $storeclass ); };
104         if ($@) {
105             # Likewise this croak is useful if the second exception is also "not found",
106             # but would be confusing if it's anything else.
107             die unless $@ =~ /^Can't locate/;
108             Carp::croak "Unable to load store class, " . $origstoreclass . " OR " . $storeclass . 
109                         " in realm " . $self->name;
110         }
111     }
112     
113     # BACKWARDS COMPATIBILITY - if the store class does not define find_user, we define it in terms 
114     # of get_user and add it to the class.  this is because the auth routines use find_user, 
115     # and rely on it being present. (this avoids per-call checks)
116     if (!$storeclass->can('find_user')) {
117         no strict 'refs';
118         *{"${storeclass}::find_user"} = sub {
119                                                 my ($self, $info) = @_;
120                                                 my @rest = @{$info->{rest}} if exists($info->{rest});
121                                                 $self->get_user($info->{id}, @rest);
122                                             };
123     }
124     
125     ## a little cruft to stay compatible with some poorly written stores / credentials
126     ## we'll remove this soon.
127     if ($storeclass->can('new')) {
128         $self->store($storeclass->new($config->{'store'}, $app, $self));
129     } else {
130         $app->log->error("THIS IS DEPRECATED: $storeclass has no new() method - Attempting to use uninstantiated");
131         $self->store($storeclass);
132     }
133     if ($credentialclass->can('new')) {
134         $self->credential($credentialclass->new($config->{'credential'}, $app, $self));
135     } else {
136         $app->log->error("THIS IS DEPRECATED: $credentialclass has no new() method - Attempting to use uninstantiated");
137         $self->credential($credentialclass);
138     }
139     
140     return $self;
141 }
142
143 sub find_user {
144     my ( $self, $authinfo, $c ) = @_;
145
146     my $res = $self->store->find_user($authinfo, $c);
147     
148     if (!$res) {
149       if ($self->config->{'auto_create_user'} && $self->store->can('auto_create_user') ) {
150           $res = $self->store->auto_create_user($authinfo, $c);
151       }
152     } elsif ($self->config->{'auto_update_user'} && $self->store->can('auto_update_user')) {
153         $res = $self->store->auto_update_user($authinfo, $c, $res);
154     } 
155     
156     return $res;
157 }
158
159 sub authenticate {
160      my ($self, $c, $authinfo) = @_;
161
162      my $user = $self->credential->authenticate($c, $self, $authinfo);
163      if (ref($user)) {
164          $c->set_authenticated($user, $self->name);
165          return $user;
166      } else {
167          return undef;
168      }
169 }
170
171 sub user_is_restorable {
172     my ($self, $c) = @_;
173     
174     return unless
175          $c->can('session')
176          and $self->config->{'use_session'}
177          and $c->session_is_valid;
178
179     return $c->session->{__user};
180 }
181
182 sub restore_user {
183     my ($self, $c, $frozen_user) = @_;
184     
185     $frozen_user ||= $self->user_is_restorable($c);
186     return unless defined($frozen_user);
187
188     my $user = $self->from_session( $c, $frozen_user );
189     
190     if ($user) {
191         $c->_user( $user );
192     
193         # this sets the realm the user originated in.
194         $user->auth_realm($self->name);
195     } 
196     else {
197         $self->failed_user_restore($c) ||
198             $c->error("Store claimed to have a restorable user, but restoration failed.  Did you change the user's id_field?");
199         }
200          
201     return $user;
202 }
203
204 ## this occurs if there is a session but the thing the session refers to
205 ## can not be found.  Do what you must do here.
206 ## Return true if you can fix the situation and find a user, false otherwise
207 sub failed_user_restore {
208         my ($self, $c) = @_;
209         
210         $self->remove_persisted_user($c);
211         return;
212 }
213
214 sub persist_user {
215     my ($self, $c, $user) = @_;
216     
217     if (
218         $c->can('session')
219         and $self->config->{'use_session'}
220         and $user->supports("session") 
221     ) {
222         $c->session->{__user_realm} = $self->name;
223     
224         # we want to ask the store for a user prepared for the session.
225         # but older modules split this functionality between the user and the
226         # store.  We try the store first.  If not, we use the old method.
227         if ($self->store->can('for_session')) {
228             $c->session->{__user} = $self->store->for_session($c, $user);
229         } else {
230             $c->session->{__user} = $user->for_session;
231         }
232     }
233     return $user;
234 }
235
236 sub remove_persisted_user {
237     my ($self, $c) = @_;
238     
239     if (
240         $c->can('session')
241         and $self->config->{'use_session'}
242         and $c->session_is_valid
243     ) {
244         delete @{ $c->session }{qw/__user __user_realm/};
245     }    
246 }
247
248 ## backwards compatibility - I don't think many people wrote realms since they
249 ## have only existed for a short time - but just in case.
250 sub save_user_in_session {
251     my ( $self, $c, $user ) = @_;
252
253     return $self->persist_user($c, $user);
254 }
255
256 sub from_session {
257     my ($self, $c, $frozen_user) = @_;
258     
259     return $self->store->from_session($c, $frozen_user);
260 }
261
262
263 __PACKAGE__;
264
265 __END__
266
267 =pod
268
269 =head1 NAME
270
271 Catalyst::Authentication::Realm - Base class for realm objects.
272
273 =head1 DESCRIPTION
274
275 =head1 CONFIGURATION
276
277 =over 4
278
279 =item class
280
281 By default this class is used by
282 L<Catalyst::Plugin::Authentication|Catalyst::Plugin::Authentication> for all
283 realms. The class parameter allows you to choose a different class to use for
284 this realm. Creating a new Realm class can allow for authentication methods
285 that fall outside the normal credential/store methodology.
286
287 =item auto_create_user
288
289 Set this to true if you wish this realm to auto-create user accounts when the
290 user doesn't exist (most useful for remote authentication schemes).
291
292 =item auto_update_user
293
294 Set this to true if you wish this realm to auto-update user accounts after
295 authentication (most useful for remote authentication schemes).
296
297 =item use_session
298
299 Sets session usage for this particular realm - overriding the global use_sesion setting.
300
301
302 =back
303
304 =head1 METHODS
305
306 =head2 new( $realmname, $config, $app )
307
308 Instantiantes this realm, plus the specified store and credential classes.
309
310 =head2 store( )
311
312 Returns an instance of the store object for this realm.
313
314 =head2 credential( )
315
316 Returns an instance of the credential object for this realm.
317
318 =head2 find_user( $authinfo, $c )
319
320 Retrieves the user given the authentication information provided.  This 
321 is most often called from the credential.  The default realm class simply
322 delegates this call the store object.  If enabled, auto-creation and 
323 auto-updating of users is also handled here.
324
325 =head2 authenticate( $c, $authinfo)
326
327 Performs the authentication process for the current realm.  The default 
328 realm class simply delegates this to the credential and sets 
329 the authenticated user on success.  Returns the authenticated user object;
330
331 =head1 USER PERSISTENCE
332
333 The Realm class allows complete control over the persistance of users
334 between requests.  By default the realm attempts to use the Catalyst
335 session system to accomplish this.  By overriding the methods below
336 in a custom Realm class, however, you can handle user persistance in
337 any way you see fit.  
338
339 =head2 persist_user($c, $user)
340
341 persist_user is the entry point for saving user information between requests
342 in most cases this will utilize the session.  By default this uses the 
343 catalyst session system to store the user by calling for_session on the
344 active store.  The user object must be a subclass of 
345 Catalyst::Authentication::User.  If you have updated the user object, you 
346 must call persist_user again to ensure that the persisted user object reflects
347 your updates.
348
349 =head2 remove_persisted_user($c)
350
351 Removes any persisted user data.  By default, removes the user from the session.
352
353 =head2 user_is_restorable( $c )
354
355 Returns whether there is a persisted user that may be restored.  Returns
356 a token used to restore the user.  With the default session persistance
357 it returns the raw frozen user information.
358
359 =head2 restore_user($c, [$frozen_user])
360
361 Restores the user from the given frozen_user parameter, or if not provided,
362 using the response from $self->user_is_restorable();  Uses $self->from_session()
363 to decode the frozen user.
364
365 =head2 failed_user_restore($c)
366
367 If there is a session to restore, but the restore fails for any reason then this method 
368 is called. This method supplied just removes the persisted user, but can be overridden
369 if required to have more complex logic (e.g. finding a the user by their 'old' username).
370
371 =head2 from_session($c, $frozenuser )
372
373 Decodes the frozenuser information provided and returns an instantiated 
374 user object.  By default, this call is delegated to $store->from_session().
375
376 =head2 save_user_in_session($c, $user)
377
378 DEPRECATED.  Use persist_user instead.  (this simply calls persist_user)
379
380 =cut