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