support setting columns from AUTOLOAD too
[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->{'resultset'})) {
78         $self->_user($authinfo->{'resultset'}->first);
79     } elsif ($dbix_class_config && exists($authinfo->{'searchargs'})) {
80         $self->_user($self->resultset->search(@{$authinfo->{'searchargs'}})->first);
81     } else {
82         ## merge the ignore fields array into a hash - so we can do an easy check while building the query
83         my %ignorefields = map { $_ => 1} @{$self->config->{'ignore_fields_in_find'}};
84         my $searchargs = {};
85
86         # now we walk all the fields passed in, and build up a search hash.
87         foreach my $key (grep {!$ignorefields{$_}} keys %{$authinfo}) {
88             if ($self->resultset->result_source->has_column($key)) {
89                 $searchargs->{$key} = $authinfo->{$key};
90             }
91         }
92         if (keys %{$searchargs}) {
93             $self->_user($self->resultset->search($searchargs)->first);
94         } else {
95             Catalyst::Exception->throw(
96                 "Failed to load user data.  You passed [" . join(',', keys %{$authinfo}) . "]"
97                   . " to authenticate() but your user source (" .  $self->config->{'user_model'} . ")"
98                   . " only has these columns: [" . join( ",", $self->resultset->result_source->columns ) . "]"
99                   . "   Check your authenticate() call."
100             );
101         }
102     }
103
104     if ($self->get_object) {
105         return $self;
106     } else {
107         return undef;
108     }
109
110 }
111
112 sub supported_features {
113     my $self = shift;
114
115     return {
116         session         => 1,
117         roles           => 1,
118     };
119 }
120
121
122 sub roles {
123     my ( $self ) = shift;
124     ## this used to load @wantedroles - but that doesn't seem to be used by the roles plugin, so I dropped it.
125
126     ## shortcut if we have already retrieved them
127     if (ref $self->_roles eq 'ARRAY') {
128         return(@{$self->_roles});
129     }
130
131     my @roles = ();
132     if (exists($self->config->{'role_column'})) {
133         my $role_data = $self->get($self->config->{'role_column'});
134         if ($role_data) {
135             @roles = split /[\s,\|]+/, $self->get($self->config->{'role_column'});
136         }
137         $self->_roles(\@roles);
138     } elsif (exists($self->config->{'role_relation'})) {
139         my $relation = $self->config->{'role_relation'};
140         if ($self->_user->$relation->result_source->has_column($self->config->{'role_field'})) {
141             @roles = map {
142                 $_->get_column($self->config->{role_field})
143             } $self->_user->$relation->search(undef, {
144                 columns => [ $self->config->{role_field} ]
145             })->all;
146             $self->_roles(\@roles);
147         } else {
148             Catalyst::Exception->throw("role table does not have a column called " . $self->config->{'role_field'});
149         }
150     } else {
151         Catalyst::Exception->throw("user->roles accessed, but no role configuration found");
152     }
153
154     return @{$self->_roles};
155 }
156
157 sub for_session {
158     my $self = shift;
159
160     #return $self->get($self->config->{'id_field'});
161
162     #my $frozenuser = $self->_user->result_source->schema->freeze( $self->_user );
163     #return $frozenuser;
164
165     my %userdata = $self->_user->get_columns();
166     return \%userdata;
167 }
168
169 sub from_session {
170     my ($self, $frozenuser, $c) = @_;
171
172     #my $obj = $self->resultset->result_source->schema->thaw( $frozenuser );
173     #$self->_user($obj);
174
175     #if (!exists($self->config->{'use_userdata_from_session'}) || $self->config->{'use_userdata_from_session'} == 0) {
176 #        $self->_user->discard_changes();
177 #    }
178 #
179 #    return $self;
180 #
181 ## if use_userdata_from_session is defined in the config, we fill in the user data from the session.
182     if (exists($self->config->{'use_userdata_from_session'}) && $self->config->{'use_userdata_from_session'} != 0) {
183         my $obj = $self->resultset->new_result({ %$frozenuser });
184         $obj->in_storage(1);
185         $self->_user($obj);
186         return $self;
187     }
188
189     if (ref $frozenuser eq 'HASH') {
190         return $self->load({
191             map { ($_ => $frozenuser->{$_}) }
192             @{ $self->config->{id_field} }
193         });
194     }
195
196     return $self->load( { $self->config->{'id_field'} => $frozenuser }, $c);
197 }
198
199 sub get {
200     my ($self, $field) = @_;
201
202     if (my $code = $self->_user->can($field)) {
203         return $self->_user->$code;
204     }
205     elsif (my $accessor =
206          try { $self->_user->result_source->column_info($field)->{accessor} }) {
207         return $self->_user->$accessor;
208     } else {
209         # XXX this should probably throw
210         return undef;
211     }
212 }
213
214 sub get_object {
215     my ($self, $force) = @_;
216
217     if ($force) {
218         $self->_user->discard_changes;
219     }
220
221     return $self->_user;
222 }
223
224 sub obj {
225     my ($self, $force) = @_;
226
227     return $self->get_object($force);
228 }
229
230 sub auto_create {
231     my $self = shift;
232     $self->_user( $self->resultset->auto_create( @_ ) );
233     return $self;
234 }
235
236 sub auto_update {
237     my $self = shift;
238     $self->_user->auto_update( @_ );
239 }
240
241 sub AUTOLOAD {
242     my $self = shift;
243     (my $method) = (our $AUTOLOAD =~ /([^:]+)$/);
244     return if $method eq "DESTROY";
245
246     if (my $code = $self->_user->can($method)) {
247         return $self->_user->$code(@_);
248     }
249     elsif (my $accessor =
250          try { $self->_user->result_source->column_info($method)->{accessor} }) {
251         return $self->_user->$accessor(@_);
252     } else {
253         # XXX this should also throw
254         return undef;
255     }
256 }
257
258 __PACKAGE__->meta->make_immutable(inline_constructor => 0);
259
260 1;
261 __END__
262
263 =head1 NAME
264
265 Catalyst::Authentication::Store::DBIx::Class::User - The backing user
266 class for the Catalyst::Authentication::Store::DBIx::Class storage
267 module.
268
269 =head1 VERSION
270
271 This documentation refers to version 0.1200.
272
273 =head1 SYNOPSIS
274
275 Internal - not used directly, please see
276 L<Catalyst::Authentication::Store::DBIx::Class> for details on how to
277 use this module. If you need more information than is present there, read the
278 source.
279
280
281
282 =head1 DESCRIPTION
283
284 The Catalyst::Authentication::Store::DBIx::Class::User class implements user storage
285 connected to an underlying DBIx::Class schema object.
286
287 =head1 SUBROUTINES / METHODS
288
289 =head2 new
290
291 Constructor.
292
293 =head2 load ( $authinfo, $c )
294
295 Retrieves a user from storage using the information provided in $authinfo.
296
297 =head2 supported_features
298
299 Indicates the features supported by this class.  These are currently Roles and Session.
300
301 =head2 roles
302
303 Returns an array of roles associated with this user, if roles are configured for this user class.
304
305 =head2 for_session
306
307 Returns a serialized user for storage in the session.
308
309 =head2 from_session
310
311 Revives a serialized user from storage in the session.
312
313 =head2 get ( $fieldname )
314
315 Returns the value of $fieldname for the user in question.  Roughly translates to a call to
316 the DBIx::Class::Row's get_column( $fieldname ) routine.
317
318 =head2 get_object
319
320 Retrieves the DBIx::Class object that corresponds to this user
321
322 =head2 obj (method)
323
324 Synonym for get_object
325
326 =head2 auto_create
327
328 This is called when the auto_create_user option is turned on in
329 Catalyst::Plugin::Authentication and a user matching the authinfo provided is not found.
330 By default, this will call the C<auto_create()> method of the resultset associated
331 with this object. It is up to you to implement that method.
332
333 =head2 auto_update
334
335 This is called when the auto_update_user option is turned on in
336 Catalyst::Plugin::Authentication. Note that by default the DBIx::Class store
337 uses every field in the authinfo hash to match the user. This means any
338 information you provide with the intent to update must be ignored during the
339 user search process. Otherwise the information will most likely cause the user
340 record to not be found. To ignore fields in the search process, you
341 have to add the fields you wish to update to the 'ignore_fields_in_find'
342 authinfo element.  Alternately, you can use one of the advanced row retrieval
343 methods (searchargs or resultset).
344
345 By default, auto_update will call the C<auto_update()> method of the
346 DBIx::Class::Row object associated with the user. It is up to you to implement
347 that method (probably in your schema file)
348
349 =head1 BUGS AND LIMITATIONS
350
351 None known currently, please email the author if you find any.
352
353 =head1 AUTHOR
354
355 Jason Kuri (jayk@cpan.org)
356
357 =head1 LICENSE
358
359 Copyright (c) 2007 the aforementioned authors. All rights
360 reserved. This program is free software; you can redistribute
361 it and/or modify it under the same terms as Perl itself.
362
363 =cut