Use String::RewritePrefix, it's already a Cat dep
[catagits/Catalyst-Plugin-Authentication.git] / lib / Catalyst / Authentication / Realm.pm
1 package Catalyst::Authentication::Realm;
2
3 use strict;
4 use warnings;
5 use String::RewritePrefix;
6
7 use base qw/Class::Accessor::Fast/;
8
9 BEGIN {
10     __PACKAGE__->mk_accessors(qw/store credential name config/);
11 };
12
13 ## Add use_session config item to realm.
14
15 sub new {
16     my ($class, $realmname, $config, $app) = @_;
17
18     my $self = { config => $config };
19     bless $self, $class;
20
21     $self->name($realmname);
22
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'};
26         } else {
27             $self->config->{'use_session'} = 1;
28         }
29     }
30
31     $app->log->debug("Setting up auth realm $realmname") if $app->debug;
32
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.) );
39         }
40     }
41     my $storeclass = $config->{'store'}{'class'};
42
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::',
47         '+' => '',
48     }, $storeclass);
49
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';
53
54     my $credentialclass = $config->{'credential'}{'class'};
55
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::',
60         '+' => '',
61     }, $credentialclass);
62
63     # if we made it here - we have what we need to load the classes
64
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.
68
69     ## Note to self - catch second exception and bitch in detail?
70
71     eval {
72         Catalyst::Utils::ensure_class_loaded( $credentialclass );
73     };
74
75     if ($@) {
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/;
82
83         eval { Catalyst::Utils::ensure_class_loaded( $credentialclass ); };
84         if ($@) {
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;
90         }
91     }
92
93     eval {
94         Catalyst::Utils::ensure_class_loaded( $storeclass );
95     };
96
97     if ($@) {
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 ); };
105         if ($@) {
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;
111         }
112     }
113
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')) {
118         no strict 'refs';
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);
123                                             };
124     }
125
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));
130     } else {
131         $app->log->error("THIS IS DEPRECATED: $storeclass has no new() method - Attempting to use uninstantiated");
132         $self->store($storeclass);
133     }
134     if ($credentialclass->can('new')) {
135         $self->credential($credentialclass->new($config->{'credential'}, $app, $self));
136     } else {
137         $app->log->error("THIS IS DEPRECATED: $credentialclass has no new() method - Attempting to use uninstantiated");
138         $self->credential($credentialclass);
139     }
140
141     return $self;
142 }
143
144 sub find_user {
145     my ( $self, $authinfo, $c ) = @_;
146
147     my $res = $self->store->find_user($authinfo, $c);
148
149     if (!$res) {
150       if ($self->config->{'auto_create_user'} && $self->store->can('auto_create_user') ) {
151           $res = $self->store->auto_create_user($authinfo, $c);
152       }
153     } elsif ($self->config->{'auto_update_user'} && $self->store->can('auto_update_user')) {
154         $res = $self->store->auto_update_user($authinfo, $c, $res);
155     }
156
157     return $res;
158 }
159
160 sub authenticate {
161      my ($self, $c, $authinfo) = @_;
162
163      my $user = $self->credential->authenticate($c, $self, $authinfo);
164      if (ref($user)) {
165          $c->set_authenticated($user, $self->name);
166          return $user;
167      } else {
168          return undef;
169      }
170 }
171
172 sub user_is_restorable {
173     my ($self, $c) = @_;
174
175     return unless
176          $c->can('session')
177          and $self->config->{'use_session'}
178          and $c->session_is_valid;
179
180     return $c->session->{__user};
181 }
182
183 sub restore_user {
184     my ($self, $c, $frozen_user) = @_;
185
186     $frozen_user ||= $self->user_is_restorable($c);
187     return unless defined($frozen_user);
188
189     my $user = $self->from_session( $c, $frozen_user );
190
191     if ($user) {
192         $c->_user( $user );
193
194         # this sets the realm the user originated in.
195         $user->auth_realm($self->name);
196     }
197     else {
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?");
200     }
201
202     return $user;
203 }
204
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 {
209     my ($self, $c) = @_;
210
211     $self->remove_persisted_user($c);
212     return;
213 }
214
215 sub persist_user {
216     my ($self, $c, $user) = @_;
217
218     if (
219         $c->can('session')
220         and $self->config->{'use_session'}
221         and $user->supports("session")
222     ) {
223         $c->session->{__user_realm} = $self->name;
224
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);
230         } else {
231             $c->session->{__user} = $user->for_session;
232         }
233     }
234     return $user;
235 }
236
237 sub remove_persisted_user {
238     my ($self, $c) = @_;
239
240     if (
241         $c->can('session')
242         and $self->config->{'use_session'}
243         and $c->session_is_valid
244     ) {
245         delete @{ $c->session }{qw/__user __user_realm/};
246     }
247 }
248
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 ) = @_;
253
254     return $self->persist_user($c, $user);
255 }
256
257 sub from_session {
258     my ($self, $c, $frozen_user) = @_;
259
260     return $self->store->from_session($c, $frozen_user);
261 }
262
263
264 __PACKAGE__;
265
266 __END__
267
268 =pod
269
270 =head1 NAME
271
272 Catalyst::Authentication::Realm - Base class for realm objects.
273
274 =head1 DESCRIPTION
275
276 =head1 CONFIGURATION
277
278 =over 4
279
280 =item class
281
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.
287
288 =item auto_create_user
289
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).
292
293 =item auto_update_user
294
295 Set this to true if you wish this realm to auto-update user accounts after
296 authentication (most useful for remote authentication schemes).
297
298 =item use_session
299
300 Sets session usage for this particular realm - overriding the global use_sesion setting.
301
302
303 =back
304
305 =head1 METHODS
306
307 =head2 new( $realmname, $config, $app )
308
309 Instantiantes this realm, plus the specified store and credential classes.
310
311 =head2 store( )
312
313 Returns an instance of the store object for this realm.
314
315 =head2 credential( )
316
317 Returns an instance of the credential object for this realm.
318
319 =head2 find_user( $authinfo, $c )
320
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.
325
326 =head2 authenticate( $c, $authinfo)
327
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;
331
332 =head1 USER PERSISTENCE
333
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
338 any way you see fit.
339
340 =head2 persist_user($c, $user)
341
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
348 your updates.
349
350 =head2 remove_persisted_user($c)
351
352 Removes any persisted user data.  By default, removes the user from the session.
353
354 =head2 user_is_restorable( $c )
355
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.
359
360 =head2 restore_user($c, [$frozen_user])
361
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.
365
366 =head2 failed_user_restore($c)
367
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).
371
372 =head2 from_session($c, $frozenuser )
373
374 Decodes the frozenuser information provided and returns an instantiated
375 user object.  By default, this call is delegated to $store->from_session().
376
377 =head2 save_user_in_session($c, $user)
378
379 DEPRECATED.  Use persist_user instead.  (this simply calls persist_user)
380
381 =cut