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