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