POD update for auto_create change
[catagits/Catalyst-Authentication-Store-DBIx-Class.git] / lib / Catalyst / Authentication / Store / DBIx / Class / User.pm
1 package Catalyst::Authentication::Store::DBIx::Class::User;
2
3 use Moose;
4 use namespace::autoclean;
5 extends 'Catalyst::Authentication::User';
6
7 use List::MoreUtils 'all';
8 use Try::Tiny;
9
10 has 'config'    => (is => 'rw');
11 has 'resultset' => (is => 'rw');
12 has '_user'     => (is => 'rw');
13 has '_roles'    => (is => 'rw');
14
15 sub new {
16     my ( $class, $config, $c) = @_;
17
18         $config->{user_model} = $config->{user_class}
19         unless defined $config->{user_model};
20
21     my $self = {
22         resultset => $c->model($config->{'user_model'}),
23         config => $config,
24         _roles => undef,
25         _user => undef
26     };
27
28     bless $self, $class;
29
30     Catalyst::Exception->throw(
31         "\$c->model('${ \$self->config->{user_model} }') did not return a resultset."
32           . " Did you set user_model correctly?"
33     ) unless $self->{resultset};
34
35     $self->config->{'id_field'} = [$self->{'resultset'}->result_source->primary_columns]
36         unless exists $self->config->{'id_field'};
37
38     $self->config->{'id_field'} = [$self->config->{'id_field'}]
39         unless ref $self->config->{'id_field'} eq 'ARRAY';
40
41     Catalyst::Exception->throw(
42         "id_field set to "
43           . join(q{,} => @{ $self->config->{'id_field'} })
44           . " but user table has no column by that name!"
45     ) unless all { $self->{'resultset'}->result_source->has_column($_) } @{ $self->config->{'id_field'} };
46
47     ## if we have lazyloading turned on - we should not query the DB unless something gets read.
48     ## that's the idea anyway - still have to work out how to manage that - so for now we always force
49     ## lazyload to off.
50     $self->config->{lazyload} = 0;
51
52 #    if (!$self->config->{lazyload}) {
53 #        return $self->load_user($authinfo, $c);
54 #    } else {
55 #        ## what do we do with a lazyload?
56 #        ## presumably this is coming out of session storage.
57 #        ## use $authinfo to fill in the user in that case?
58 #    }
59
60     return $self;
61 }
62
63
64 sub load {
65     my ($self, $authinfo, $c) = @_;
66
67     my $dbix_class_config = 0;
68
69     if (exists($authinfo->{'dbix_class'})) {
70         $authinfo = $authinfo->{'dbix_class'};
71         $dbix_class_config = 1;
72     }
73
74     ## User can provide an arrayref containing the arguments to search on the user class.
75     ## or even provide a prepared resultset, allowing maximum flexibility for user retreival.
76     ## these options are only available when using the dbix_class authinfo hash.
77     if ($dbix_class_config && exists($authinfo->{'result'})) {
78         $self->_user($authinfo->{'result'});
79     } elsif ($dbix_class_config && exists($authinfo->{'resultset'})) {
80         $self->_user($authinfo->{'resultset'}->first);
81     } elsif ($dbix_class_config && exists($authinfo->{'searchargs'})) {
82         $self->_user($self->resultset->search(@{$authinfo->{'searchargs'}})->first);
83     } else {
84         ## merge the ignore fields array into a hash - so we can do an easy check while building the query
85         my %ignorefields = map { $_ => 1} @{$self->config->{'ignore_fields_in_find'}};
86         my $searchargs = {};
87
88         # now we walk all the fields passed in, and build up a search hash.
89         foreach my $key (grep {!$ignorefields{$_}} keys %{$authinfo}) {
90             if ($self->resultset->result_source->has_column($key)) {
91                 $searchargs->{$key} = $authinfo->{$key};
92             }
93         }
94         if (keys %{$searchargs}) {
95             $self->_user($self->resultset->search($searchargs)->first);
96         } else {
97             Catalyst::Exception->throw(
98                 "Failed to load user data.  You passed [" . join(',', keys %{$authinfo}) . "]"
99                   . " to authenticate() but your user source (" .  $self->config->{'user_model'} . ")"
100                   . " only has these columns: [" . join( ",", $self->resultset->result_source->columns ) . "]"
101                   . "   Check your authenticate() call."
102             );
103         }
104     }
105
106     if ($self->get_object) {
107         return $self;
108     } else {
109         return undef;
110     }
111
112 }
113
114 sub supported_features {
115     my $self = shift;
116
117     return {
118         session         => 1,
119         roles           => 1,
120     };
121 }
122
123
124 sub roles {
125     my ( $self ) = shift;
126     ## this used to load @wantedroles - but that doesn't seem to be used by the roles plugin, so I dropped it.
127
128     ## shortcut if we have already retrieved them
129     if (ref $self->_roles eq 'ARRAY') {
130         return(@{$self->_roles});
131     }
132
133     my @roles = ();
134     if (exists($self->config->{'role_column'})) {
135         my $role_data = $self->get($self->config->{'role_column'});
136         if ($role_data) {
137             @roles = split /[\s,\|]+/, $self->get($self->config->{'role_column'});
138         }
139         $self->_roles(\@roles);
140     } elsif (exists($self->config->{'role_relation'})) {
141         my $relation = $self->config->{'role_relation'};
142         if ($self->_user->$relation->result_source->has_column($self->config->{'role_field'})) {
143             @roles = map {
144                 $_->get_column($self->config->{role_field})
145             } $self->_user->$relation->search(undef, {
146                 columns => [ $self->config->{role_field} ]
147             })->all;
148             $self->_roles(\@roles);
149         } else {
150             Catalyst::Exception->throw("role table does not have a column called " . $self->config->{'role_field'});
151         }
152     } else {
153         Catalyst::Exception->throw("user->roles accessed, but no role configuration found");
154     }
155
156     return @{$self->_roles};
157 }
158
159 sub for_session {
160     my $self = shift;
161
162     #return $self->get($self->config->{'id_field'});
163
164     #my $frozenuser = $self->_user->result_source->schema->freeze( $self->_user );
165     #return $frozenuser;
166
167     my %userdata = $self->_user->get_columns();
168
169     # If use_userdata_from_session is set, then store all of the columns of the user obj in the session
170     if (exists($self->config->{'use_userdata_from_session'}) && $self->config->{'use_userdata_from_session'} != 0) {
171         return \%userdata;
172     } else { # Otherwise, we just need the PKs for load() to use.
173         my %pk_fields = map { ($_ => $userdata{$_}) } @{ $self->config->{id_field} };
174         return \%pk_fields;
175     }
176 }
177
178 sub from_session {
179     my ($self, $frozenuser, $c) = @_;
180
181     #my $obj = $self->resultset->result_source->schema->thaw( $frozenuser );
182     #$self->_user($obj);
183
184     #if (!exists($self->config->{'use_userdata_from_session'}) || $self->config->{'use_userdata_from_session'} == 0) {
185 #        $self->_user->discard_changes();
186 #    }
187 #
188 #    return $self;
189 #
190 ## if use_userdata_from_session is defined in the config, we fill in the user data from the session.
191     if (exists($self->config->{'use_userdata_from_session'}) && $self->config->{'use_userdata_from_session'} != 0) {
192         my $obj = $self->resultset->new_result({ %$frozenuser });
193         $obj->in_storage(1);
194         $self->_user($obj);
195         return $self;
196     }
197
198     if (ref $frozenuser eq 'HASH') {
199         return $self->load({
200             map { ($_ => $frozenuser->{$_}) }
201             @{ $self->config->{id_field} }
202         }, $c);
203     }
204
205     return $self->load( { $self->config->{'id_field'} => $frozenuser }, $c);
206 }
207
208 sub get {
209     my ($self, $field) = @_;
210
211     if (my $code = $self->_user->can($field)) {
212         return $self->_user->$code;
213     }
214     elsif (my $accessor =
215          try { $self->_user->result_source->column_info($field)->{accessor} }) {
216         return $self->_user->$accessor;
217     } else {
218         # XXX this should probably throw
219         return undef;
220     }
221 }
222
223 sub get_object {
224     my ($self, $force) = @_;
225
226     if ($force) {
227         $self->_user->discard_changes;
228     }
229
230     return $self->_user;
231 }
232
233 sub obj {
234     my ($self, $force) = @_;
235
236     return $self->get_object($force);
237 }
238
239 sub auto_create {
240     my $self = shift;
241     $self->_user( $self->resultset->can( 'auto_create' ) ? $self->resultset->auto_create( @_ )
242                 : $self->resultset->create( @_ ) );
243     return $self;
244 }
245
246 sub auto_update {
247     my $self = shift;
248     $self->_user->auto_update( @_ );
249 }
250
251 sub can {
252     my $self = shift;
253     return $self->SUPER::can(@_) || do {
254         my ($method) = @_;
255         if (my $code = $self->_user->can($method)) {
256             sub { shift->_user->$code(@_) }
257         } elsif (my $accessor =
258             try { $self->_user->result_source->column_info($method)->{accessor} }) {
259             sub { shift->_user->$accessor }
260         } else {
261             undef;
262         }
263     };
264 }
265
266 sub AUTOLOAD {
267     my $self = shift;
268     (my $method) = (our $AUTOLOAD =~ /([^:]+)$/);
269     return if $method eq "DESTROY";
270
271     if (my $code = $self->_user->can($method)) {
272         return $self->_user->$code(@_);
273     }
274     elsif (my $accessor =
275          try { $self->_user->result_source->column_info($method)->{accessor} }) {
276         return $self->_user->$accessor(@_);
277     } else {
278         # XXX this should also throw
279         return undef;
280     }
281 }
282
283 __PACKAGE__->meta->make_immutable(inline_constructor => 0);
284
285 1;
286 __END__
287
288 =head1 NAME
289
290 Catalyst::Authentication::Store::DBIx::Class::User - The backing user
291 class for the Catalyst::Authentication::Store::DBIx::Class storage
292 module.
293
294 =head1 VERSION
295
296 This documentation refers to version 0.1503.
297
298 =head1 SYNOPSIS
299
300 Internal - not used directly, please see
301 L<Catalyst::Authentication::Store::DBIx::Class> for details on how to
302 use this module. If you need more information than is present there, read the
303 source.
304
305
306
307 =head1 DESCRIPTION
308
309 The Catalyst::Authentication::Store::DBIx::Class::User class implements user storage
310 connected to an underlying DBIx::Class schema object.
311
312 =head1 SUBROUTINES / METHODS
313
314 =head2 new
315
316 Constructor.
317
318 =head2 load ( $authinfo, $c )
319
320 Retrieves a user from storage using the information provided in $authinfo.
321
322 =head2 supported_features
323
324 Indicates the features supported by this class.  These are currently Roles and Session.
325
326 =head2 roles
327
328 Returns an array of roles associated with this user, if roles are configured for this user class.
329
330 =head2 for_session
331
332 Returns a serialized user for storage in the session.
333
334 =head2 from_session
335
336 Revives a serialized user from storage in the session.
337
338 =head2 get ( $fieldname )
339
340 Returns the value of $fieldname for the user in question.  Roughly translates to a call to
341 the DBIx::Class::Row's get_column( $fieldname ) routine.
342
343 =head2 get_object
344
345 Retrieves the DBIx::Class object that corresponds to this user
346
347 =head2 obj (method)
348
349 Synonym for get_object
350
351 =head2 auto_create
352
353 This is called when the auto_create_user option is turned on in
354 Catalyst::Plugin::Authentication and a user matching the authinfo provided is not found.
355 By default, and if available, this will call the C<auto_create()> method of the resultset associated
356 with this object, otherwise it will call C<create()> on it.
357
358 It is up to you to implement the C<auto_create> method if required.
359
360 =head2 auto_update
361
362 This is called when the auto_update_user option is turned on in
363 Catalyst::Plugin::Authentication. Note that by default the DBIx::Class store
364 uses every field in the authinfo hash to match the user. This means any
365 information you provide with the intent to update must be ignored during the
366 user search process. Otherwise the information will most likely cause the user
367 record to not be found. To ignore fields in the search process, you
368 have to add the fields you wish to update to the 'ignore_fields_in_find'
369 authinfo element.  Alternately, you can use one of the advanced row retrieval
370 methods (searchargs or resultset).
371
372 By default, auto_update will call the C<auto_update()> method of the
373 DBIx::Class::Row object associated with the user. It is up to you to implement
374 that method (probably in your schema file)
375
376 =head2 AUTOLOAD
377
378 Delegates method calls to the underlieing user row.
379
380 =head2 can
381
382 Delegates handling of the C<< can >> method to the underlieing user row.
383
384 =head1 BUGS AND LIMITATIONS
385
386 None known currently, please email the author if you find any.
387
388 =head1 AUTHOR
389
390 Jason Kuri (jayk@cpan.org)
391
392 =head1 CONTRIBUTORS
393
394 Matt S Trout (mst) <mst@shadowcat.co.uk>
395
396 (fixes wrt can/AUTOLOAD sponsored by L<http://reask.com/>)
397
398 =head1 LICENSE
399
400 Copyright (c) 2007-2010 the aforementioned authors. All rights
401 reserved. This program is free software; you can redistribute
402 it and/or modify it under the same terms as Perl itself.
403
404 =cut