1Catalyst::Manual::TutorUisaelr::C0o6n_tArCuiatbthuaotlreyidsztaP:te:irMolann(Du3oa)clu:m:eTnuttaotriioanl::06_Authorization(3)
2
3
4

NAME

6       Catalyst::Manual::Tutorial::06_Authorization - Catalyst Tutorial -
7       Chapter 6: Authorization
8

OVERVIEW

10       This is Chapter 6 of 10 for the Catalyst tutorial.
11
12       Tutorial Overview
13
14       1.  Introduction
15
16       2.  Catalyst Basics
17
18       3.  More Catalyst Basics
19
20       4.  Basic CRUD
21
22       5.  Authentication
23
24       6.  06_Authorization
25
26       7.  Debugging
27
28       8.  Testing
29
30       9.  Advanced CRUD
31
32       10. Appendices
33

DESCRIPTION

35       This chapter of the tutorial adds role-based authorization to the
36       existing authentication implemented in Chapter 5.  It provides simple
37       examples of how to use roles in both TT templates and controller
38       actions.  The first half looks at basic authorization concepts. The
39       second half looks at how moving your authorization code to your model
40       can simplify your code and make things easier to maintain.
41
42       Source code for the tutorial in included in the /home/catalyst/Final
43       directory of the Tutorial Virtual machine (one subdirectory per
44       chapter).  There are also instructions for downloading the code in
45       Catalyst::Manual::Tutorial::01_Intro.
46

BASIC AUTHORIZATION

