two tiny cleanups in trunk
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Manual / Tutorial / Authentication.pod
CommitLineData
4d583dd8 1=head1 NAME
2
64ccd8a8 3Catalyst::Manual::Tutorial::Authentication - Catalyst Tutorial - Part 4: Authentication
4d583dd8 4
5
4d583dd8 6=head1 OVERVIEW
7
8This is B<Part 4 of 9> for the Catalyst tutorial.
9
64ccd8a8 10L<Tutorial Overview|Catalyst::Manual::Tutorial>
4d583dd8 11
12=over 4
13
14=item 1
15
16L<Introduction|Catalyst::Manual::Tutorial::Intro>
17
18=item 2
19
20L<Catalyst Basics|Catalyst::Manual::Tutorial::CatalystBasics>
21
22=item 3
23
64ccd8a8 24L<Basic CRUD|Catalyst::Manual::Tutorial_BasicCRUD>
4d583dd8 25
26=item 4
27
28B<Authentication>
29
30=item 5
31
32L<Authorization|Catalyst::Manual::Tutorial::Authorization>
33
34=item 6
35
36L<Debugging|Catalyst::Manual::Tutorial::Debugging>
37
38=item 7
39
40L<Testing|Catalyst::Manual::Tutorial::Testing>
41
42=item 8
43
44L<AdvancedCRUD|Catalyst::Manual::Tutorial::AdvancedCRUD>
45
46=item 9
47
71dedf57 48L<Appendices|Catalyst::Manual::Tutorial::Appendicies>
4d583dd8 49
50=back
51
52
4d583dd8 53=head1 DESCRIPTION
54
64ccd8a8 55Now that we finally have a simple yet functional application, we can
71dedf57 56focus on providing authentication (with authorization coming next in
57Part 5).
4d583dd8 58
64ccd8a8 59This part of the tutorial is divided into two main sections: 1) basic,
60cleartext authentication and 2) hash-based authentication.
4d583dd8 61
64ccd8a8 62B<TIP>: Note that all of the code for this part of the tutorial can be
63pulled from the Catalyst Subversion repository in one step with the
64following command:
4d583dd8 65
66 svn checkout http://dev.catalyst.perl.org/repos/Catalyst/trunk/examples/Tutorial@###
67 IMPORTANT: Does not work yet. Will be completed for final version.
68
69
4d583dd8 70=head1 BASIC AUTHENTICATION
71
71dedf57 72This section explores how to add authentication logic to a Catalyst
73application.
4d583dd8 74
a63e6e67 75
4d583dd8 76=head2 Add Users and Roles to the Database
77
71dedf57 78First, we add both user and role information to the database (we will
79add the role information here although it will not be used until the
64ccd8a8 80authorization section, Part 5). Create a new SQL script file by opening
81C<myapp02.sql> in your editor and insert:
4d583dd8 82
83 --
84 -- Add users and roles tables, along with a many-to-many join table
85 --
86 CREATE TABLE users (
87 id INTEGER PRIMARY KEY,
88 username TEXT,
89 password TEXT,
90 email_address TEXT,
91 first_name TEXT,
92 last_name TEXT,
93 active INTEGER
94 );
95 CREATE TABLE roles (
96 id INTEGER PRIMARY KEY,
97 role TEXT
98 );
99 CREATE TABLE user_roles (
100 user_id INTEGER,
101 role_id INTEGER,
102 PRIMARY KEY (user_id, role_id)
103 );
104 --
105 -- Load up some initial test data
106 --
107 INSERT INTO users VALUES (1, 'test01', 'mypass', 't01@na.com', 'Joe', 'Blow', 1);
108 INSERT INTO users VALUES (2, 'test02', 'mypass', 't02@na.com', 'Jane', 'Doe', 1);
109 INSERT INTO users VALUES (3, 'test03', 'mypass', 't03@na.com', 'No', 'Go', 0);
110 INSERT INTO roles VALUES (1, 'user');
111 INSERT INTO roles VALUES (2, 'admin');
112 INSERT INTO user_roles VALUES (1, 1);
113 INSERT INTO user_roles VALUES (1, 2);
114 INSERT INTO user_roles VALUES (2, 1);
115 INSERT INTO user_roles VALUES (3, 1);
116
117Then load this into the C<myapp.db> database with the following command:
118
119 $ sqlite3 myapp.db < myapp02.sql
120
121
71dedf57 122=head2 Add User and Role Information to DBIC Schema
4d583dd8 123
64ccd8a8 124This step adds DBIC-based classes for the user-related database tables
71dedf57 125(the role information will not be used until Part 5):
4d583dd8 126
64ccd8a8 127Edit C<lib/MyAppDB.pm> and update the contents to match (only the
128C<MyAppDB =E<gt> [qw/Book BookAuthor Author User UserRole Role/]> line
129has changed):
4d583dd8 130
131 package MyAppDB;
132
133 =head1 NAME
134
135 MyAppDB -- DBIC Schema Class
136
137 =cut
138
139 # Our schema needs to inherit from 'DBIx::Class::Schema'
140 use base qw/DBIx::Class::Schema/;
141
142 # Need to load the DB Model classes here.
143 # You can use this syntax if you want:
144 # __PACKAGE__->load_classes(qw/Book BookAuthor Author User UserRole Role/);
145 # Also, if you simply want to load all of the classes in a directory
146 # of the same name as your schema class (as we do here) you can use:
147 # __PACKAGE__->load_classes(qw//);
148 # But the variation below is more flexible in that it can be used to
149 # load from multiple namespaces.
150 __PACKAGE__->load_classes({
151 MyAppDB => [qw/Book BookAuthor Author User UserRole Role/]
152 });
153
154 1;
155
156
157=head2 Create New "Result Source Objects"
158
159Create the following three files with the content shown below.
160
161C<lib/MyAppDB/User.pm>:
162
163 package MyAppDB::User;
164
165 use base qw/DBIx::Class/;
166
167 # Load required DBIC stuff
168 __PACKAGE__->load_components(qw/PK::Auto Core/);
169 # Set the table name
170 __PACKAGE__->table('users');
171 # Set columns in table
172 __PACKAGE__->add_columns(qw/id username password email_address first_name last_name/);
173 # Set the primary key for the table
174 __PACKAGE__->set_primary_key('id');
175
176 #
177 # Set relationships:
178 #
179
180 # has_many():
181 # args:
182 # 1) Name of relationship, DBIC will create accessor with this name
183 # 2) Name of the model class referenced by this relationship
184 # 3) Column name in *foreign* table
185 __PACKAGE__->has_many(map_user_role => 'MyAppDB::UserRole', 'user_id');
186
187
188 =head1 NAME
189
190 MyAppDB::User - A model object representing a person with access to the system.
191
192 =head1 DESCRIPTION
193
194 This is an object that represents a row in the 'users' table of your application
195 database. It uses DBIx::Class (aka, DBIC) to do ORM.
196
197 For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
198 Offline utilities may wish to use this class directly.
199
200 =cut
201
202 1;
203
204
205C<lib/MyAppDB/Role.pm>:
206
207 package MyAppDB::Role;
208
209 use base qw/DBIx::Class/;
210
211 # Load required DBIC stuff
212 __PACKAGE__->load_components(qw/PK::Auto Core/);
213 # Set the table name
214 __PACKAGE__->table('roles');
215 # Set columns in table
216 __PACKAGE__->add_columns(qw/id role/);
217 # Set the primary key for the table
218 __PACKAGE__->set_primary_key('id');
219
220 #
221 # Set relationships:
222 #
223
224 # has_many():
225 # args:
226 # 1) Name of relationship, DBIC will create accessor with this name
227 # 2) Name of the model class referenced by this relationship
228 # 3) Column name in *foreign* table
229 __PACKAGE__->has_many(map_user_role => 'MyAppDB::UserRole', 'role_id');
230
231
232 =head1 NAME
233
234 MyAppDB::Role - A model object representing a class of access permissions to
235 the system.
236
237 =head1 DESCRIPTION
238
239 This is an object that represents a row in the 'roles' table of your
240 application database. It uses DBIx::Class (aka, DBIC) to do ORM.
241
242 For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
243 "Offline" utilities may wish to use this class directly.
244
245 =cut
246
247 1;
248
249
250C<lib/MyAppDB/UserRole.pm>:
251
252 package MyAppDB::UserRole;
253
254 use base qw/DBIx::Class/;
255
256 # Load required DBIC stuff
257 __PACKAGE__->load_components(qw/PK::Auto Core/);
258 # Set the table name
259 __PACKAGE__->table('user_roles');
260 # Set columns in table
261 __PACKAGE__->add_columns(qw/user_id role_id/);
262 # Set the primary key for the table
263 __PACKAGE__->set_primary_key(qw/user_id role_id/);
264
265 #
266 # Set relationships:
267 #
268
269 # belongs_to():
270 # args:
271 # 1) Name of relationship, DBIC will create accessor with this name
272 # 2) Name of the model class referenced by this relationship
273 # 3) Column name in *this* table
274 __PACKAGE__->belongs_to(user => 'MyAppDB::User', 'user_id');
275
276 # belongs_to():
277 # args:
278 # 1) Name of relationship, DBIC will create accessor with this name
279 # 2) Name of the model class referenced by this relationship
280 # 3) Column name in *this* table
281 __PACKAGE__->belongs_to(role => 'MyAppDB::Role', 'role_id');
282
283
284 =head1 NAME
285
286 MyAppDB::UserRole - A model object representing the JOIN between Users and Roles.
287
288 =head1 DESCRIPTION
289
290 This is an object that represents a row in the 'user_roles' table of your application
291 database. It uses DBIx::Class (aka, DBIC) to do ORM.
292
293 You probably won't need to use this class directly -- it will be automatically
294 used by DBIC where joins are needed.
295
296 For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
297 Offline utilities may wish to use this class directly.
298
299 =cut
300
301 1;
302
303The code for these three result source classes is obviously very familiar to the C<Book>, C<Author>, and C<BookAuthor> classes created in Part 2.
304
305
306=head2 Sanity-Check Reload of Development Server
307
308We aren't ready to try out the authentication just yet; we only want to do a quick check to be sure our model loads correctly. Press C<Ctrl-C> to kill the previous server instance (if it's still running) and restart it:
309
310 $ script/myapp_server.pl
311
312Look for the three new model objects in the startup debug output:
313
314 ...
315 .-------------------------------------------------------------------+----------.
316 | Class | Type |
317 +-------------------------------------------------------------------+----------+
318 | MyApp::Controller::Books | instance |
319 | MyApp::Controller::Root | instance |
320 | MyApp::Model::MyAppDB | instance |
321 | MyApp::Model::MyAppDB::Author | class |
322 | MyApp::Model::MyAppDB::Book | class |
323 | MyApp::Model::MyAppDB::BookAuthor | class |
324 | MyApp::Model::MyAppDB::Role | class |
325 | MyApp::Model::MyAppDB::User | class |
326 | MyApp::Model::MyAppDB::UserRole | class |
327 | MyApp::View::TT | instance |
328 '-------------------------------------------------------------------+----------'
329 ...
330
331Again, notice that your "result source" classes have been "re-loaded" by Catalyst under C<MyApp::Model>.
332
333
334=head2 Include Authentication and Session Plugins
335
33aee7ed 336Edit C<lib/MyApp.pm> and update it as follows (everything below C<StackTrace> is new):
4d583dd8 337
338 use Catalyst qw/
339 -Debug
340 ConfigLoader
341 Static::Simple
342
4d583dd8 343 StackTrace
4d583dd8 344
345 Authentication
346 Authentication::Store::DBIC
347 Authentication::Credential::Password
348
349 Session
350 Session::Store::FastMmap
351 Session::State::Cookie
352 /;
353
64ccd8a8 354The three C<Authentication> plugins work together to support
355Authentication while the C<Session> plugins are required to maintain
356state across multiple HTTP requests. Note that there are several
a63e6e67 357options for L<Session::Store|Catalyst::Plugin::Session::Store>
358(L<Session::Store::FastMmap|Catalyst::Plugin::Session::Store::FastMmap>
64ccd8a8 359is generally a good choice if you are on Unix; try
360L<Cache::FileCache|Catalyst::Plugin::Cache::FileCache> if you are on
361Win32) -- consult L<Session::Store|Catalyst::Plugin::Session::Store> and
362its subclasses for additional information.
4d583dd8 363
a63e6e67 364
4d583dd8 365=head2 Configure Authentication
366
64ccd8a8 367Although C<__PACKAGE__-E<gt>config(name =E<gt> 'value');> is still
368supported, newer Catalyst applications tend to place all configuration
369information in C<myapp.yml> and automatically load this information into
a63e6e67 370C<MyApp-E<gt>config> using the
371L<ConfigLoader|Catalyst::Plugin::ConfigLoader> plugin. Here, we need
372to load several parameters that tell
373L<Catalyst::Plugin::Authentication|Catalyst::Plugin::Authentication>
374where to locate information in your database. To do this, edit the
375C<myapp.yml> YAML and update it to match:
4d583dd8 376
377 ---
378 name: MyApp
379 authentication:
380 dbic:
381 # Note this first definition would be the same as setting
382 # __PACKAGE__->config->{authentication}->{dbic}->{user_class} = 'MyAppDB::User'
383 # in lib/MyApp.pm (IOW, each hash key becomes a "name:" in the YAML file).
384 #
385 # This is the model object created by Catalyst::Model::DBIC from your
386 # schema (you created 'MyAppDB::User' but as the Catalyst startup
387 # debug messages show, it was loaded as 'MyApp::Model::MyAppDB::User').
a63e6e67 388 # NOTE: Omit 'MyApp::Model' to avoid a component lookup issue in Catalyst 5.66
4d583dd8 389 user_class: MyAppDB::User
390 # This is the name of the field in your 'users' table that contains the user's name
391 user_field: username
392 # This is the name of the field in your 'users' table that contains the password
393 password_field: password
394 # Other options can go here for hashed passwords
395
396Inline comments in the code above explain how each field is being used.
397
64ccd8a8 398B<TIP>: Although YAML uses a very simple and easy-to-ready format, it
399does require the use of a consistent level of indenting. Be sure you
400line up everything on a given 'level' with the same number of indents.
401Also, be sure not to use C<tab> characters (YAML does not support them
402because they are handled inconsistently across editors).
4d583dd8 403
a63e6e67 404
4d583dd8 405=head2 Add Login and Logout Controllers
406
407Use the Catalyst create script to create two stub controller files:
408
409 $ script/myapp_create.pl controller Login
410 $ script/myapp_create.pl controller Logout
411
64ccd8a8 412B<NOTE>: You could easily use a single controller here. For example,
413you could have a C<User> controller with both C<login> and C<logout>
414actions. Remember, Catalyst is designed to be very flexible, and leaves
415such matters up to you, the designer and programmer.
4d583dd8 416
417Then open C<lib/MyApp/Controller/Login.pm> and add:
418
7e5eb02c 419 =head2 base
4d583dd8 420
421 Login logic
422
423 =cut
424
7e5eb02c 425 sub base :Path :Args(0) {
4d583dd8 426 my ($self, $c) = @_;
427
428 # Get the username and password from form
429 my $username = $c->request->params->{username} || "";
430 my $password = $c->request->params->{password} || "";
431
432 # If the username and password values were found in form
433 if ($username && $password) {
434 # Attempt to log the user in
435 if ($c->login($username, $password)) {
436 # If successful, then let them use the application
437 $c->response->redirect($c->uri_for('/books/list'));
438 return;
439 } else {
440 # Set an error message
441 $c->stash->{error_msg} = "Bad username or password.";
442 }
443 }
444
445 # If either of above don't work out, send to the login page
446 $c->stash->{template} = 'login.tt2';
447 }
448
64ccd8a8 449This controller fetches the C<username> and C<password> values from the
450login form and attempts to perform a login. If successful, it redirects
451the user to the book list page. If the login fails, the user will stay
452at the login page but receive an error message. If the C<username> and
453C<password> values are not present in the form, the user will be taken
454to the empty login form.
4d583dd8 455
7e5eb02c 456We are using C<sub base :Path :Args(0) {...}> here to specifically match
457the URL C</login>. C<Path> actions (aka, "literal actions") create URI
458matches relative to the namespace of the controller where they are defined.
459Although C<Path> supports arguments that allow relative and absolute paths
460to be defined, here we use an empty C<Path> definition to match on just the
461name of the controller itself. The method name, C<base>, is arbitrary.
462We make the match even more specific with the C<:Args(0)> action modifier
463-- this forces the match on I<only> C</login>, not C</login/somethingelse>.
464
465Note that we could have used something like C<sub default :Private>;
466however, the use of C<default> actions is discouraged because it does
467not receive path args as with other actions. The recommended practice
468is to only use C<default> in C<MyApp::Controller::Root>.
469
4d583dd8 470Next, create a corresponding method in C<lib/MyApp/Controller/Logout.pm>:
471
7e5eb02c 472 =head2 base
4d583dd8 473
474 Logout logic
475
476 =cut
477
7e5eb02c 478 sub base :Path :Args(0) {
4d583dd8 479 my ($self, $c) = @_;
480
481 # Clear the user's state
482 $c->logout;
483
71dedf57 484 # Send the user to the starting point
4d583dd8 485 $c->response->redirect($c->uri_for('/'));
486 }
487
7e5eb02c 488Note that we are using the same C<sub base :Path :Args(0) {...}> style
489of action as with the login logic.
490
4d583dd8 491
492=head2 Add a Login Form TT Template Page
493
494Create a login form by opening C<root/src/login.tt2> and inserting:
495
496 [% META title = 'Login' %]
497
498 <!-- Login form -->
499 <form method="post" action=" [% Catalyst.uri_for('/login') %] ">
500 <table>
501 <tr>
502 <td>Username:</td>
503 <td><input type="text" name="username" size="40" /></td>
504 </tr>
505 <tr>
506 <td>Password:</td>
507 <td><input type="password" name="password" size="40" /></td>
508 </tr>
509 <tr>
510 <td colspan="2"><input type="submit" name="submit" value="Submit" /></td>
511 </tr>
512 </table>
513 </form>
514
515
516=head2 Add Valid User Check
517
64ccd8a8 518We need something that provides enforcement for the authentication
519mechanism -- a I<global> mechanism that prevents users who have not
520passed authentication from reaching any pages except the login page.
521This is generally done via an C<auto> action/method (prior to Catalyst
522v5.66, this sort of thing would go in C<MyApp.pm>, but starting in
523v5.66, the preferred location is C<lib/MyApp/Controller/Root.pm>).
4d583dd8 524
71dedf57 525Edit the existing C<lib/MyApp/Controller/Root.pm> class file and insert
526the following method:
4d583dd8 527
528 =head2 auto
529
530 Check if there is a user and, if not, forward to login page
531
532 =cut
533
534 # Note that 'auto' runs after 'begin' but before your actions and that
535 # 'auto' "chain" (all from application path to most specific class are run)
536 sub auto : Private {
537 my ($self, $c) = @_;
538
539 # Allow unauthenticated users to reach the login page
540 if ($c->request->path =~ /login/) {
541 return 1;
542 }
543
544 # If a user doesn't exist, force login
545 if (!$c->user_exists) {
546 # Dump a log message to the development server debug output
547 $c->log->debug('***Root::auto User not found, forwarding to /login');
548 # Redirect the user to the login page
549 $c->response->redirect($c->uri_for('/login'));
550 # Return 0 to cancel 'post-auto' processing and prevent use of application
551 return 0;
552 }
553
554 # User found, so return 1 to continue with processing after this 'auto'
555 return 1;
556 }
557
64ccd8a8 558B<Note:> Catalyst provides a number of different types of actions, such
559as C<Local>, C<Regex>, and C<Private>. You should refer to
71dedf57 560L<Catalyst::Manual::Intro> for a more detailed explanation, but the
561following bullet points provide a quick introduction:
4d583dd8 562
563=over 4
564
565=item *
566
64ccd8a8 567The majority of application use C<Local> actions for items that respond
568to user requests and C<Private> actions for those that do not directly
569respond to user input.
4d583dd8 570
571=item *
572
64ccd8a8 573There are five types of C<Private> actions: C<begin>, C<end>,
574C<default>, C<index>, and C<auto>.
4d583dd8 575
576=item *
577
a63e6e67 578Unlike the other actions where only a single method is called for each
579request, I<every> auto action along the chain of namespaces will be
580called.
4d583dd8 581
582=back
583
64ccd8a8 584By placing the authentication enforcement code inside the C<auto> method
585of C<lib/MyApp/Controller/Root.pm> (or C<lib/MyApp.pm>), it will be
586called for I<every> request that is received by the entire application.
4d583dd8 587
a63e6e67 588
4d583dd8 589=head2 Displaying Content Only to Authenticated Users
590
64ccd8a8 591Let's say you want to provide some information on the login page that
592changes depending on whether the user has authenticated yet. To do
593this, open C<root/src/login.tt2> in your editor and add the following
594lines to the bottom of the file:
4d583dd8 595
596 <p>
597 [%
598 # This code illustrates how certain parts of the TT
599 # template will only be shown to users who have logged in
600 %]
601 [% IF Catalyst.user %]
602 Please Note: You are already logged in as '[% Catalyst.user.username %]'.
603 You can <a href="[% Catalyst.uri_for('/logout') %]">logout</a> here.
604 [% ELSE %]
605 You need to log in to use this application.
606 [% END %]
607 [%#
608 Note that this whole block is a comment because the "#" appears
609 immediate after the "[%" (with no spaces in between). Although it
610 can be a handy way to temporarily "comment out" a whole block of
611 TT code, it's probably a little too subtle for use in "normal"
612 comments.
613 %]
614
64ccd8a8 615Although most of the code is comments, the middle few lines provide a
616"you are already logged in" reminder if the user returns to the login
617page after they have already authenticated. For users who have not yet
618authenticated, a "You need to log in..." message is displayed (note the
619use of an IF-THEN-ELSE construct in TT).
4d583dd8 620
621
622=head2 Try Out Authentication
623
64ccd8a8 624Press C<Ctrl-C> to kill the previous server instance (if it's still
625running) and restart it:
4d583dd8 626
627 $ script/myapp_server.pl
628
64ccd8a8 629B<IMPORTANT NOTE>: If you happen to be using Internet Explorer, you may
630need to use the command C<script/myapp_server.pl -k> to enable the
631keepalive feature in the development server. Otherwise, the HTTP
632redirect on successful login may not work correctly with IE (it seems to
633work without -k if you are running the web browser and development
634server on the same machine). If you are using browser a browser other
635than IE, it should work either way. If you want to make keepalive the
636default, you can edit C<script/myapp_server.pl> and change the
637initialization value for C<$keepalive> to C<1>. (You will need to do
638this every time you create a new Catalyst application or rebuild the
639C<myapp_server.pl> script.)
640
641Now trying going to L<http://localhost:3000/books/list> and you should
642be redirected to the login page, hitting Shift+Reload if necessary (the
643"You are already logged in" message should I<not> appear -- if it does,
71dedf57 644click the C<logout> button and try again). Note the C<***Root::auto User
645not found...> debug message in the development server output. Enter
646username C<test01> and password C<mypass>, and you should be taken to
647the Book List page.
4d583dd8 648
71dedf57 649Open C<root/src/books/list.tt2> and add the following lines to the
650bottom:
4d583dd8 651
652 <p>
653 <a href="[% Catalyst.uri_for('/login') %]">Login</a>
654 <a href="[% Catalyst.uri_for('form_create') %]">Create</a>
655 </p>
656
a63e6e67 657Reload your browser and you should now see a "Login" and "Create" links
658at the bottom of the page (as mentioned earlier, you can update
659template files without reloading the development server). Click this
660link to return to the login page. This time you I<should> see the
661"You are already logged in" message.
4d583dd8 662
64ccd8a8 663Finally, click the C<You can logout here> link on the C</login> page.
664You should stay at the login page, but the message should change to "You
665need to log in to use this application."
4d583dd8 666
667
4d583dd8 668=head1 USING PASSWORD HASHES
669
64ccd8a8 670In this section we increase the security of our system by converting
671from cleartext passwords to SHA-1 password hashes.
4d583dd8 672
64ccd8a8 673B<Note:> This section is optional. You can skip it and the rest of the
674tutorial will function normally.
4d583dd8 675
64ccd8a8 676Note that even with the techniques shown in this section, the browser
677still transmits the passwords in cleartext to your application. We are
678just avoiding the I<storage> of cleartext passwords in the database by
71dedf57 679using a SHA-1 hash. If you are concerned about cleartext passwords
680between the browser and your application, consider using SSL/TLS, made
a63e6e67 681easy with the Catalyst plugin
682L<Catalyst::Plugin:RequireSSL|Catalyst::Plugin:RequireSSL>.
683
4d583dd8 684
685=head2 Get a SHA-1 Hash for the Password
686
64ccd8a8 687Catalyst uses the C<Digest> module to support a variety of hashing
688algorithms. Here we will use SHA-1 (SHA = Secure Hash Algorithm).
689First, we should compute the SHA-1 hash for the "mypass" password we are
690using. The following command-line Perl script provides a "quick and
691dirty" way to do this:
4d583dd8 692
693 $ perl -MDigest::SHA -e 'print Digest::SHA::sha1_hex("mypass"), "\n"'
694 e727d1464ae12436e899a726da5b2f11d8381b26
695 $
696
cc548726 697B<Note:> You should probably modify this code for production use to
698not read the password from the command line. By having the script
699prompt for the cleartext password, it avoids having the password linger
700in forms such as your C<.bash_history> files (assuming you are using
701BASH as your shell). An example of such a script can be found in
702Appendix 3.
703
a63e6e67 704
4d583dd8 705=head2 Switch to SHA-1 Password Hashes in the Database
706
64ccd8a8 707Next, we need to change the C<password> column of our C<users> table to
708store this hash value vs. the existing cleartext password. Open
709C<myapp03.sql> in your editor and enter:
4d583dd8 710
711 --
712 -- Convert passwords to SHA-1 hashes
713 --
714 UPDATE users SET password = 'e727d1464ae12436e899a726da5b2f11d8381b26' WHERE id = 1;
715 UPDATE users SET password = 'e727d1464ae12436e899a726da5b2f11d8381b26' WHERE id = 2;
716 UPDATE users SET password = 'e727d1464ae12436e899a726da5b2f11d8381b26' WHERE id = 3;
717
718Then use the following command to update the SQLite database:
719
720 $ sqlite3 myapp.db < myapp03.sql
721
64ccd8a8 722B<Note:> We are using SHA-1 hashes here, but many other hashing
723algorithms are supported. See C<Digest> for more information.
4d583dd8 724
a63e6e67 725
64ccd8a8 726=head2 Enable SHA-1 Hash Passwords in
727C<Catalyst::Plugin::Authentication::Store::DBIC>
4d583dd8 728
64ccd8a8 729Edit C<myapp.yml> and update it to match (the C<password_type> and
730C<password_hash_type> are new, everything else is the same):
4d583dd8 731
732 ---
733 name: MyApp
734 authentication:
735 dbic:
736 # Note this first definition would be the same as setting
737 # __PACKAGE__->config->{authentication}->{dbic}->{user_class} = 'MyAppDB::User'
738 # in lib/MyApp.pm (IOW, each hash key becomes a "name:" in the YAML file).
739 #
740 # This is the model object created by Catalyst::Model::DBIC from your
741 # schema (you created 'MyAppDB::User' but as the Catalyst startup
742 # debug messages show, it was loaded as 'MyApp::Model::MyAppDB::User').
a63e6e67 743 # NOTE: Omit 'MyApp::Model' to avoid a component lookup issue in Catalyst 5.66
4d583dd8 744 user_class: MyAppDB::User
745 # This is the name of the field in your 'users' table that contains the user's name
746 user_field: username
747 # This is the name of the field in your 'users' table that contains the password
748 password_field: password
749 # Other options can go here for hashed passwords
750 # Enabled hashed passwords
751 password_type: hashed
752 # Use the SHA-1 hashing algorithm
753 password_hash_type: SHA-1
754
755
756=head2 Try Out the Hashed Passwords
757
64ccd8a8 758Press C<Ctrl-C> to kill the previous server instance (if it's still
759running) and restart it:
4d583dd8 760
761 $ script/myapp_server.pl
762
64ccd8a8 763You should now be able to go to L<http://localhost:3000/books/list> and
764login as before. When done, click the "Logout" link on the login page
765(or point your browser at L<http://localhost:3000/logout>).
4d583dd8 766
a63e6e67 767
4d583dd8 768=head1 AUTHOR
769
770Kennedy Clark, C<hkclark@gmail.com>
771
eed93301 772Please report any errors, issues or suggestions to the author. The
773most recent version of the Catlayst Tutorial can be found at
774L<http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Runtime/lib/Catalyst/Manual/Tutorial/>.
4d583dd8 775
a63e6e67 776Copyright 2006, Kennedy Clark, under Creative Commons License
777(L<http://creativecommons.org/licenses/by-nc-sa/2.5/>).