Move init stuff to before 'setup_finalize'
[catagits/Catalyst-Plugin-Authentication.git] / lib / Catalyst / Authentication / Credential / Password.pm
1 package Catalyst::Authentication::Credential::Password;
2 use Moose;
3 use namespace::autoclean;
4
5 use Scalar::Util        ();
6 use Catalyst::Exception ();
7 use Digest              ();
8
9 has [qw/_config realm/] => ( is => 'rw' );
10
11 sub BUILDARGS {
12     my ($class, $config, $app, $realm) = @_;
13     
14     { realm => $realm, _config => $config };
15 }
16
17 sub BUILD {
18     my ($self, $args) = @_;    
19     $self->_config->{'password_field'} ||= 'password';
20     $self->_config->{'password_type'}  ||= 'clear';
21     $self->_config->{'password_hash_type'} ||= 'SHA-1';
22     
23     my $passwordtype = $self->_config->{'password_type'};
24     if (!grep /$passwordtype/, ('none', 'clear', 'hashed', 'salted_hash', 'crypted', 'self_check')) {
25         Catalyst::Exception->throw(__PACKAGE__ . " used with unsupported password type: " . $self->_config->{'password_type'});
26     }
27 }
28
29 sub authenticate {
30     my ( $self, $c, $realm, $authinfo ) = @_;
31
32     ## because passwords may be in a hashed format, we have to make sure that we remove the 
33     ## password_field before we pass it to the user routine, as some auth modules use 
34     ## all data passed to them to find a matching user... 
35     my $userfindauthinfo = {%{$authinfo}};
36     delete($userfindauthinfo->{$self->_config->{'password_field'}});
37     
38     my $user_obj = $realm->find_user($userfindauthinfo, $c);
39     if (ref($user_obj)) {
40         if ($self->check_password($user_obj, $authinfo)) {
41             return $user_obj;
42         }
43     } else {
44         $c->log->debug("Unable to locate user matching user info provided") if $c->debug;
45         return;
46     }
47 }
48
49 sub check_password {
50     my ( $self, $user, $authinfo ) = @_;
51     
52     if ($self->_config->{'password_type'} eq 'self_check') {
53         return $user->check_password($authinfo->{$self->_config->{'password_field'}});
54     } else {
55         my $password = $authinfo->{$self->_config->{'password_field'}};
56         my $storedpassword = $user->get($self->_config->{'password_field'});
57         
58         if ($self->_config->{'password_type'} eq 'none') {
59             return 1;
60         } elsif ($self->_config->{'password_type'} eq 'clear') {
61             # FIXME - Should we warn in the $storedpassword undef case, 
62             #         as the user probably fluffed the config?
63             return unless defined $storedpassword;
64             return $password eq $storedpassword;
65         } elsif ($self->_config->{'password_type'} eq 'crypted') {            
66             return $storedpassword eq crypt( $password, $storedpassword );
67         } elsif ($self->_config->{'password_type'} eq 'salted_hash') {
68             require Crypt::SaltedHash;
69             my $salt_len = $self->_config->{'password_salt_len'} ? $self->_config->{'password_salt_len'} : 0;
70             return Crypt::SaltedHash->validate( $storedpassword, $password,
71                 $salt_len );
72         } elsif ($self->_config->{'password_type'} eq 'hashed') {
73
74              my $d = Digest->new( $self->_config->{'password_hash_type'} );
75              $d->add( $self->_config->{'password_pre_salt'} || '' );
76              $d->add($password);
77              $d->add( $self->_config->{'password_post_salt'} || '' );
78
79              my $computed    = $d->clone()->digest;
80              my $b64computed = $d->clone()->b64digest;
81              return ( ( $computed eq $storedpassword )
82                    || ( unpack( "H*", $computed ) eq $storedpassword )
83                    || ( $b64computed eq $storedpassword)
84                    || ( $b64computed.'=' eq $storedpassword) );
85         }
86     }
87 }
88
89 __PACKAGE__->meta->make_immutable;
90
91 __END__
92
93 =pod
94
95 =head1 NAME
96
97 Catalyst::Authentication::Credential::Password - Authenticate a user
98 with a password.
99
100 =head1 SYNOPSIS
101
102     use Catalyst qw/
103       Authentication
104       /;
105
106     package MyApp::Controller::Auth;
107
108     sub login : Local {
109         my ( $self, $c ) = @_;
110
111         $c->authenticate( { username => $c->req->param('username'),
112                             password => $c->req->param('password') });
113     }
114
115 =head1 DESCRIPTION
116
117 This authentication credential checker takes authentication information
118 (most often a username) and a password, and attempts to validate the password
119 provided against the user retrieved from the store.
120
121 =head1 CONFIGURATION
122
123     # example
124     __PACKAGE__->config->{'Plugin::Authentication'} = 
125                 {  
126                     default_realm => 'members',
127                     realms => {
128                         members => {
129                             
130                             credential => {
131                                 class => 'Password',
132                                 password_field => 'password',
133                                 password_type => 'hashed',
134                                 password_hash_type => 'SHA-1'                                
135                             },    
136                             ...
137
138
139 The password module is capable of working with several different password
140 encryption/hashing algorithms. The one the module uses is determined by the
141 credential configuration.
142
143 Those who have used L<Catalyst::Plugin::Authentication> prior to the 0.10 release
144 should note that the password field and type information is no longer part
145 of the store configuration and is now part of the Password credential configuration.
146
147 =over 4 
148
149 =item class 
150
151 The classname used for Credential. This is part of
152 L<Catalyst::Plugin::Authentication> and is the method by which
153 Catalyst::Authentication::Credential::Password is loaded as the
154 credential validator. For this module to be used, this must be set to
155 'Password'.
156
157 =item password_field
158
159 The field in the user object that contains the password. This will vary
160 depending on the storage class used, but is most likely something like
161 'password'. In fact, this is so common that if this is left out of the config,
162 it defaults to 'password'. This field is obtained from the user object using
163 the get() method. Essentially: $user->get('passwordfieldname'); 
164 B<NOTE> If the password_field is something other than 'password', you must 
165 be sure to use that same field name when calling $c->authenticate(). 
166
167 =item password_type 
168
169 This sets the password type.  Often passwords are stored in crypted or hashed
170 formats.  In order for the password module to verify the plaintext password 
171 passed in, it must be told what format the password will be in when it is retreived
172 from the user object. The supported options are:
173
174 =over 8
175
176 =item none
177
178 No password check is done. An attempt is made to retrieve the user based on
179 the information provided in the $c->authenticate() call. If a user is found, 
180 authentication is considered to be successful.
181
182 =item clear
183
184 The password in user is in clear text and will be compared directly.
185
186 =item self_check
187
188 This option indicates that the password should be passed to the check_password()
189 routine on the user object returned from the store.  
190
191 =item crypted
192
193 The password in user is in UNIX crypt hashed format.  
194
195 =item salted_hash
196
197 The password in user is in salted hash format, and will be validated
198 using L<Crypt::SaltedHash>.  If this password type is selected, you should
199 also provide the B<password_salt_len> config element to define the salt length.
200
201 =item hashed
202
203 If the user object supports hashed passwords, they will be used in conjunction
204 with L<Digest>. The following config elements affect the hashed configuration:
205
206 =over 8
207
208 =item password_hash_type 
209
210 The hash type used, passed directly to L<Digest/new>.  
211
212 =item password_pre_salt 
213
214 Any pre-salt data to be passed to L<Digest/add> before processing the password.
215
216 =item password_post_salt
217
218 Any post-salt data to be passed to L<Digest/add> after processing the password.
219
220 =back
221
222 =back
223
224 =back
225
226 =head1 USAGE
227
228 The Password credential module is very simple to use. Once configured as
229 indicated above, authenticating using this module is simply a matter of
230 calling $c->authenticate() with an authinfo hashref that includes the
231 B<password> element. The password element should contain the password supplied
232 by the user to be authenticated, in clear text. The other information supplied
233 in the auth hash is ignored by the Password module, and simply passed to the
234 auth store to be used to retrieve the user. An example call follows:
235
236     if ($c->authenticate({ username => $username,
237                            password => $password} )) {
238         # authentication successful
239     } else {
240         # authentication failed
241     }
242
243 =head1 METHODS
244
245 There are no publicly exported routines in the Password module (or indeed in
246 most credential modules.)  However, below is a description of the routines 
247 required by L<Catalyst::Plugin::Authentication> for all credential modules.
248
249 =head2 new( $config, $app, $realm )
250
251 Instantiate a new Password object using the configuration hash provided in
252 $config. A reference to the application is provided as the second argument.
253 Note to credential module authors: new() is called during the application's
254 plugin setup phase, which is before the application specific controllers are
255 loaded. The practical upshot of this is that things like $c->model(...) will
256 not function as expected.
257
258 =head2 authenticate( $authinfo, $c )
259
260 Try to log a user in, receives a hashref containing authentication information
261 as the first argument, and the current context as the second.
262
263 =head2 check_password( )
264
265 =cut