48       In this section you learn the basics of how authorization works under
49       Catalyst.
50
51   Update Plugins to Include Support for Authorization
52       Edit "lib/MyApp.pm" and add "Authorization::Roles" to the list:
53
54           # Load plugins
55           use Catalyst qw/
56               -Debug
57               ConfigLoader
58               Static::Simple
59
60               StackTrace
61
62               Authentication
63               Authorization::Roles
64
65               Session
66               Session::Store::File
67               Session::State::Cookie
68
69               StatusMessage
70           /;
71
72       Once again, include this additional plugin as a new dependency in the
73       Makefile.PL file like this:
74
75           requires 'Catalyst::Plugin::Authorization::Roles';
76
77   Add Role-Specific Logic to the "Book List" Template
78       Open "root/src/books/list.tt2" in your editor and add the following
79       lines to the bottom of the file:
80
81           ...
82           <p>Hello [% c.user.username %], you have the following roles:</p>
83
84           <ul>
85             [% # Dump list of roles -%]
86             [% FOR role = c.user.roles %]<li>[% role %]</li>[% END %]
87           </ul>
88
89           <p>
90           [% # Add some simple role-specific logic to template %]
91           [% # Use $c->check_user_roles() to check authz -%]
92           [% IF c.check_user_roles('user') %]
93             [% # Give normal users a link for 'logout' %]
94             <a href="[% c.uri_for('/logout') %]">User Logout</a>
95           [% END %]
96
97           [% # Can also use $c->user->check_roles() to check authz -%]
98           [% IF c.check_user_roles('admin') %]
99             [% # Give admin users a link for 'create' %]
100             <a href="[% c.uri_for(c.controller.action_for('form_create')) %]">Admin Create</a>
101           [% END %]
102           </p>
103
104       This code displays a different combination of links depending on the
105       roles assigned to the user.
106
107   Limit Books::add to 'admin' Users
108       "IF" statements in TT templates simply control the output that is sent
109       to the user's browser; it provides no real enforcement (if users know
110       or guess the appropriate URLs, they are still perfectly free to hit any
111       action within your application).  We need to enhance the controller
112       logic to wrap restricted actions with role-validation logic.
113
114       For example, we might want to restrict the "formless create" action to
115       admin-level users by editing "lib/MyApp/Controller/Books.pm" and
116       updating "url_create" to match the following code:
117
118           =head2 url_create
119
120           Create a book with the supplied title and rating,
121           with manual authorization
122
123           =cut
124
125           sub url_create :Chained('base') :PathPart('url_create') :Args(3) {
126               # In addition to self & context, get the title, rating & author_id args
127               # from the URL.  Note that Catalyst automatically puts extra information
128               # after the "/<controller_name>/<action_name/" into @_
129               my ($self, $c, $title, $rating, $author_id) = @_;
130
131               # Check the user's roles
132               if ($c->check_user_roles('admin')) {
133                   # Call create() on the book model object. Pass the table
134                   # columns/field values we want to set as hash values
135                   my $book = $c->model('DB::Book')->create({
136                           title   => $title,
137                           rating  => $rating
138                       });
139
140                   # Add a record to the join table for this book, mapping to
141                   # appropriate author
142                   $book->add_to_book_authors({author_id => $author_id});
143                   # Note: Above is a shortcut for this:
144                   # $book->create_related('book_authors', {author_id => $author_id});
145
146                   # Assign the Book object to the stash and set template
147                   $c->stash(book     => $book,
148                             template => 'books/create_done.tt2');
149               } else {
150                   # Provide very simple feedback to the user.
151                   $c->response->body('Unauthorized!');
152               }
153           }
154
155       To add authorization, we simply wrap the main code of this method in an
156       "if" statement that calls "check_user_roles".  If the user does not
157       have the appropriate permissions, they receive an "Unauthorized!"
158       message.  Note that we intentionally chose to display the message this
159       way to demonstrate that TT templates will not be used if the response
160       body has already been set.  In reality you would probably want to use a
161       technique that maintains the visual continuity of your template layout
162       (for example, using Catalyst::Plugin::StatusMessage as shown in the
163       last chapter to redirect to an "unauthorized" page).
164
165       TIP: If you want to keep your existing "url_create" method, you can
166       create a new copy and comment out the original by making it look like a
167       Pod comment.  For example, put something like "=begin" before "sub add
168       : Local {" and "=end" after the closing "}".
169
170   Try Out Authentication And Authorization
171       Make sure the development server is running:
172
173           $ script/myapp_server.pl -r
174
175       Now trying going to <http://localhost:3000/books/list> and you should
176       be taken to the login page (you might have to "Shift+Reload" or
177       "Ctrl+Reload" your browser and/or click the "User Logout" link on the
178       book list page).  Try logging in with both "test01" and "test02" (both
179       use a password of "mypass") and notice how the roles information
180       updates at the bottom of the "Book List" page. Also try the "User
181       Logout" link on the book list page.
182
183       Now the "url_create" URL will work if you are already logged in as user
184       "test01", but receive an authorization failure if you are logged in as
185       "test02".  Try:
186
187           http://localhost:3000/books/url_create/test/1/6
188
189       while logged in as each user.  Use one of the "logout" links (or go to
190       <http://localhost:3000/logout> in your browser directly) when you are
191       done.
192

ENABLE MODEL-BASED AUTHORIZATION

194       Hopefully it's fairly obvious that adding detailed permission checking
195       logic to our controllers and view templates isn't a very clean or
196       scalable way to build role-based permissions into out application.  As
197       with many other aspects of MVC web development, the goal is to have
198       your controllers and views be an "thin" as possible, with all of the
199       "fancy business logic" built into your model.
200
201       For example, let's add a method to our "Books.pm" Result Class to check
202       if a user is allowed to delete a book.  Open
203       "lib/MyApp/Schema/Result/Book.pm" and add the following method (be sure
204       to add it below the ""DO NOT MODIFY ..."" line):
205
206           =head2 delete_allowed_by
207
208           Can the specified user delete the current book?
209
210           =cut
211
212           sub delete_allowed_by {
213               my ($self, $user) = @_;
214
215               # Only allow delete if user has 'admin' role
216               return $user->has_role('admin');
217           }
218
219       Here we call a "has_role" method on our user object, so we should add
220       this method to our Result Class.  Open
221       "lib/MyApp/Schema/Result/User.pm" and add the following method below
222       the ""DO NOT MODIFY ..."" line:
223
224           =head2 has_role
225
226           Check if a user has the specified role
227
228           =cut
229
230           use Perl6::Junction qw/any/;
231           sub has_role {
232               my ($self, $role) = @_;
233
234               # Does this user posses the required role?
235               return any(map { $_->role } $self->roles) eq $role;
236           }
237
238       Let's also add Perl6::Junction to the requirements listed in
239       Makefile.PL:
240
241           requires 'Perl6::Junction';
242
243       Note: Feel free to use "grep" in lieu of Perl6::Junction::any if you
244       prefer.  Also, please don't let the use of the Perl6::Junction module
245       above lead you to believe that Catalyst is somehow dependent on Perl
246       6... we are simply using that module for its easy-to-read
247       <http://blogs.perl.org/users/marc_sebastian_jakobs/2009/11/my-favorite-
248       module-of-the-month-perl6junction.html> "any" function.
249
250       Now we need to add some enforcement inside our controller.  Open
251       "lib/MyApp/Controller/Books.pm" and update the "delete" method to match
252       the following code:
253
254           =head2 delete
255
256           Delete a book
257
258           =cut
259
260           sub delete :Chained('object') :PathPart('delete') :Args(0) {
261               my ($self, $c) = @_;
262
263               # Check permissions
264               $c->detach('/error_noperms')
265                   unless $c->stash->{object}->delete_allowed_by($c->user->get_object);
266
267               # Saved the PK id for status_msg below
268               my $id = $c->stash->{object}->id;
269
270               # Use the book object saved by 'object' and delete it along
271               # with related 'book_authors' entries
272               $c->stash->{object}->delete;
273
274               # Redirect the user back to the list page
275               $c->response->redirect($c->uri_for($self->action_for('list'),
276                   {mid => $c->set_status_msg("Deleted book $id")}));
277           }
278
279       Here, we "detach" to an error page if the user is lacking the
280       appropriate permissions.  For this to work, we need to make
281       arrangements for the '/error_noperms' action to work.  Open
282       "lib/MyApp/Controller/Root.pm" and add this method:
283
284           =head2 error_noperms
285
286           Permissions error screen
287
288           =cut
289
290           sub error_noperms :Chained('/') :PathPart('error_noperms') :Args(0) {
291               my ($self, $c) = @_;
292
293               $c->stash(template => 'error_noperms.tt2');
294           }
295
296       And also add the template file by putting the following text into
297       "root/src/error_noperms.tt2":
298
299           <span class="error">Permission Denied</span>
300
301       Log in as "test01" and create several new books using the "url_create"
302       feature:
303
304           http://localhost:3000/books/url_create/Test/1/4
305
306       Then, while still logged in as "test01", click the "Delete" link next
307       to one of these books.  The book should be removed and you should see
308       the usual green "Book deleted" message.  Next, click the "User Logout"
309       link and log back in as "test02".  Now try deleting one of the books.
310       You should be taken to the red "Permission Denied" message on our error
311       page.
312
313       Use one of the 'Logout' links (or go to the
314       <http://localhost:3000/logout> URL directly) when you are done.
315
316       You can jump to the next chapter of the tutorial here: Debugging
317

AUTHOR

319       Kennedy Clark, "hkclark@gmail.com"
320
321       Feel free to contact the author for any errors or suggestions, but the
322       best way to report issues is via the CPAN RT Bug system at
323       <https://rt.cpan.org/Public/Dist/Display.html?Name=Catalyst-Manual>.
324
325       Copyright 2006-2011, Kennedy Clark, under the Creative Commons
326       Attribution Share-Alike License Version 3.0
327       (<https://creativecommons.org/licenses/by-sa/3.0/us/>).
328
329
330
331perl v5.30.1                   Cat2a0l2y0s-t0:1:-M2a9nual::Tutorial::06_Authorization(3)
Impressum