File Coverage

blib/lib/Catalyst/Authentication/Realm.pm
Criterion Covered Total %
statement 55 112 49.1
branch 13 48 27.0
condition 5 29 17.2
subroutine 12 20 60.0
pod 10 10 100.0
total 95 219 43.3


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