version 0.1501
[catagits/Catalyst-Authentication-Store-DBIx-Class.git] / lib / Catalyst / Authentication / Store / DBIx / Class.pm
CommitLineData
6727afe2 1package Catalyst::Authentication::Store::DBIx::Class;
5000f545 2
3use strict;
4use warnings;
5use base qw/Class::Accessor::Fast/;
6
419a8c0b 7our $VERSION= "0.1501";
6727afe2 8
b33ee900 9
10BEGIN {
11 __PACKAGE__->mk_accessors(qw/config/);
12}
13
6727afe2 14
5000f545 15sub new {
16 my ( $class, $config, $app ) = @_;
17
4bebb973 18 ## figure out if we are overriding the default store user class
b33ee900 19 $config->{'store_user_class'} = (exists($config->{'store_user_class'})) ? $config->{'store_user_class'} :
6727afe2 20 "Catalyst::Authentication::Store::DBIx::Class::User";
b33ee900 21
5000f545 22 ## make sure the store class is loaded.
b33ee900 23 Catalyst::Utils::ensure_class_loaded( $config->{'store_user_class'} );
4bebb973 24
b33ee900 25 ## fields can be specified to be ignored during user location. This allows
ff7203cb 26 ## the store to ignore certain fields in the authinfo hash.
4bebb973 27
b33ee900 28 $config->{'ignore_fields_in_find'} ||= [ ];
29
30 my $self = {
31 config => $config
32 };
5000f545 33
34 bless $self, $class;
b33ee900 35
5000f545 36}
37
ba48c9c3 38## --jk note to self:
fff51ece 39## let's use DBIC's get_columns method to return a hash and save / restore that
ba48c9c3 40## from the session. Then we can respond to get() calls, etc. in most cases without
41## resorting to a DB call. If user_object is called, THEN we can hit the DB and
4bebb973 42## return a real object.
5000f545 43sub from_session {
44 my ( $self, $c, $frozenuser ) = @_;
45
f26005a7 46# return $frozenuser if ref $frozenuser;
47
b33ee900 48 my $user = $self->config->{'store_user_class'}->new($self->{'config'}, $c);
b33ee900 49 return $user->from_session($frozenuser, $c);
5000f545 50}
51
52sub for_session {
53 my ($self, $c, $user) = @_;
4bebb973 54
5000f545 55 return $user->for_session($c);
56}
57
58sub find_user {
59 my ( $self, $authinfo, $c ) = @_;
4bebb973 60
b33ee900 61 my $user = $self->config->{'store_user_class'}->new($self->{'config'}, $c);
5000f545 62
b33ee900 63 return $user->load($authinfo, $c);
64
65}
5000f545 66
67sub user_supports {
b33ee900 68 my $self = shift;
69 # this can work as a class method on the user class
70 $self->config->{'store_user_class'}->supports( @_ );
5000f545 71}
72
67f6319b 73sub auto_create_user {
fb689852 74 my( $self, $authinfo, $c ) = @_;
75 my $res = $self->config->{'store_user_class'}->new($self->{'config'}, $c);
76 return $res->auto_create( $authinfo, $c );
77}
78
67f6319b 79sub auto_update_user {
fb689852 80 my( $self, $authinfo, $c, $res ) = @_;
81 $res->auto_update( $authinfo, $c );
82 return $res;
83}
84
5000f545 85__PACKAGE__;
86
87__END__
88
89=head1 NAME
90
6727afe2 91Catalyst::Authentication::Store::DBIx::Class - A storage class for Catalyst Authentication using DBIx::Class
5000f545 92
93=head1 VERSION
94
419a8c0b 95This documentation refers to version 0.1501.
5000f545 96
97=head1 SYNOPSIS
98
93102ff5 99 use Catalyst qw/
100 Authentication
101 Authorization::Roles/;
102
4bebb973 103 __PACKAGE__->config->{authentication} =
104 {
93102ff5 105 default_realm => 'members',
106 realms => {
107 members => {
108 credential => {
109 class => 'Password',
110 password_field => 'password',
111 password_type => 'clear'
112 },
113 store => {
114 class => 'DBIx::Class',
f55cb81e 115 user_model => 'MyApp::User',
93102ff5 116 role_relation => 'roles',
4bebb973 117 role_field => 'rolename',
93102ff5 118 }
c1d29ab7 119 }
93102ff5 120 }
121 };
122
123 # Log a user in:
4bebb973 124
93102ff5 125 sub login : Global {
126 my ( $self, $c ) = @_;
4bebb973 127
128 $c->authenticate({
4bad18f4 129 screen_name => $c->req->params->{username},
130 password => $c->req->params->{password},
c1d29ab7 131 status => [ 'registered', 'loggedin', 'active']
132 }))
93102ff5 133 }
4bebb973 134
135 # verify a role
136
93102ff5 137 if ( $c->check_user_roles( 'editor' ) ) {
138 # do editor stuff
139 }
4bebb973 140
5000f545 141=head1 DESCRIPTION
142
4bebb973 143The Catalyst::Authentication::Store::DBIx::Class class provides
93102ff5 144access to authentication information stored in a database via DBIx::Class.
145
146=head1 CONFIGURATION
147
148The DBIx::Class authentication store is activated by setting the store
f55cb81e 149config's B<class> element to DBIx::Class as shown above. See the
150L<Catalyst::Plugin::Authentication> documentation for more details on
151configuring the store. You can also use
152L<Catalyst::Authentication::Realm::SimpleDB> for a simplified setup.
93102ff5 153
154The DBIx::Class storage module has several configuration options
155
93102ff5 156
4bebb973 157 __PACKAGE__->config->{authentication} =
158 {
93102ff5 159 default_realm => 'members',
160 realms => {
161 members => {
162 credential => {
163 # ...
164 },
165 store => {
166 class => 'DBIx::Class',
f55cb81e 167 user_model => 'MyApp::User',
93102ff5 168 role_relation => 'roles',
169 role_field => 'rolename',
f26005a7 170 ignore_fields_in_find => [ 'remote_name' ],
4bebb973 171 use_userdata_from_session => 1,
93102ff5 172 }
173 }
174 }
175 };
176
b81ead77 177=over 4
178
93102ff5 179=item class
180
fff51ece 181Class is part of the core Catalyst::Plugin::Authentication module; it
93102ff5 182contains the class name of the store to be used.
183
f55cb81e 184=item user_model
5000f545 185
f55cb81e 186Contains the model name (as passed to $c->model()) of the DBIx::Class schema
187to use as the source for user information. This config item is B<REQUIRED>.
88b34b66 188
4bebb973 189(Note that this option used to be called C<< user_class >>. C<< user_class >> is
88b34b66 190still functional, but should be used only for compatibility with previous configs.
191The setting called C<< user_class >> on other authentication stores is
192present, but named C<< store_user_class >> in this store)
5000f545 193
93102ff5 194=item role_column
5000f545 195
93102ff5 196If your role information is stored in the same table as the rest of your user
197information, this item tells the module which field contains your role
198information. The DBIx::Class authentication store expects the data in this
4bebb973 199field to be a series of role names separated by some combination of spaces,
200commas, or pipe characters.
5000f545 201
93102ff5 202=item role_relation
5000f545 203
93102ff5 204If your role information is stored in a separate table, this is the name of
4bebb973 205the relation that will lead to the roles the user is in. If this is
fff51ece 206specified, then a role_field is also required. Also when using this method
4bebb973 207it is expected that your role table will return one row for each role
93102ff5 208the user is in.
5000f545 209
93102ff5 210=item role_field
5000f545 211
4bebb973 212This is the name of the field in the role table that contains the string
213identifying the role.
5000f545 214
93102ff5 215=item ignore_fields_in_find
5000f545 216
c1d29ab7 217This item is an array containing fields that may be passed to the
218$c->authenticate() routine (and therefore find_user in the storage class), but
219which should be ignored when creating the DBIx::Class search to retrieve a
220user. This makes it possible to avoid problems when a credential requires an
221authinfo element whose name overlaps with a column name in your users table.
222If this doesn't make sense to you, you probably don't need it.
5000f545 223
f26005a7 224=item use_userdata_from_session
225
4bebb973 226Under normal circumstances, on each request the user's data is re-retrieved
227from the database using the primary key for the user table. When this flag
f26005a7 228is set in the configuration, it causes the DBIx::Class store to avoid this
4bebb973 229database hit on session restore. Instead, the user object's column data
230is retrieved from the session and used as-is.
f26005a7 231
232B<NOTE>: Since the user object's column
4bebb973 233data is only stored in the session during the initial authentication of
f26005a7 234the user, turning this on can potentially lead to a situation where the data
235in $c->user is different from what is stored the database. You can force
236a reload of the data from the database at any time by calling $c->user->get_object(1);
4bebb973 237Note that this will update $c->user for the remainder of this request.
f26005a7 238It will NOT update the session. If you need to update the session
4bebb973 239you should call $c->update_user_in_session() as well.
f26005a7 240
93102ff5 241=item store_user_class
5000f545 242
4bebb973 243This allows you to override the authentication user class that the
28aa2168 244DBIx::Class store module uses to perform its work. Most of the
4bebb973 245work done in this module is actually done by the user class,
6727afe2 246L<Catalyst::Authentication::Store::DBIx::Class::User>, so
93102ff5 247overriding this doesn't make much sense unless you are using your
4bebb973 248own class to extend the functionality of the existing class.
93102ff5 249Chances are you do not want to set this.
5000f545 250
f7e6d29f 251=item id_field
252
253In most cases, this config variable does not need to be set, as
254Catalyst::Authentication::Store::DBIx::Class will determine the primary
4bebb973 255key of the user table on its own. If you need to override the default,
f7e6d29f 256or your user table has multiple primary keys, then id_field
257should contain the column name that should be used to restore the user.
258A given value in this column should correspond to a single user in the database.
4bebb973 259Note that this is used B<ONLY> when restoring a user from the session and
f7e6d29f 260has no bearing whatsoever in the initial authentication process. Note also
261that if use_userdata_from_session is enabled, this config parameter
262is not used at all.
263
93102ff5 264=back
5000f545 265
4bebb973 266=head1 USAGE
5000f545 267
6727afe2 268The L<Catalyst::Authentication::Store::DBIx::Class> storage module
4bebb973 269is not called directly from application code. You interface with it
270through the $c->authenticate() call.
5000f545 271
c1d29ab7 272There are three methods you can use to retrieve information from the DBIx::Class
273storage module. They are Simple retrieval, and the advanced retrieval methods
274Searchargs and Resultset.
275
4bebb973 276=head2 Simple Retrieval
c1d29ab7 277
28aa2168 278The first, and most common, method is simple retrieval. As its name implies
c1d29ab7 279simple retrieval allows you to simply to provide the column => value pairs
280that should be used to locate the user in question. An example of this usage
281is below:
282
4bebb973 283 if ($c->authenticate({
f7e6d29f 284 screen_name => $c->req->params->{'username'},
c1d29ab7 285 password => $c->req->params->{'password'},
286 status => [ 'registered', 'active', 'loggedin']
287 })) {
288
289 # ... authenticated user code here
290 }
291
4bebb973 292The above example would attempt to retrieve a user whose username column (here,
f7e6d29f 293screen_name) matched the username provided, and whose status column matched one of the
c1d29ab7 294values provided. These name => value pairs are used more or less directly in
fff51ece 295the DBIx::Class search() routine, so in most cases, you can use DBIx::Class
c1d29ab7 296syntax to retrieve the user according to whatever rules you have.
297
298NOTE: Because the password in most cases is encrypted - it is not used
28aa2168 299directly but its encryption and comparison with the value provided is usually
c1d29ab7 300handled by the Password Credential. Part of the Password Credential's behavior
301is to remove the password argument from the authinfo that is passed to the
6727afe2 302storage module. See L<Catalyst::Authentication::Credential::Password>.
c1d29ab7 303
304One thing you need to know about this retrieval method is that the name
fff51ece 305portion of the pair is checked against the user class's column list. Pairs are
c1d29ab7 306only used if a matching column is found. Other pairs will be ignored. This
307means that you can only provide simple name-value pairs, and that some more
308advanced DBIx::Class constructs, such as '-or', '-and', etc. are in most cases
309not possible using this method. For queries that require this level of
310functionality, see the 'searchargs' method below.
311
312=head2 Advanced Retrieval
313
314The Searchargs and Resultset retrieval methods are used when more advanced
315features of the underlying L<DBIx::Class> schema are required. These methods
316provide a direct interface with the DBIx::Class schema and therefore
4bebb973 317require a better understanding of the DBIx::Class module.
c1d29ab7 318
319=head3 The dbix_class key
320
321Since the format of these arguments are often complex, they are not keys in
4bebb973 322the base authinfo hash. Instead, both of these arguments are placed within
323a hash attached to the store-specific 'dbix_class' key in the base $authinfo
c1d29ab7 324hash. When the DBIx::Class authentication store sees the 'dbix_class' key
325in the passed authinfo hash, all the other information in the authinfo hash
4bebb973 326is ignored and only the values within the 'dbix_class' hash are used as
c1d29ab7 327though they were passed directly within the authinfo hash. In other words, if
328'dbix_class' is present, it replaces the authinfo hash for processing purposes.
329
330The 'dbix_class' hash can be used to directly pass arguments to the
331DBIx::Class authentication store. Reasons to do this are to avoid credential
332modification of the authinfo hash, or to avoid overlap between credential and
333store key names. It's a good idea to avoid using it in this way unless you are
334sure you have an overlap/modification issue. However, the two advanced
6bd97524 335retrieval methods, B<searchargs>, B<result> and B<resultset>, require its use,
336as they are only processed as part of the 'dbix_class' hash.
c1d29ab7 337
338=over 4
339
340=item Searchargs
341
342The B<searchargs> method of retrieval allows you to specify an arrayref containing
ad93b3e9 343the two arguments to the search() method from L<DBIx::Class::ResultSet>. If provided,
c1d29ab7 344all other args are ignored, and the search args provided are used directly to locate
345the user. An example will probably make more sense:
346
347 if ($c->authenticate(
4bebb973 348 {
c1d29ab7 349 password => $password,
4bebb973 350 'dbix_class' =>
c1d29ab7 351 {
f26005a7 352 searchargs => [ { -or => [ username => $username,
c1d29ab7 353 email => $email,
4bebb973 354 clientid => $clientid ]
c1d29ab7 355 },
4bebb973 356 { prefetch => qw/ preferences / }
c1d29ab7 357 ]
358 }
4bebb973 359 } ) )
c1d29ab7 360 {
361 # do successful authentication actions here.
362 }
363
364The above would allow authentication based on any of the three items -
fff51ece 365username, email, or clientid - and would prefetch the data related to that user
c1d29ab7 366from the preferences table. The searchargs array is passed directly to the
f55cb81e 367search() method associated with the user_model.
c1d29ab7 368
6bd97524 369=item Result
370
371The B<result> method of retrieval allows you to look up the user yourself and
372pass on the loaded user to the authentication store.
373
374 my $user = $ctx->model('MyApp::User')->find({ ... });
375
376 if ($ctx->authenticate({ dbix_class => { result => $user } })) {
377 ...
378 }
379
380Be aware that the result method will not verify that you are passing a result
381that is attached to the same user_model as specified in the config or even
382loaded from the database, as opposed to existing only in memory. It's your
383responsibility to make sure of that.
384
c1d29ab7 385=item Resultset
386
387The B<resultset> method of retrieval allows you to directly specify a
388resultset to be used for user retrieval. This allows you to create a resultset
389within your login action and use it for retrieving the user. A simple example:
390
391 my $rs = $c->model('MyApp::User')->search({ email => $c->request->params->{'email'} });
392 ... # further $rs adjustments
4bebb973 393
394 if ($c->authenticate({
c1d29ab7 395 password => $password,
fff51ece 396 'dbix_class' => { resultset => $rs }
c1d29ab7 397 })) {
398 # do successful authentication actions here.
4bebb973 399 }
c1d29ab7 400
401Be aware that the resultset method will not verify that you are passing a
f55cb81e 402resultset that is attached to the same user_model as specified in the config.
c1d29ab7 403
6bd97524 404NOTE: The resultset and searchargs methods of user retrieval, consider the first
405row returned to be the matching user. In most cases there will be only one
406matching row, but it is easy to produce multiple rows, especially when using the
407advanced retrieval methods. Remember, what you get when you use this module is
408what you would get when calling search(...)->first;
c1d29ab7 409
410NOTE ALSO: The user info used to save the user to the session and to retrieve
411it is the same regardless of what method of retrieval was used. In short,
4bebb973 412the value in the id field (see 'id_field' config item) is used to retrieve the
c1d29ab7 413user from the database upon restoring from the session. When the DBIx::Class storage
414module does this, it does so by doing a simple search using the id field. In other
4bebb973 415words, it will not use the same arguments you used to request the user initially.
416This is especially important to those using the advanced methods of user retrieval.
c1d29ab7 417If you need more complicated logic when reviving the user from the session, you will
4bebb973 418most likely want to subclass the L<Catalyst::Authentication::Store::DBIx::Class::User> class
c1d29ab7 419and provide your own for_session and from_session routines.
420
421=back
5000f545 422
6727afe2 423
93102ff5 424=head1 METHODS
5000f545 425
4bebb973 426There are no publicly exported routines in the DBIx::Class authentication
427store (or indeed in most authentication stores). However, below is a
428description of the routines required by L<Catalyst::Plugin::Authentication>
429for all authentication stores. Please see the documentation for
93102ff5 430L<Catalyst::Plugin::Authentication::Internals> for more information.
431
6727afe2 432
433=head2 new ( $config, $app )
93102ff5 434
c1d29ab7 435Constructs a new store object.
93102ff5 436
4bebb973 437=head2 find_user ( $authinfo, $c )
93102ff5 438
c1d29ab7 439Finds a user using the information provided in the $authinfo hashref and
fff51ece 440returns the user, or undef on failure. This is usually called from the
c1d29ab7 441Credential. This translates directly to a call to
6727afe2 442L<Catalyst::Authentication::Store::DBIx::Class::User>'s load() method.
93102ff5 443
6727afe2 444=head2 for_session ( $c, $user )
93102ff5 445
c1d29ab7 446Prepares a user to be stored in the session. Currently returns the value of
fff51ece 447the user's id field (as indicated by the 'id_field' config element)
93102ff5 448
6727afe2 449=head2 from_session ( $c, $frozenuser)
93102ff5 450
c1d29ab7 451Revives a user from the session based on the info provided in $frozenuser.
93102ff5 452Currently treats $frozenuser as an id and retrieves a user with a matching id.
453
6727afe2 454=head2 user_supports
93102ff5 455
4bebb973 456Provides information about what the user object supports.
93102ff5 457
76e7a763 458=head2 auto_update_user( $authinfo, $c, $res )
459
460This method is called if the realm's auto_update_user setting is true. It
461will delegate to the user object's C<auto_update> method.
67f6319b 462
76e7a763 463=head2 auto_create_user( $authinfo, $c )
67f6319b 464
76e7a763 465This method is called if the realm's auto_create_user setting is true. It
fff51ece 466will delegate to the user class's (resultset) C<auto_create> method.
5000f545 467
468=head1 NOTES
469
93102ff5 470As of the current release, session storage consists of simply storing the user's
fff51ece 471id in the session, and then using that same id to re-retrieve the user's information
93102ff5 472from the database upon restoration from the session. More dynamic storage of
473user information in the session is intended for a future release.
5000f545 474
475=head1 BUGS AND LIMITATIONS
476
fff51ece 477None known currently; please email the author if you find any.
5000f545 478
479=head1 SEE ALSO
480
93102ff5 481L<Catalyst::Plugin::Authentication>, L<Catalyst::Plugin::Authentication::Internals>,
482and L<Catalyst::Plugin::Authorization::Roles>
5000f545 483
484=head1 AUTHOR
485
b33ee900 486Jason Kuri (jayk@cpan.org)
5000f545 487
c1d29ab7 488=head1 LICENSE
5000f545 489
c1d29ab7 490Copyright (c) 2007 the aforementioned authors. All rights
93102ff5 491reserved. This program is free software; you can redistribute
492it and/or modify it under the same terms as Perl itself.
5000f545 493
494=cut