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