| 1 |
package Dancer2::Manual::Tutorial; |
| 2 |
# ABSTRACT: A step-by-step guide to get you dancing |
| 3 |
|
| 4 |
__END__ |
| 5 |
|
| 6 |
=pod |
| 7 |
|
| 8 |
=encoding UTF-8 |
| 9 |
|
| 10 |
=head1 NAME |
| 11 |
|
| 12 |
Dancer2::Manual::Tutorial - A step-by-step guide to get you dancing |
| 13 |
|
| 14 |
=head1 VERSION |
| 15 |
|
| 16 |
version 2.2.2 |
| 17 |
|
| 18 |
=head1 Dancer2 Tutorial |
| 19 |
|
| 20 |
In this tutorial, you're going to end up with a working blog application, |
| 21 |
constructed from simple examples and demonstrations of techniques used |
| 22 |
in Dancer2 applications. |
| 23 |
|
| 24 |
If you'd like to see the finished product, you can clone the git repository |
| 25 |
containing the code used in this tutorial: |
| 26 |
|
| 27 |
git clone https://github.com/PerlDancer/DLBlog.git |
| 28 |
|
| 29 |
=head1 Introduction - the Danceyland Blog |
| 30 |
|
| 31 |
Danceyland wants to share information about happenings at the park on |
| 32 |
an ongoing basis, and feel the best medium for doing so is by publishing |
| 33 |
a blog. Your task is to construct a blog engine to facilitate this using |
| 34 |
Dancer2 and other Perl modules. |
| 35 |
|
| 36 |
=head2 What You'll Learn |
| 37 |
|
| 38 |
By the end of this tutorial, you'll know how to: |
| 39 |
|
| 40 |
=over |
| 41 |
|
| 42 |
=item * Scaffold a new Dancer2 app |
| 43 |
|
| 44 |
=item * Design and construct routes for an application |
| 45 |
|
| 46 |
=item * Work with sessions, templates, and databases |
| 47 |
|
| 48 |
=item * Extend your Dancer2 applications with plugins |
| 49 |
|
| 50 |
=item * Add authentication to Dancer2 applications |
| 51 |
|
| 52 |
=item * Perform a basic app deployment |
| 53 |
|
| 54 |
=back |
| 55 |
|
| 56 |
=head2 Prerequisites |
| 57 |
|
| 58 |
=over |
| 59 |
|
| 60 |
=item * Linux, BSD, or Windows with WSL and a Linux distribution installed |
| 61 |
|
| 62 |
(Strawberry Perl on Windows may work, but is not guaranteed) |
| 63 |
|
| 64 |
=item * SQLite 3, installed via your operating system's package manager |
| 65 |
|
| 66 |
=back |
| 67 |
|
| 68 |
=head1 Setting Up Your Environment |
| 69 |
|
| 70 |
=head2 Installing Dancer2 |
| 71 |
|
| 72 |
cpan Dancer2 |
| 73 |
|
| 74 |
or |
| 75 |
|
| 76 |
cpanm Dancer2 |
| 77 |
|
| 78 |
=head2 Creating Your First App |
| 79 |
|
| 80 |
dancer2 gen -a DLBlog |
| 81 |
|
| 82 |
Output: |
| 83 |
|
| 84 |
+ DLBlog |
| 85 |
+ DLBlog/.dancer |
| 86 |
+ DLBlog/config.yml |
| 87 |
+ DLBlog/cpanfile |
| 88 |
+ DLBlog/Makefile.PL |
| 89 |
+ DLBlog/MANIFEST.SKIP |
| 90 |
+ DLBlog/t |
| 91 |
+ DLBlog/t/002_index_route.t |
| 92 |
+ DLBlog/t/001_base.t |
| 93 |
+ DLBlog/environments |
| 94 |
+ DLBlog/environments/production.yml |
| 95 |
+ DLBlog/environments/development.yml |
| 96 |
+ DLBlog/bin |
| 97 |
+ DLBlog/bin/app.psgi |
| 98 |
+ DLBlog/views |
| 99 |
+ DLBlog/views/index.tt |
| 100 |
+ DLBlog/public |
| 101 |
+ DLBlog/public/dispatch.cgi |
| 102 |
+ DLBlog/public/404.html |
| 103 |
+ DLBlog/public/favicon.ico |
| 104 |
+ DLBlog/public/500.html |
| 105 |
+ DLBlog/public/dispatch.fcgi |
| 106 |
+ DLBlog/lib |
| 107 |
+ DLBlog/lib/DLBlog.pm |
| 108 |
+ DLBlog/views/layouts |
| 109 |
+ DLBlog/views/layouts/main.tt |
| 110 |
+ DLBlog/public/images |
| 111 |
+ DLBlog/public/images/perldancer.jpg |
| 112 |
+ DLBlog/public/images/perldancer-bg.jpg |
| 113 |
+ DLBlog/public/javascripts |
| 114 |
+ DLBlog/public/javascripts/jquery.js |
| 115 |
+ DLBlog/public/css |
| 116 |
+ DLBlog/public/css/style.css |
| 117 |
+ DLBlog/public/css/error.css |
| 118 |
|
| 119 |
Your new application is ready! To run it: |
| 120 |
|
| 121 |
cd DLBlog |
| 122 |
plackup bin/app.psgi |
| 123 |
|
| 124 |
To access your application, point your browser to http://localhost:5000 |
| 125 |
|
| 126 |
If you need community assistance, the following resources are available: |
| 127 |
- Dancer website: https://perldancer.org |
| 128 |
- Twitter: https://twitter.com/PerlDancer/ |
| 129 |
- GitHub: https://github.com/PerlDancer/Dancer2/ |
| 130 |
- Mailing list: https://lists.perldancer.org/mailman/listinfo/dancer-users |
| 131 |
- IRC: irc.perl.org#dancer |
| 132 |
|
| 133 |
Happy Dancing! |
| 134 |
|
| 135 |
Make sure to change to your new project directory to begin work: |
| 136 |
|
| 137 |
cd DLBlog |
| 138 |
|
| 139 |
=head2 Understanding Directory Structure |
| 140 |
|
| 141 |
Your application directory now contains several subdirectories: |
| 142 |
|
| 143 |
=over |
| 144 |
|
| 145 |
=item bin |
| 146 |
|
| 147 |
Contains the PSGI file that starts your application. Can be used for |
| 148 |
other utilities and scripts for your application. |
| 149 |
|
| 150 |
=item environments |
| 151 |
|
| 152 |
Configuration information. One file per environment (such as C<development> |
| 153 |
and C<production>). |
| 154 |
|
| 155 |
=item lib |
| 156 |
|
| 157 |
Your core application code. This is where you'll put your models, |
| 158 |
controllers, and other code. |
| 159 |
|
| 160 |
=item public |
| 161 |
|
| 162 |
Contains static files such as images, CSS, and JavaScript. Also contains |
| 163 |
instance scripts for CGI and FastCGI. |
| 164 |
|
| 165 |
=item t |
| 166 |
|
| 167 |
Tests for your application. |
| 168 |
|
| 169 |
=item views |
| 170 |
|
| 171 |
Contains templates and layouts. |
| 172 |
|
| 173 |
=back |
| 174 |
|
| 175 |
=head2 Using Plackup for Development |
| 176 |
|
| 177 |
plackup -r bin/app.psgi |
| 178 |
|
| 179 |
This autorestarts your application when changes are made to your code. |
| 180 |
This is ideal during development, but should not be used in a production |
| 181 |
setting. |
| 182 |
|
| 183 |
=head1 Configuring Our Application |
| 184 |
|
| 185 |
By default, new Dancer2 applications use L<Dancer2::Template::Tiny>. |
| 186 |
While this works well for some types of apps, it's not well suited to |
| 187 |
applications like the Danceyland Blog. Instead, we'll configure this |
| 188 |
application to use L<Template::Toolkit>, a mainstay of Perl templating. |
| 189 |
|
| 190 |
To enable Template Toolkit, you'll need to edit your F<config.yml>: |
| 191 |
|
| 192 |
# template engine |
| 193 |
# tiny: default basic template engine |
| 194 |
# template_toolkit: TT |
| 195 |
|
| 196 |
#template: "tiny" |
| 197 |
|
| 198 |
template: "template_toolkit" |
| 199 |
engines: |
| 200 |
template: |
| 201 |
template_toolkit: |
| 202 |
# Note: start_tag and end_tag are regexes |
| 203 |
start_tag: '<%' |
| 204 |
end_tag: '%>' |
| 205 |
|
| 206 |
YAML files, such as your application config, support the same comment |
| 207 |
characters as Perl. L<Dancer2::Template::Tiny> is disabled by commenting |
| 208 |
that line in your config file, and the default TT config is used by |
| 209 |
uncommenting the C<template> and C<engines> configuration. |
| 210 |
|
| 211 |
This tells Dancer2 to: |
| 212 |
|
| 213 |
=over |
| 214 |
|
| 215 |
=item Load the Template Toolkit template engine |
| 216 |
|
| 217 |
=item Specify Template Toolkit as the template engine to use |
| 218 |
|
| 219 |
=item Passes configuration to the TT engine (C<start_tag, end_tag>) |
| 220 |
|
| 221 |
=back |
| 222 |
|
| 223 |
We'll visit this file regularly throughout the tutorial. |
| 224 |
|
| 225 |
F<config.yml> is the right place to set configuration common to all |
| 226 |
environments (dev, production, etc.), such as the template engine to use. |
| 227 |
Later, we'll see how to use different configuration parameters in |
| 228 |
different environments. |
| 229 |
|
| 230 |
=head1 CRUD Routes |
| 231 |
|
| 232 |
CRUD is an acronym for Create, Read, Update, and Delete. These are the |
| 233 |
basic operations for any database-driven application, such as the |
| 234 |
Danceyland Blog. |
| 235 |
|
| 236 |
=head2 What Routes are Needed? |
| 237 |
|
| 238 |
Blogs contain one or more entries, which we need to be able to Create, |
| 239 |
Read, Update, and Delete. We'll need the following routes: |
| 240 |
|
| 241 |
=over |
| 242 |
|
| 243 |
=item * |
| 244 |
|
| 245 |
Create a blog entry. This corresponds to the HTTP C<POST> method. It also |
| 246 |
requires a form to input the data, which is displayed using the HTTP C<GET> |
| 247 |
method. |
| 248 |
|
| 249 |
=item * |
| 250 |
|
| 251 |
Read (i.e., display) a blog entry. This corresponds to the HTTP C<GET> |
| 252 |
method. |
| 253 |
|
| 254 |
=item * |
| 255 |
|
| 256 |
Update a blog entry. If we were building an API or single-page application, |
| 257 |
this would correspond to the HTTP C<PUT> or C<PATCH> methods. In a |
| 258 |
traditional CRUD-based web application, this will use the C<POST> method. |
| 259 |
|
| 260 |
There is a UI component to this as well, which will use the HTTP C<GET> |
| 261 |
method. |
| 262 |
|
| 263 |
=item * |
| 264 |
|
| 265 |
Delete a blog entry. If we were building an API or single-page application, |
| 266 |
this would correspond to the HTTP C<DELETE> method. However, for simplicity, |
| 267 |
we'll use the HTTP C<GET> method to prompt the user for confirmation, and a |
| 268 |
C<POST> route to actually perform the deletion. |
| 269 |
|
| 270 |
=back |
| 271 |
|
| 272 |
We'll also need a route to see the list of all blog entries. This will use |
| 273 |
the HTTP C<GET> method. |
| 274 |
|
| 275 |
=head3 Add an Entry (Create) |
| 276 |
|
| 277 |
This requires two routes: one to display the create form, and another to |
| 278 |
process the input and create the entry. |
| 279 |
|
| 280 |
To display the entry form: |
| 281 |
|
| 282 |
get '/create' => sub { |
| 283 |
return "Show the entry form"; |
| 284 |
}; |
| 285 |
|
| 286 |
To process the input and create the blog entry: |
| 287 |
|
| 288 |
post '/create' => sub { |
| 289 |
return "Creates the new blog entry"; |
| 290 |
}; |
| 291 |
|
| 292 |
=head3 Display an Entry (Read) |
| 293 |
|
| 294 |
This route is similar to the one needed to display the creation form: |
| 295 |
|
| 296 |
get '/entry/:id' => sub { |
| 297 |
my $id = route_parameters->get('id'); |
| 298 |
return "Showing entry ID $id"; |
| 299 |
}; |
| 300 |
|
| 301 |
The route declaration contains a parameter this time: the id of the |
| 302 |
blog entry we wish to view. The C<route_parameters> keyword is used to |
| 303 |
fetch the ID passed to our application. |
| 304 |
|
| 305 |
=head3 Update an Entry (Update) |
| 306 |
|
| 307 |
As with adding an entry, this requires two routes: one to display the |
| 308 |
entry form, and another to process the changes: |
| 309 |
|
| 310 |
get '/update/:id' => sub { |
| 311 |
my $id = route_parameters->get('id'); |
| 312 |
return "Show the update form for entry id $id"; |
| 313 |
}; |
| 314 |
|
| 315 |
post '/update/:id' => sub { |
| 316 |
my $id = route_parameters->get('id'); |
| 317 |
return "Updates the specified blog entry"; |
| 318 |
}; |
| 319 |
|
| 320 |
Again, the entry ID is provided to our Dancer2 application as a route |
| 321 |
parameter. |
| 322 |
|
| 323 |
=head3 Delete an Entry (Delete) |
| 324 |
|
| 325 |
This also needs two routes: one to confirm the user wants to delete the |
| 326 |
blog entry, and another to actually delete it: |
| 327 |
|
| 328 |
get '/delete/:id' => sub { |
| 329 |
my $id = route_parameters->get('id'); |
| 330 |
return "Show the delete confirmation for entry id $id"; |
| 331 |
}; |
| 332 |
|
| 333 |
post '/delete/:id' => sub { |
| 334 |
my $id = route_parameters->get('id'); |
| 335 |
return "Deletes the specified blog entry"; |
| 336 |
}; |
| 337 |
|
| 338 |
=head3 Displaying the Entry List |
| 339 |
|
| 340 |
Finally, we need a route to display the list of all blog entries: |
| 341 |
|
| 342 |
get '/' => sub { |
| 343 |
return "Show the list of blog entries"; |
| 344 |
}; |
| 345 |
|
| 346 |
=head2 Putting it all Together |
| 347 |
|
| 348 |
So far, F<lib/DLBlog.pm> should look like this: |
| 349 |
|
| 350 |
package DLBlog; |
| 351 |
use Dancer2; |
| 352 |
|
| 353 |
get '/' => sub { |
| 354 |
return "Show the list of blog entries"; |
| 355 |
}; |
| 356 |
|
| 357 |
get '/entry/:id' => sub { |
| 358 |
my $id = route_parameters->get('id'); |
| 359 |
return "Showing entry ID $id"; |
| 360 |
}; |
| 361 |
|
| 362 |
get '/create' => sub { |
| 363 |
return "Show the entry form"; |
| 364 |
}; |
| 365 |
|
| 366 |
post '/create' => sub { |
| 367 |
return "Creates the new blog entry"; |
| 368 |
}; |
| 369 |
|
| 370 |
get '/update/:id' => sub { |
| 371 |
my $id = route_parameters->get('id'); |
| 372 |
return "Show the update form for entry id $id"; |
| 373 |
}; |
| 374 |
|
| 375 |
post '/update/:id' => sub { |
| 376 |
my $id = route_parameters->get('id'); |
| 377 |
return "Updates the specified blog entry"; |
| 378 |
}; |
| 379 |
|
| 380 |
get '/delete/:id' => sub { |
| 381 |
my $id = route_parameters->get('id'); |
| 382 |
return "Show the delete confirmation for entry id $id"; |
| 383 |
}; |
| 384 |
|
| 385 |
post '/delete/:id' => sub { |
| 386 |
my $id = route_parameters->get('id'); |
| 387 |
return "Deletes the specified blog entry"; |
| 388 |
}; |
| 389 |
|
| 390 |
true; |
| 391 |
|
| 392 |
=head3 Run your application! |
| 393 |
|
| 394 |
Let's see how it works. From the shell: |
| 395 |
|
| 396 |
plackup -r bin/app.psgi |
| 397 |
|
| 398 |
Then open your browser and test your GET routes (we have nothing to post |
| 399 |
yet!): |
| 400 |
|
| 401 |
=over |
| 402 |
|
| 403 |
=item * L<http://localhost:5000/> |
| 404 |
|
| 405 |
=item * L<http://localhost:5000/entry/1> |
| 406 |
|
| 407 |
=item * L<http://localhost:5000/create> |
| 408 |
|
| 409 |
=item * L<http://localhost:5000/update/1> |
| 410 |
|
| 411 |
=item * L<http://localhost:5000/delete/1> |
| 412 |
|
| 413 |
=back |
| 414 |
|
| 415 |
=head1 Setting Up Views |
| 416 |
|
| 417 |
=head2 Layout |
| 418 |
|
| 419 |
Let's replace F<views/layouts/main.tt> with simple HTML5 boilerplate: |
| 420 |
|
| 421 |
<!DOCTYPE html> |
| 422 |
<html lang="en"> |
| 423 |
<head> |
| 424 |
<meta charset="<% settings.charset %>"> |
| 425 |
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes"> |
| 426 |
<title><% title %></title> |
| 427 |
<link rel="stylesheet" href="<% request.uri_base %>/css/style.css"> |
| 428 |
</head> |
| 429 |
<body> |
| 430 |
<% content %> |
| 431 |
<div id="footer"> |
| 432 |
Powered by <a href="https://perldancer.org/">Dancer2</a> <% dancer_version %> |
| 433 |
</div> |
| 434 |
</body> |
| 435 |
</html> |
| 436 |
|
| 437 |
This gives us a barebones framework to build our blog into. It sets proper |
| 438 |
encoding of characters, an application title, adds a stylesheet, and adds |
| 439 |
a footer containing the version of Dancer2 powering the blog. |
| 440 |
|
| 441 |
=head2 Templates |
| 442 |
|
| 443 |
The special C<< <% content %> >> variable above is where templates used |
| 444 |
by our routes will display. Instead of returning a string from the routes |
| 445 |
defined above, let's create some templates that will contain the UI |
| 446 |
necessary to interact with the blog, along with some business logic to |
| 447 |
display them at the right time. |
| 448 |
|
| 449 |
=head3 The Index Route (C</>) |
| 450 |
|
| 451 |
Replace the existing F<views/index.tt> with the following: |
| 452 |
|
| 453 |
<div id="entries"> |
| 454 |
<% IF entries.size %> |
| 455 |
<dl> |
| 456 |
<% FOREACH entry IN entries %> |
| 457 |
<dt><a href="/entry/<% entry.id %>"><% entry.title | html_entity %></a> |
| 458 |
(created at <% entry.created_at | html_entity %>)</dt> |
| 459 |
<dd><% entry.summary | html_entity %></dd> |
| 460 |
<% END %> |
| 461 |
</dl> |
| 462 |
<% ELSE %> |
| 463 |
<p>No entries found.</p> |
| 464 |
<% END %> |
| 465 |
</div> |
| 466 |
|
| 467 |
This list will be populated when we read entries from the database later |
| 468 |
in this tutorial. |
| 469 |
|
| 470 |
What's with all these C<html_entity> things? The C<|> is Template Toolkit |
| 471 |
syntax for a filter, and C<html_entity> represents the filter we are using. |
| 472 |
This particular filter properly excapes characters like ampersands when |
| 473 |
displaying them as HTML. |
| 474 |
|
| 475 |
To use this template in our app, we'll use the C<template> keyword to plug |
| 476 |
this into our route: |
| 477 |
|
| 478 |
get '/' => sub { |
| 479 |
my @entries; # We'll populate this later |
| 480 |
template 'index', { entries => \@entries }; |
| 481 |
}; |
| 482 |
|
| 483 |
=head3 The View Entry Route C</entry/:id> |
| 484 |
|
| 485 |
We'll create a new template, F<views/entry.tt>, that contains everything |
| 486 |
we think we'll need to show a blog entry: |
| 487 |
|
| 488 |
<% IF entry %> |
| 489 |
<div id="sidebar"> |
| 490 |
<h1>Posted at</h1> |
| 491 |
<p><% entry.created_at | html_entity %></p> |
| 492 |
<h1>Summary</h1> |
| 493 |
<p><% entry.summary | html_entity %></p> |
| 494 |
</div> |
| 495 |
<div id="content"> |
| 496 |
<h2><% entry.title | html_entity %></h2> |
| 497 |
<p><% entry.content | html_entity %></p> |
| 498 |
<% ELSE %> |
| 499 |
<p>Invalid entry.</p> |
| 500 |
<% END %> |
| 501 |
</div> |
| 502 |
|
| 503 |
C<entry> is a hashref that has the contents of our blog post. If a valid |
| 504 |
entry ID isn't provided, we give the user a message explaining so. |
| 505 |
Otherwise, we'll provide a two column layout with metadata in the sidebar, |
| 506 |
and blog content on the main part of the page. |
| 507 |
|
| 508 |
This is going to be ugly as written; we'll add some styling at the end to |
| 509 |
make things look nicer. |
| 510 |
|
| 511 |
Let's modify our route for viewing entries to use this template: |
| 512 |
|
| 513 |
get '/entry/:id' => sub { |
| 514 |
my $id = route_parameters->get('id'); |
| 515 |
my $entry; # Populated from the database later |
| 516 |
template 'entry', { entry => $entry }; |
| 517 |
}; |
| 518 |
|
| 519 |
=head3 The Create Entry Routes C</create> |
| 520 |
|
| 521 |
This is just a simple form to create a new blog entry. Create |
| 522 |
F<views/create.tt> with the following: |
| 523 |
|
| 524 |
<div id="create"> |
| 525 |
<form method="post" action="<% request.uri_for('/create') %>"> |
| 526 |
<label for="title">Title</label> |
| 527 |
<input type="text" name="title" id="title"><br> |
| 528 |
<label for="summary">Summary</label> |
| 529 |
<input type="text" name="summary" id="summary"><br> |
| 530 |
<label for="content">Content</label> |
| 531 |
<textarea name="content" id="content" cols="50" rows="10"></textarea><br> |
| 532 |
<input type="submit"> |
| 533 |
</form> |
| 534 |
</div> |
| 535 |
|
| 536 |
Using C<uri_for> when specifying the POST URL allows Dancer2 to create a |
| 537 |
proper URL no matter where your app is running from. |
| 538 |
|
| 539 |
This can be added to the create route: |
| 540 |
|
| 541 |
get '/create' => sub { |
| 542 |
template 'create'; |
| 543 |
}; |
| 544 |
|
| 545 |
There is no template when POSTing to C</create>. There are two possible |
| 546 |
outcomes when creating a blog entry: |
| 547 |
|
| 548 |
=over |
| 549 |
|
| 550 |
=item Creation was successful, so we redirect somewhere sensible |
| 551 |
|
| 552 |
=item Creation failed, so we redisplay the filled in form and show an error |
| 553 |
|
| 554 |
=back |
| 555 |
|
| 556 |
We'll show how to do both of these in the implementation section later. |
| 557 |
For now: |
| 558 |
|
| 559 |
post '/create' => sub { |
| 560 |
my $new_id = 1; |
| 561 |
redirect uri_for "/entry/$new_id"; # redirect does not need a return |
| 562 |
}; |
| 563 |
|
| 564 |
=head3 The Update Entry Routes (C</update/:id>) |
| 565 |
|
| 566 |
Showing the UI for updating a blog entry is similar to what we did in |
| 567 |
create above, except that we will need to display the existing values |
| 568 |
of an entry in the form (we don't want to make the user re-enter |
| 569 |
everything when updating, do we?). Since we have no values to show right |
| 570 |
now, we will implement this latter part in the implementation section |
| 571 |
below. |
| 572 |
|
| 573 |
For now, let's just return the existing create form: |
| 574 |
|
| 575 |
get '/update/:id' => sub { |
| 576 |
my $id = route_parameters->get('id'); |
| 577 |
template 'create'; |
| 578 |
}; |
| 579 |
|
| 580 |
We don't need a special template for displaying the results of an update, |
| 581 |
we just need to show the resulting entry. Don't we already have a route |
| 582 |
that does that though? Why should we do that work again here? We shouldn't! |
| 583 |
|
| 584 |
Dancer2 will let you change the flow of your application using the |
| 585 |
C<forward> or C<redirect> keywords. But which should we choose? |
| 586 |
|
| 587 |
=over |
| 588 |
|
| 589 |
=item C<forward> is an internal redirect |
| 590 |
|
| 591 |
This lets you perform the functionality contained in another route, but |
| 592 |
it's done internally, which means that the URL shown to the user in their |
| 593 |
browser's address bar looks like the one they requested. In the case of |
| 594 |
our update, the browser bar will show C<http://localhost:5000/update/1>, |
| 595 |
but what they would be seeing is the output from C<http://localhost:5000/entry/1>. |
| 596 |
This is not desirable, as it is confusing for a user to look at. |
| 597 |
|
| 598 |
=item C<redirect> is an external redirect |
| 599 |
|
| 600 |
External redirects sends the user to a different URL by sending a redirect |
| 601 |
response from Dancer2. Even though the user is executing a POST to |
| 602 |
C<http://localhost:5000/update/1>, upon completion, they're browser bar |
| 603 |
will show C<http://localhost:5000/entry/1>. This is a better option, as |
| 604 |
when an update completes successfully, the URL will match what the user sees |
| 605 |
in their browser. |
| 606 |
|
| 607 |
To do this, let's use the redirect keyword: |
| 608 |
|
| 609 |
post '/update/:id' => sub { |
| 610 |
my $id = route_parameters->get('id'); |
| 611 |
redirect uri_for "/entry/$id"; # redirect does not need a return |
| 612 |
}; |
| 613 |
|
| 614 |
We will show how to update an existing entry later in the tutorial. |
| 615 |
|
| 616 |
=back |
| 617 |
|
| 618 |
=head3 The Delete Routes |
| 619 |
|
| 620 |
It's wouldn't be kind to the user to simply delete an entry without giving |
| 621 |
them the option to change their mind, and that's what the GET route for |
| 622 |
deletion is intended to do. |
| 623 |
|
| 624 |
Let's give the user a simple confirmation form. Create F<views/delete.tt>: |
| 625 |
|
| 626 |
<div id="delete"> |
| 627 |
<form method="post" action="<% request.uri_for('/delete/' _ id) %>"> |
| 628 |
<p>Delete entry <% id %>. Are you sure?</p> |
| 629 |
<p> |
| 630 |
<input type="radio" id="yes" name="delete_it" value="yes"> |
| 631 |
<label for="yes">Yes</label> |
| 632 |
</p> |
| 633 |
<p> |
| 634 |
<input type="radio" id="no" name="delete_it" value="no"> |
| 635 |
<label for="no">No</label> |
| 636 |
</p> |
| 637 |
<input type="submit"> |
| 638 |
</form> |
| 639 |
</div> |
| 640 |
|
| 641 |
Our GET route for delete will need to change: |
| 642 |
|
| 643 |
get '/delete/:id' => sub { |
| 644 |
my $id = route_parameters->get('id'); |
| 645 |
template 'delete', { id => $id }; |
| 646 |
}; |
| 647 |
|
| 648 |
Similar to create and update, there's no need to create another template |
| 649 |
to show the results of a delete. We'll just send the user back to the |
| 650 |
list of blog entries: |
| 651 |
|
| 652 |
post '/delete/:id' => sub { |
| 653 |
my $id = route_parameters->get('id'); |
| 654 |
|
| 655 |
# Always default to not destroying data |
| 656 |
my $delete_it = body_parameters->get('delete_it') // 0; |
| 657 |
|
| 658 |
if( $delete_it ) { |
| 659 |
# Do the deletion here |
| 660 |
redirect uri_for "/"; |
| 661 |
} else { |
| 662 |
# Display our entry again |
| 663 |
redirect uri_for "/entry/$id"; |
| 664 |
} |
| 665 |
}; |
| 666 |
|
| 667 |
Notice the addition of the C<body_parameters>? This is to get the value |
| 668 |
of the radio button the user selected. This is important to decide if |
| 669 |
the user actually wants to delete or not. |
| 670 |
|
| 671 |
=head2 Reviewing our Application Code |
| 672 |
|
| 673 |
F<lib/DLBlog.pm> should now look like this: |
| 674 |
|
| 675 |
package DLBlog; |
| 676 |
use Dancer2; |
| 677 |
|
| 678 |
get '/' => sub { |
| 679 |
my @entries; # We'll populate this later |
| 680 |
template 'index', { entries => \@entries }; |
| 681 |
}; |
| 682 |
|
| 683 |
get '/entry/:id' => sub { |
| 684 |
my $id = route_parameters->get('id'); |
| 685 |
my $entry; # Populated from the database later |
| 686 |
template 'entry', { entry => $entry }; |
| 687 |
}; |
| 688 |
|
| 689 |
get '/create' => sub { |
| 690 |
template 'create'; |
| 691 |
}; |
| 692 |
|
| 693 |
post '/create' => sub { |
| 694 |
my $new_id = 1; |
| 695 |
redirect uri_for "/entry/$new_id"; # redirect does not need a return |
| 696 |
}; |
| 697 |
|
| 698 |
get '/update/:id' => sub { |
| 699 |
my $id = route_parameters->get('id'); |
| 700 |
template 'create'; |
| 701 |
}; |
| 702 |
|
| 703 |
post '/update/:id' => sub { |
| 704 |
my $id = route_parameters->get('id'); |
| 705 |
redirect uri_for "/entry/$id"; |
| 706 |
}; |
| 707 |
|
| 708 |
get '/delete/:id' => sub { |
| 709 |
my $id = route_parameters->get('id'); |
| 710 |
template 'delete', { id => $id }; |
| 711 |
}; |
| 712 |
|
| 713 |
post '/delete/:id' => sub { |
| 714 |
my $id = route_parameters->get('id'); |
| 715 |
|
| 716 |
# Always default to not destroying data |
| 717 |
my $delete_it = body_parameters->get('delete_it') // 0; |
| 718 |
|
| 719 |
if( $delete_it ) { |
| 720 |
# Do the deletion here |
| 721 |
redirect uri_for "/"; |
| 722 |
} else { |
| 723 |
# Display our entry again |
| 724 |
redirect uri_for "/entry/$id"; |
| 725 |
} |
| 726 |
}; |
| 727 |
|
| 728 |
true; |
| 729 |
|
| 730 |
=head2 Adding Utility to our Views |
| 731 |
|
| 732 |
This is all well and good, but it's not the most functional for our users. |
| 733 |
A basic menu of available options would help users to understand what |
| 734 |
actions can be performed in the Danceyland Blog. |
| 735 |
|
| 736 |
=head3 Adding a Menu to our Layout |
| 737 |
|
| 738 |
Let's edit our layout so users can see the same list of options across all |
| 739 |
pages. By adding the menu once to the layout, we don't have to reproduce |
| 740 |
this in the list, create, update, and delete templates. |
| 741 |
|
| 742 |
Our menu will look like this: |
| 743 |
|
| 744 |
<div id="menu"> |
| 745 |
<a href="<% request.uri_for('/') %>">List All Entries</a> | |
| 746 |
<a href="<% request.uri_for('/create') %>">Create New Entry</a> |
| 747 |
</div> |
| 748 |
|
| 749 |
Now, let's add it to the top of our layout. The end result looks like: |
| 750 |
|
| 751 |
<!DOCTYPE html> |
| 752 |
<html lang="en"> |
| 753 |
<head> |
| 754 |
<meta charset="<% settings.charset %>"> |
| 755 |
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes"> |
| 756 |
<title><% title %></title> |
| 757 |
<link rel="stylesheet" href="<% request.uri_base %>/css/style.css"> |
| 758 |
</head> |
| 759 |
<body> |
| 760 |
<div id="menu"> |
| 761 |
<a href="<% request.uri_for('/') %>">List All Entries</a> | |
| 762 |
<a href="<% request.uri_for('/create') %>">Create New Entry</a> |
| 763 |
</div> |
| 764 |
<% content %> |
| 765 |
<div id="footer"> |
| 766 |
Powered by <a href="https://perldancer.org/">Dancer2</a> <% dancer_version %> |
| 767 |
</div> |
| 768 |
</body> |
| 769 |
</html> |
| 770 |
|
| 771 |
Refresh your browser to see the menu appear at the top of your page. |
| 772 |
|
| 773 |
=head1 The Danceyland Database |
| 774 |
|
| 775 |
We need some way to persist the blog entries, and relational databases |
| 776 |
excel at this. We'll use SQLite for this tutorial, but you can use any |
| 777 |
database supported by L<Dancer2::Plugin::Database> and L<DBI>. |
| 778 |
|
| 779 |
L<SQLite|https://sqlite.org> is a lightweight, single file database that |
| 780 |
makes it easy to add relational database functionality to a low-concurrency |
| 781 |
web application. |
| 782 |
|
| 783 |
=head2 Setting Up the Database |
| 784 |
|
| 785 |
At minimum, we need to create a table to contain our blog entries. Create |
| 786 |
a new directory for your database and SQL files: |
| 787 |
|
| 788 |
$ mkdir db |
| 789 |
|
| 790 |
Then create a new file, F<db/entries.sql>, with the following: |
| 791 |
|
| 792 |
CREATE TABLE entries ( |
| 793 |
id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 794 |
title TEXT NOT NULL, |
| 795 |
summary TEXT NOT NULL, |
| 796 |
content TEXT NOT NULL, |
| 797 |
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP |
| 798 |
); |
| 799 |
|
| 800 |
Later, we'll add an additional table for users. |
| 801 |
|
| 802 |
Let's create our blog database with the above table. From our project |
| 803 |
directory: |
| 804 |
|
| 805 |
$ sqlite3 db/dlblog.db < db/entries.sql |
| 806 |
|
| 807 |
=head2 Using Dancer2::Plugin::DBIx::Class |
| 808 |
|
| 809 |
L<Dancer2::Plugin::DBIx::Class> is a plugin that integrates the |
| 810 |
L<DBIx::Class> Object Relational Mapper (ORM) and Dancer2. It maps tables, |
| 811 |
rows, and columns into classes, objects, and methods in Perl. L<DBIx::Class> |
| 812 |
(DBIC for short) makes it convenient to work with databases in your Perl |
| 813 |
applications and reduces a lot of manual SQL creation. |
| 814 |
|
| 815 |
DBIC is also a large and complex beast, and can take some time to become |
| 816 |
proficient with it. This tutorial merely scrapes the surface of what you |
| 817 |
can do with it; for more information, check out |
| 818 |
L<DBIx::Class::Manual::DocMap>. |
| 819 |
|
| 820 |
You'll also need to install two other dependencies, L<DBD::SQLite> (the |
| 821 |
SQLite database driver), L<DBIx::Class::Schema::Loader> (for automatically |
| 822 |
generating database classes from tables), and L<DateTime::Format::SQLite> |
| 823 |
(to interact with dates in DBIC objects). |
| 824 |
|
| 825 |
Install them using C<cpan> or C<cpanm>: |
| 826 |
|
| 827 |
cpanm DBD::SQLite Dancer2::Plugin::DBIx::Class \ |
| 828 |
DBIx::Class::Schema::Loader DateTime::Format::SQLite |
| 829 |
|
| 830 |
Add these to your F<cpanfile>: |
| 831 |
|
| 832 |
requires "DBD::SQLite"; |
| 833 |
requires "Dancer2::Plugin::DBIx::Class"; |
| 834 |
requires "DBIx::Class::Schema::Loader"; |
| 835 |
requires "DateTime::Format::SQLite"; |
| 836 |
|
| 837 |
And then add it to the top of F<lib/DLBlog.pm> after C<use Dancer2;>: |
| 838 |
|
| 839 |
use Dancer2::Plugin::DBIx::Class; |
| 840 |
|
| 841 |
We need to add configuration to tell our plugin where to find the SQLite |
| 842 |
database. For this project, it's sufficient to put configuration for |
| 843 |
the database in F<config.yml>. In a production application, you'd |
| 844 |
have different database credentials in your development and staging |
| 845 |
environments than you would in your production environment (we'd hope you |
| 846 |
would anyhow!). And this is where environment config files are handy. |
| 847 |
|
| 848 |
By default, Dancer2 runs your application in the development environment. |
| 849 |
To that end, we'll add plugin configuration appropriately. Add the following |
| 850 |
to your F<environments/development.yml> file: |
| 851 |
|
| 852 |
plugins: |
| 853 |
DBIx::Class: |
| 854 |
default: |
| 855 |
dsn: "dbi:SQLite:dbname=db/dlblog.db" |
| 856 |
schema_class: "DLBlog::Schema" |
| 857 |
dbi_params: |
| 858 |
RaiseError: 1 |
| 859 |
AutoCommit: 1 |
| 860 |
|
| 861 |
Note that we only provided C<DBIx::Class> for the plugin name; Dancer2 |
| 862 |
automatically infers the C<Dancer2::Plugin::> prefix. |
| 863 |
|
| 864 |
As SQLite databases are a local file, we don't need to provide login |
| 865 |
credentials for the database. The two settings in the C<dbi_params> |
| 866 |
section tell L<DBIx::Class> to raise an error automatically to our code |
| 867 |
(should one occur), and to automatically manage transactions for us (so |
| 868 |
we don't have to). |
| 869 |
|
| 870 |
=head1 Generating Schema Classes |
| 871 |
|
| 872 |
L<DBIx::Class> relies on class definitions to map database tables to |
| 873 |
Perl constructs. Thankfully, L<DBIx::Class::Schema::Loader> can do much |
| 874 |
of this work for us. |
| 875 |
|
| 876 |
To generate the schema object, and a class that represents the C<entries> |
| 877 |
table, run the following from your shell: |
| 878 |
|
| 879 |
dbicdump -o dump_directory=./lib \ |
| 880 |
-o components='["InflateColumn::DateTime"]' \ |
| 881 |
DLBlog::Schema dbi:SQLite:db/dlblog.db '{ quote_char => "\"" }' |
| 882 |
|
| 883 |
This creates two new files in your application: |
| 884 |
|
| 885 |
=over |
| 886 |
|
| 887 |
=item * F<lib/DLBlog/Schema.pm> |
| 888 |
|
| 889 |
This is a class that represents all database schema. |
| 890 |
|
| 891 |
=item * F<lib/DLBlog/Schema/Result/Entry.pm> |
| 892 |
|
| 893 |
This is a class representing a single row in the C<entries> table. |
| 894 |
|
| 895 |
=back |
| 896 |
|
| 897 |
=head1 Implementing the Danceyland Blog |
| 898 |
|
| 899 |
Let's start by creating an entry and saving it to the database; all other |
| 900 |
routes rely on us having at least one entry (in some form). |
| 901 |
|
| 902 |
=head2 Performing Queries |
| 903 |
|
| 904 |
L<Dancer2::Plugin::DBIx::Class> lets us easily perform SQL queries against |
| 905 |
a database. It does this by providing methods to interact with data, such |
| 906 |
as C<find>, C<search>, C<create>, and C<update>. These methods make for |
| 907 |
simpler maintenance of code, as they do all the work of writing and executing |
| 908 |
SQL in the background. |
| 909 |
|
| 910 |
For example, let's use a convenience method to create a new blog entry. |
| 911 |
Here's the form we created for entering a blog post: |
| 912 |
|
| 913 |
<div id="create"> |
| 914 |
<form method="post" action="<% request.uri_for('/create') %>"> |
| 915 |
<label for="title">Title</label> |
| 916 |
<input type="text" name="title" id="title"><br> |
| 917 |
<label for="summary">Summary</label> |
| 918 |
<input type="text" name="summary" id="summary"><br> |
| 919 |
<label for="content">Content</label> |
| 920 |
<textarea name="content" id="content" cols="50" rows="10"></textarea><br> |
| 921 |
<button type="submit">Save Entry</button> |
| 922 |
</form> |
| 923 |
</div> |
| 924 |
|
| 925 |
We can take values submitted via this form and turn them into a row in |
| 926 |
the database: |
| 927 |
|
| 928 |
post '/create' => sub { |
| 929 |
my $params = body_parameters(); |
| 930 |
|
| 931 |
my $entry = do { |
| 932 |
try { |
| 933 |
resultset('Entry')->create( $params->as_hashref ); |
| 934 |
} |
| 935 |
catch( $e ) { |
| 936 |
error "Database error: $e"; |
| 937 |
var error_message => 'A database error occurred; your entry could not be created', |
| 938 |
forward '/create', {}, { method => 'GET' }; |
| 939 |
} |
| 940 |
}; |
| 941 |
redirect uri_for "/entry/" . $entry->id; # redirect does not need a return |
| 942 |
}; |
| 943 |
|
| 944 |
Form fields are sent to Dancer2 as body parameters, so we need to use the |
| 945 |
C<body_parameters> keyword to get them: |
| 946 |
|
| 947 |
my $params = body_parameters(); |
| 948 |
|
| 949 |
This returns all body parameters as a single hashref, where each form |
| 950 |
field name is a key, and the value is what the user input into the form. |
| 951 |
|
| 952 |
In a production environment, you'd want to sanitize this data before |
| 953 |
attempting a database operation. When you sanitize data, you are ensuring |
| 954 |
that data contains only the values you would expect to receive. If it's |
| 955 |
not what you'd expect, you can remove the extra cruft (sanitize), or ask |
| 956 |
the user to correct their entry. |
| 957 |
|
| 958 |
Database operations can fail, so we should make an attempt to trap any |
| 959 |
errors. C<try/catch> lends itself well to this type of error checking. |
| 960 |
Newer versions of Perl have a built-in C<try> keyword, but older versions |
| 961 |
do not. To protect against this, let's install L<Feature::Compat::Try>, |
| 962 |
which uses the built-in C<try> if your Perl has it, otherwise provides |
| 963 |
a backported implementation. To install this module, run F<cpanm>: |
| 964 |
|
| 965 |
cpanm Feature::Compat::Try |
| 966 |
|
| 967 |
And add it to your F<cpanfile>: |
| 968 |
|
| 969 |
requires "Feature::Compat::Try"; |
| 970 |
|
| 971 |
Then make sure to include it at the top of your application: |
| 972 |
|
| 973 |
use Feature::Compat::Try; |
| 974 |
|
| 975 |
The code inside the C<try> block will be executed, and if it fails, will |
| 976 |
C<catch> the error, and execute the code in that block. |
| 977 |
|
| 978 |
try { |
| 979 |
resultset('Entry')->create( $params->as_hashref ); |
| 980 |
} |
| 981 |
|
| 982 |
This uses the C<quick_insert> method of our Database plugin, and passes |
| 983 |
the values from the form through to create a row in the C<entries> table. |
| 984 |
|
| 985 |
If a database error occurs, we need to handle it: |
| 986 |
|
| 987 |
catch( $e ) { |
| 988 |
error "Database error: $e"; |
| 989 |
var error_message => 'A database error occurred; your entry could not be created', |
| 990 |
forward '/create', {}, { method => 'GET' }; |
| 991 |
} |
| 992 |
|
| 993 |
The first line creates an error log message containing the actual database |
| 994 |
error; this will be valuable in helping to debug your application, or |
| 995 |
troubleshoot a user issue. We then stash a message in a variable to be |
| 996 |
displayed on the create page once it is redisplayed. |
| 997 |
For the sake of brevity, we populate message with a really basic error |
| 998 |
message. In a production application, you'd want to provide the user with |
| 999 |
a more descriptive message to help them resolve their own problem, if |
| 1000 |
possible. |
| 1001 |
|
| 1002 |
Why not pass the database error directly to the user? Because this gives |
| 1003 |
a potential attacker information about your database and application. |
| 1004 |
|
| 1005 |
Finally, we send the user back to the entry form: |
| 1006 |
|
| 1007 |
forward uri_for '/create', {}, { method => 'GET' }; |
| 1008 |
|
| 1009 |
By default, C<forward> invokes a route with the same HTTP verb of the route |
| 1010 |
it is executing from. You can change the verb used by passing a third |
| 1011 |
hashref containing the C<method> key. The second (empty) hashref contains |
| 1012 |
an optional list of parameters to be passed to the forwarded route. |
| 1013 |
|
| 1014 |
If the insert succeeds, C<create> returns an object that represents the |
| 1015 |
newly created database row, and assigns it to the variable C<$entry>. |
| 1016 |
We can perform additional database operations against this row by calling |
| 1017 |
methods on C<$entry>. As a convenience to the user, we should take them to |
| 1018 |
a page where they can view their new entry: |
| 1019 |
|
| 1020 |
debug 'Created entry ' . $entry->id . ' for "' . $entry->title . '"'; |
| 1021 |
redirect uri_for "/entry/" . $entry->id; # redirect does not need a return |
| 1022 |
|
| 1023 |
The first line logs a message showing the post was successfully created, |
| 1024 |
then redirects the user to the entry display page on the last line. |
| 1025 |
|
| 1026 |
=head3 Redisplaying the Create Form |
| 1027 |
|
| 1028 |
In the case of an error, it's a good practice to redisplay the original |
| 1029 |
form with the previous values populated. We could add code in our POST |
| 1030 |
route to redisplay the form, or we could use the code we already wrote |
| 1031 |
to display the form instead. We'll go with the latter. |
| 1032 |
|
| 1033 |
Dancer2's C<var> keyword lets you create variables to use elsewhere in |
| 1034 |
your application, including templates. We'll use these to keep track of |
| 1035 |
what the user has already entered, and to display a message to the user |
| 1036 |
if any required parameters are missing. |
| 1037 |
|
| 1038 |
To save any entered parameters into vars, add this line right after the |
| 1039 |
call to C<body_parameters>: |
| 1040 |
|
| 1041 |
var $_ => $params->{ $_ } foreach qw< title summary content >; |
| 1042 |
|
| 1043 |
Now, let's check if any of these were not provided when the user submitted |
| 1044 |
the create form: |
| 1045 |
|
| 1046 |
my @missing = grep { $params->{$_} eq '' } qw< title summary content >; |
| 1047 |
if( @missing ) { |
| 1048 |
var missing => join ",", @missing; |
| 1049 |
warning "Missing parameters: " . var 'missing'; |
| 1050 |
forward '/create', {}, { method => 'GET' }; |
| 1051 |
} |
| 1052 |
|
| 1053 |
If any of C<title>, C<summary>, or C<content> are missing, we build up |
| 1054 |
a message containing the list of missing parameters. We then set a variable, |
| 1055 |
C<missing>, with the message to display. Finally, we internally redirect |
| 1056 |
(via the C<forward> keyword) back to the GET route that displays our create |
| 1057 |
form. |
| 1058 |
|
| 1059 |
Your new C<post '/create'> route should now look like this: |
| 1060 |
|
| 1061 |
post '/create' => sub { |
| 1062 |
my $params = body_parameters(); |
| 1063 |
var $_ => $params->{ $_ } foreach qw< title summary content >; |
| 1064 |
|
| 1065 |
my @missing = grep { $params->{$_} eq '' } qw< title summary content >; |
| 1066 |
if( @missing ) { |
| 1067 |
var missing => join ",", @missing; |
| 1068 |
warning "Missing parameters: " . var 'missing'; |
| 1069 |
forward '/create', {}, { method => 'GET' }; |
| 1070 |
} |
| 1071 |
|
| 1072 |
my $entry = do { |
| 1073 |
try { |
| 1074 |
resultset('Entry')->create( $params->as_hashref ); |
| 1075 |
} |
| 1076 |
catch( $e ) { |
| 1077 |
error "Database error: $e"; |
| 1078 |
var error_message => 'A database error occurred; your entry could not be created', |
| 1079 |
forward '/create', {}, { method => 'GET' }; |
| 1080 |
} |
| 1081 |
}; |
| 1082 |
|
| 1083 |
debug 'Created entry ' . $entry->id . ' for "' . $entry->title . '"'; |
| 1084 |
redirect uri_for "/entry/" . $entry->id; # redirect does not need a return |
| 1085 |
}; |
| 1086 |
|
| 1087 |
These changes to our C<post '/create'> route creates some succinct code |
| 1088 |
that's easy to follow, but may not be the best for a production application. |
| 1089 |
Better error handling could be added, retry logic for failed database |
| 1090 |
connections doesn't exist, data validation is lacking, etc. All of these |
| 1091 |
features can be added to the blog at a later time as additional exercises for |
| 1092 |
the developer. |
| 1093 |
|
| 1094 |
=head3 Updating the create form to show previous values |
| 1095 |
|
| 1096 |
We need to adjust the create form to show the values we stashed as |
| 1097 |
variables with the C<var> keyword: |
| 1098 |
|
| 1099 |
<div id="create"> |
| 1100 |
<form method="post" action="<% request.uri_for('/create') %>"> |
| 1101 |
<label for="title">Title</label> |
| 1102 |
<input type="text" name="title" id="title" value="<% vars.title %>"><br> |
| 1103 |
<label for="summary">Summary</label> |
| 1104 |
<input type="text" name="summary" id="summary" value="<% vars.summary %>"><br> |
| 1105 |
<label for="content">Content</label> |
| 1106 |
<textarea name="content" id="content" cols="50" rows="10"><% vars.content %></textarea><br> |
| 1107 |
<button type="submit">Save Entry</button> |
| 1108 |
</form> |
| 1109 |
</div> |
| 1110 |
|
| 1111 |
Variables stashed in your Dancer2 application are available via the C<vars> |
| 1112 |
hashref, such as C<< <% vars.title %> >>. When C</create> displays this form, |
| 1113 |
any stashed variable values will be filled in to their appropriat form |
| 1114 |
element. |
| 1115 |
|
| 1116 |
=head1 Displaying messages |
| 1117 |
|
| 1118 |
In our application, we created a message to display a list of any missing |
| 1119 |
required fields. We also created an error message if our database operation |
| 1120 |
fails. Now, we need to create a place in the layout to display them. |
| 1121 |
|
| 1122 |
Below our menu, but above our content, add the following: |
| 1123 |
|
| 1124 |
<% IF vars.missing %> |
| 1125 |
<div id="missing"> |
| 1126 |
<b>Missing parameters: <% vars.missing | html_entity %></b> |
| 1127 |
</div> |
| 1128 |
<% END %> |
| 1129 |
<% IF error_message %> |
| 1130 |
<div id="error"> |
| 1131 |
<b>Error: <% vars.error_message | html_entity %></b> |
| 1132 |
</div> |
| 1133 |
<% END %> |
| 1134 |
|
| 1135 |
This creates two message C<divs>: one that displays missing values, and |
| 1136 |
another that displays errors. Creating them separately allows us to more |
| 1137 |
easily style them appropriately later. |
| 1138 |
|
| 1139 |
Notice the C<IF/END> blocks? This content is optional; i.e., if there are |
| 1140 |
no missing fields or error messages, this markup will not be added to the |
| 1141 |
rendered HTML page. |
| 1142 |
|
| 1143 |
The layout should now look like: |
| 1144 |
|
| 1145 |
<!DOCTYPE html> |
| 1146 |
<html lang="en"> |
| 1147 |
<head> |
| 1148 |
<meta charset="<% settings.charset %>"> |
| 1149 |
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes"> |
| 1150 |
<title><% title %></title> |
| 1151 |
<link rel="stylesheet" href="<% request.uri_base %>/css/style.css"> |
| 1152 |
</head> |
| 1153 |
<body> |
| 1154 |
<div id="menu"> |
| 1155 |
<a href="<% request.uri_for('/') %>">List All Entries</a> | |
| 1156 |
<a href="<% request.uri_for('/create') %>">Create New Entry</a> |
| 1157 |
</div> |
| 1158 |
<% IF vars.missing %> |
| 1159 |
<div id="missing"> |
| 1160 |
<b>Missing parameters: <% vars.missing | html_entity %></b> |
| 1161 |
</div> |
| 1162 |
<% END %> |
| 1163 |
<% IF error_message %> |
| 1164 |
<div id="error"> |
| 1165 |
<b>Error: <% vars.error_message | html_entity %></b> |
| 1166 |
</div> |
| 1167 |
<% END %> |
| 1168 |
<% content %> |
| 1169 |
<div id="footer"> |
| 1170 |
Powered by <a href="https://perldancer.org/">Dancer2</a> <% dancer_version %> |
| 1171 |
</div> |
| 1172 |
</body> |
| 1173 |
</html> |
| 1174 |
|
| 1175 |
=head2 Displaying Blog Data |
| 1176 |
|
| 1177 |
Displaying a blog entry is fairly simple; the C<quick_select> method of |
| 1178 |
L<Dancer2::Plugin::Database> will return a database row as a hashref, which |
| 1179 |
can be passed as a parameter to a template: |
| 1180 |
|
| 1181 |
get '/entry/:id[Int]' => sub { |
| 1182 |
my $id = route_parameters->get('id'); |
| 1183 |
my $entry = resultset( 'Entry' )->find( $id ); |
| 1184 |
template 'entry', { entry => $entry }; |
| 1185 |
}; |
| 1186 |
|
| 1187 |
You may notice the route declaration changed; Dancer2 will let you decorate |
| 1188 |
a route parameter with a L<Type::Tiny> datatype; if the provided parameter |
| 1189 |
doesn't match the type expected by Dancer2, an HTTP 404 status will be |
| 1190 |
returned. Any call to C<route_parameters> is then guaranteed to have a |
| 1191 |
value of the desired type. |
| 1192 |
|
| 1193 |
We use the C<find()> method of L<DBIx::Class::ResultSet> to return a single |
| 1194 |
row and turn it into an object, which we will reference as C<$entry>. Should |
| 1195 |
C<find> not succeed, our template will display a message indicating so: |
| 1196 |
|
| 1197 |
<% IF entry %> |
| 1198 |
<div id="sidebar"> |
| 1199 |
<h1>Posted at</h1> |
| 1200 |
<p><% entry.created_at | html_entity %></p> |
| 1201 |
<h1>Summary</h1> |
| 1202 |
<p><% entry.summary | html_entity %></p> |
| 1203 |
</div> |
| 1204 |
<div id="content"> |
| 1205 |
<h2><% entry.title | html_entity %></h2> |
| 1206 |
<p><% entry.content | html_entity %></p> |
| 1207 |
<% ELSE %> |
| 1208 |
<p>Invalid entry.</p> |
| 1209 |
<% END %> |
| 1210 |
</div> |
| 1211 |
|
| 1212 |
By passing the resultset object directly to the template, you can call |
| 1213 |
methods directly on that object to display different columns of information, |
| 1214 |
such as C<title> and C<content>. If there is no valid entry, the C<ELSE> |
| 1215 |
section of the template will be displayed instead of the contents of the |
| 1216 |
blog post. |
| 1217 |
|
| 1218 |
=head2 Updating a blog entry |
| 1219 |
|
| 1220 |
To update a blog entry, we need a form that contains the values that have |
| 1221 |
already been entered for a given blog post. Didn't we already do that as |
| 1222 |
part of redisplaying the create form when it was missing values? Why yes |
| 1223 |
we did! What if we could reuse that form for editing an existing entry? |
| 1224 |
With a little bit of work, we absolutely can. |
| 1225 |
|
| 1226 |
Rename F<create.tt> to be F<create_update.tt>, then replace the contents |
| 1227 |
with the following: |
| 1228 |
|
| 1229 |
<div id="create_update"> |
| 1230 |
<form method="post" action="<% post_to %>"> |
| 1231 |
<label for="title">title</label> |
| 1232 |
<input type="text" name="title" id="title" value="<% vars.title %>"><br> |
| 1233 |
<label for="summary">summary</label> |
| 1234 |
<input type="text" name="summary" id="summary" value="<% vars.summary %>"><br> |
| 1235 |
<label for="content">content</label> |
| 1236 |
<textarea name="content" id="content" cols="50" rows="10"><% vars.content %></textarea><br> |
| 1237 |
<button type="submit">Save Entry</button> |
| 1238 |
</form> |
| 1239 |
</div> |
| 1240 |
|
| 1241 |
The following minor changes have been made: |
| 1242 |
|
| 1243 |
=over |
| 1244 |
|
| 1245 |
=item * The div id was changed to reflect the form's new purpose |
| 1246 |
|
| 1247 |
=item * The form action was changed to the template variable C<post_to> |
| 1248 |
|
| 1249 |
=back |
| 1250 |
|
| 1251 |
The form action will be different based upon whether we are creating a new |
| 1252 |
blog entry, or updating an existing one. |
| 1253 |
|
| 1254 |
We need to create a route to display the form such that it is suitable for |
| 1255 |
updating a blog entry: |
| 1256 |
|
| 1257 |
get '/update/:id[Int]' => sub { |
| 1258 |
my $id = route_parameters->get('id'); |
| 1259 |
my $entry = resultset( 'Entry' )->find( $id ); |
| 1260 |
var $_ => $entry->$_ foreach qw< title summary content >; |
| 1261 |
template 'create_update', { post_to => uri_for "/update/$id" }; |
| 1262 |
}; |
| 1263 |
|
| 1264 |
As with our route to display a blog entry, we include the type of parameter |
| 1265 |
(C<Int>) that we expect to receive. Dancer2 will issue a C<404> not found |
| 1266 |
error if this parameter is something other than an integer. We also attempt |
| 1267 |
to fetch the row from the C<entries> table identified with the id passed |
| 1268 |
to the application. |
| 1269 |
|
| 1270 |
Once an entry has been retrieved, we populate the same list of variables |
| 1271 |
that we did to redisplay the form when required values were missing earlier. |
| 1272 |
Finally, we create the correct C<post_to> URL for updating a blog entry, and |
| 1273 |
pass it to the template. |
| 1274 |
|
| 1275 |
As with create, we need a POST route to process the blog update: |
| 1276 |
|
| 1277 |
post '/update/:id[Int]' => sub { |
| 1278 |
my $id = route_parameters->get('id'); |
| 1279 |
my $entry = resultset( 'Entry' )->find( $id ); |
| 1280 |
if( !$entry ) { |
| 1281 |
status 'not_found'; |
| 1282 |
return "Attempt to update non-existent entry $id"; |
| 1283 |
} |
| 1284 |
|
| 1285 |
my $params = body_parameters(); |
| 1286 |
var $_ => $params->{ $_ } foreach qw< title summary content >; |
| 1287 |
my @missing = grep { $params->{$_} eq '' } qw< title summary content >; |
| 1288 |
if( @missing ) { |
| 1289 |
var missing => join ",", @missing; |
| 1290 |
warning "Missing parameters: " . var 'missing'; |
| 1291 |
forward "/update/$id", {}, { method => 'GET' }; |
| 1292 |
} |
| 1293 |
|
| 1294 |
try { |
| 1295 |
$entry->update( $params->as_hashref ); |
| 1296 |
} |
| 1297 |
catch( $e ) { |
| 1298 |
error "Database error: $e"; |
| 1299 |
var error_message => 'A database error occurred; your entry could not be updated', |
| 1300 |
forward "/update/$id", {}, { method => 'GET' }; |
| 1301 |
} |
| 1302 |
redirect uri_for "/entry/" . $entry->id; # redirect does not need a return |
| 1303 |
}; |
| 1304 |
|
| 1305 |
An additional check exists here that was unnecessary for create: a check to |
| 1306 |
ensure the blog post to update actually exists. If it doesn't, the proper |
| 1307 |
response is to issue a C<404> not found response to the user: |
| 1308 |
|
| 1309 |
if( !$entry ) { |
| 1310 |
status 'not_found'; |
| 1311 |
return "Attempt to update non-existent entry $id"; |
| 1312 |
} |
| 1313 |
|
| 1314 |
The C<status> keyword sets the proper response code in the response header, |
| 1315 |
and the message in the C<return> sends additional information back to the |
| 1316 |
user. |
| 1317 |
|
| 1318 |
Once the proper blog entry has been loaded, the exact same logic needed |
| 1319 |
to create an entry applies to updating one. |
| 1320 |
|
| 1321 |
=head3 Updating the create form's C<post_to> |
| 1322 |
|
| 1323 |
Simply call C<uri_for> in our route, then pass the resulting value to |
| 1324 |
F<create_update.tt>: |
| 1325 |
|
| 1326 |
get '/create' => sub { |
| 1327 |
# Vars are passed to templates automatically |
| 1328 |
template 'create_update', { post_to => uri_for '/create' }; |
| 1329 |
}; |
| 1330 |
|
| 1331 |
=head2 Deleting a Blog Entry |
| 1332 |
|
| 1333 |
A simple GET route is needed to display information about the route to be |
| 1334 |
deleted: |
| 1335 |
|
| 1336 |
get '/delete/:id[Int]' => sub { |
| 1337 |
my $id = route_parameters->get('id'); |
| 1338 |
my $entry = resultset( 'Entry' )->find( $id ); |
| 1339 |
template 'delete', { entry => $entry }; |
| 1340 |
}; |
| 1341 |
|
| 1342 |
We require a single route parameter: an integer that represents the ID |
| 1343 |
of the blog post we wish to delete. We then attempt to load that entry |
| 1344 |
from the database with the C<find()> method of L<DBIx::Class::ResultSet>, |
| 1345 |
then dump it to our earlier delete template. |
| 1346 |
|
| 1347 |
Speaking of which, let's modify our template to use methods on our resultset |
| 1348 |
object: |
| 1349 |
|
| 1350 |
<% IF entry %> |
| 1351 |
<div id="delete"> |
| 1352 |
<form method="post" action="<% request.uri_for('/delete/' _ entry.id) %>"> |
| 1353 |
<p>Delete entry <% entry.id %>. Are you sure?</p> |
| 1354 |
<div> |
| 1355 |
<input type="radio" id="yes" name="delete_it" value="yes"> |
| 1356 |
<label for="yes">Yes</label> |
| 1357 |
</div> |
| 1358 |
<div class="form-check"> |
| 1359 |
<input type="radio" id="no" name="delete_it" value="no"> |
| 1360 |
<label for="no">No</label> |
| 1361 |
</div><br> |
| 1362 |
<button type="submit">Delete Entry</button> |
| 1363 |
</form> |
| 1364 |
<% ELSE %> |
| 1365 |
<p>Invalid entry.</p> |
| 1366 |
<% END %> |
| 1367 |
</div> |
| 1368 |
|
| 1369 |
Any place we had been using a parameter earlier now calls a corresponding |
| 1370 |
method on the C<entry> object. We've also added a check to display a message |
| 1371 |
if an invalid entry ID was provided. |
| 1372 |
|
| 1373 |
Now, let's write the code to actually perform the delete: |
| 1374 |
|
| 1375 |
post '/delete/:id[Int]' sub { |
| 1376 |
my $id = route_parameters->get('id'); |
| 1377 |
my $entry = resultset( 'Entry' )->find( $id ); |
| 1378 |
if( !$entry ) { |
| 1379 |
status 'not_found'; |
| 1380 |
return "Attempt to delete non-existent entry $id"; |
| 1381 |
} |
| 1382 |
|
| 1383 |
# Always default to not destroying data |
| 1384 |
my $delete_it = body_parameters->get('delete_it') // 0; |
| 1385 |
|
| 1386 |
if( $delete_it ) { |
| 1387 |
$entry->delete; |
| 1388 |
redirect uri_for "/"; |
| 1389 |
} else { |
| 1390 |
# Display our entry again |
| 1391 |
redirect uri_for "/entry/$id"; |
| 1392 |
} |
| 1393 |
}; |
| 1394 |
|
| 1395 |
This uses all of the same techniques and logic we've built previously: |
| 1396 |
|
| 1397 |
=over |
| 1398 |
|
| 1399 |
=item * A route definition that checks the datatype of the ID |
| 1400 |
|
| 1401 |
=item * A check to ensure a blog post with that ID exists |
| 1402 |
|
| 1403 |
=item * The code to safely perform a delete |
| 1404 |
|
| 1405 |
Once a resultset object has been instantiated, calling the C<delete> method |
| 1406 |
removes it from the database. |
| 1407 |
|
| 1408 |
=item * Code to redirect to the entry display if the post isn't deleted |
| 1409 |
|
| 1410 |
=back |
| 1411 |
|
| 1412 |
=head2 Implementation Recap |
| 1413 |
|
| 1414 |
At this point, we've built an app that allows a user to perform the following |
| 1415 |
tasks when writing a blog: |
| 1416 |
|
| 1417 |
=over |
| 1418 |
|
| 1419 |
=item * Creating an entry |
| 1420 |
|
| 1421 |
=item * Editing an existing entry |
| 1422 |
|
| 1423 |
=item * Deleting an entry |
| 1424 |
|
| 1425 |
=item * Listing all blog entries |
| 1426 |
|
| 1427 |
=item * Displaying a single entry |
| 1428 |
|
| 1429 |
=back |
| 1430 |
|
| 1431 |
Congratulations - you've added all the basic functionality! Now, let's secure |
| 1432 |
critical functions of this blog by putting a login in front of them. |
| 1433 |
|
| 1434 |
=head1 Authentication |
| 1435 |
|
| 1436 |
Now that the core functionality is done, we need to secure critical |
| 1437 |
functions; visitors shouldn't be allowed to create or modify content, |
| 1438 |
only authorized users of the Danceyland blog. Dancer2 has several |
| 1439 |
plugins available that help you to add user authentication to your |
| 1440 |
applications; for the Danceyland blog, our needs are rather simple, and |
| 1441 |
so we will use L<Dancer2::Plugin::Auth::Tiny> as our authentication system |
| 1442 |
of choice. |
| 1443 |
|
| 1444 |
L<Dancer2::Plugin::Auth::Tiny> provides some additional syntax to let us |
| 1445 |
easily specify which routes require a logged in user and which do not. It |
| 1446 |
also provides a bit of scaffolding to help us build the actual login |
| 1447 |
procedure. We'll come back to this in a bit. |
| 1448 |
|
| 1449 |
We need a way to keep track of who the logged in user is. For that, we're |
| 1450 |
going to need to set up and work with sessions. |
| 1451 |
|
| 1452 |
=head2 Sessions |
| 1453 |
|
| 1454 |
Sessions allow us to introduce persistence in our web applications. This |
| 1455 |
manifests itself in many different ways, be it remembering the currently |
| 1456 |
logged in user, or remembering form entries between pages on a multi-page |
| 1457 |
form. Sessions give us a mechanism for "remembering" things. |
| 1458 |
|
| 1459 |
Sessions require a storage mechanism to power them. Some common storage |
| 1460 |
engines for sessions include memory caches, files, and databases (SQL and |
| 1461 |
NoSQL both). |
| 1462 |
|
| 1463 |
While sessions are generally managed server side, they can also be found |
| 1464 |
client side in secure cookies and browser local storage. |
| 1465 |
|
| 1466 |
For purposes of this tutorial, we're going to use Dancer2's YAML session |
| 1467 |
engine, L<Dancer2::Session::YAML>. By keeping our sessions in YAML, it's |
| 1468 |
easy to look at the contents of a session while we are developing and |
| 1469 |
debugging the blog. |
| 1470 |
|
| 1471 |
=head3 Setting Up a Session Engine |
| 1472 |
|
| 1473 |
Session engines work much like template engines; there require a little |
| 1474 |
bit of setup in your application's config file, and then they are available |
| 1475 |
for use throughout the application. |
| 1476 |
|
| 1477 |
To set up the YAML session engine, add the following to your F<config.yml>: |
| 1478 |
|
| 1479 |
session: "YAML" |
| 1480 |
|
| 1481 |
engines: |
| 1482 |
session: |
| 1483 |
YAML: |
| 1484 |
cookie_name: dlblog.session |
| 1485 |
|
| 1486 |
You can only have one C<engines> section, so this should be combined with |
| 1487 |
your existing template configuration. The section should now look like: |
| 1488 |
|
| 1489 |
template: "template_toolkit" |
| 1490 |
session: "YAML" |
| 1491 |
engines: |
| 1492 |
template: |
| 1493 |
template_toolkit: |
| 1494 |
# Note: start_tag and end_tag are regexes |
| 1495 |
start_tag: '<%' |
| 1496 |
end_tag: '%>' |
| 1497 |
session: |
| 1498 |
YAML: |
| 1499 |
cookie_name: dlblog.session |
| 1500 |
|
| 1501 |
=head3 Storing and Retrieving Session Data |
| 1502 |
|
| 1503 |
We can use our session to store information across multiple requests. |
| 1504 |
|
| 1505 |
Store session data with the C<session> keyword: |
| 1506 |
|
| 1507 |
session user => 'admin'; |
| 1508 |
|
| 1509 |
Retrieving session data can also be done with the C<session> keyword: |
| 1510 |
|
| 1511 |
my $user = session 'user'; |
| 1512 |
|
| 1513 |
You can verify the username was written to the session by looking at the |
| 1514 |
session file created on disk. If you look in your project directory, you'll |
| 1515 |
notice a new F<sessions/> directory. There should now be exactly one file |
| 1516 |
there: your current session. Run the following: |
| 1517 |
|
| 1518 |
$ cat sessions/<some session id>.yml |
| 1519 |
|
| 1520 |
You'll have a file that looks like: |
| 1521 |
|
| 1522 |
--- |
| 1523 |
user: admin |
| 1524 |
|
| 1525 |
The session filename matches the session ID, which is stored in a cookie |
| 1526 |
that is delivered to the client browser when your application is accessed. |
| 1527 |
If you have the browser developer tools open when you access your |
| 1528 |
development site, you can inspect the cookie and see for yourself. |
| 1529 |
|
| 1530 |
YAML files are great for sessions while developing, but they are not a |
| 1531 |
good choice for production. We'll examine some other options when we |
| 1532 |
discuss deploying to production later in this tutorial. |
| 1533 |
|
| 1534 |
=head2 Storing application users |
| 1535 |
|
| 1536 |
Since we're already using a database to store our blog contents, it only |
| 1537 |
makes sense to track our application users there, too. Let's create a |
| 1538 |
simplistic table to store user data in F<db/users.sql>: |
| 1539 |
|
| 1540 |
CREATE TABLE users ( |
| 1541 |
id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 1542 |
username VARCHAR NOT NULL UNIQUE, |
| 1543 |
password VARCHAR NOT NULL |
| 1544 |
); |
| 1545 |
|
| 1546 |
Then run this from our shell: |
| 1547 |
|
| 1548 |
sqlite3 db/dlblog.db < db/users.sql |
| 1549 |
|
| 1550 |
By declaring password to be an unbounded varchar field, we allow for |
| 1551 |
passwords or passphrases of any length. Notice we don't track admin |
| 1552 |
status, rights, or anything of the like - if you can log in, you can |
| 1553 |
administer the blog. |
| 1554 |
|
| 1555 |
We'll need to regenerate the L<DBIx::Class::Result> classes so we can |
| 1556 |
create objects that represent users. Run the following in your shell from |
| 1557 |
the project directory: |
| 1558 |
|
| 1559 |
dbicdump -o dump_directory=./lib \ |
| 1560 |
-o components='["InflateColumn::DateTime"]' \ |
| 1561 |
DLBlog::Schema dbi:SQLite:db/dlblog.db '{ quote_char => "\"" }' |
| 1562 |
|
| 1563 |
You should have an additional source file in your project directory now, |
| 1564 |
F<lib/DLBlog/Schema/Result/User.pm>. |
| 1565 |
|
| 1566 |
=head2 Password management with Dancer2::Plugin::CryptPassphrase |
| 1567 |
|
| 1568 |
It is best practice to store passwords encrypted, less someone with database |
| 1569 |
access look at your C<users> table and steal account credentials. Rather than |
| 1570 |
roll our own, we'll use one of the many great options on CPAN. |
| 1571 |
|
| 1572 |
L<Dancer2::Plugin::CryptPassphrase> provides convenient access to |
| 1573 |
L<Crypt::Passphrase> in your Dancer2 applications. We'll use the latter |
| 1574 |
to generate a password hash for any new users we create. |
| 1575 |
|
| 1576 |
Install the above modules: |
| 1577 |
|
| 1578 |
cpanm Dancer2::Plugin::CryptPassphrase |
| 1579 |
|
| 1580 |
and add the module to your F<cpanfile>: |
| 1581 |
|
| 1582 |
requires "Dancer2::Plugin::CryptPassphrase"; |
| 1583 |
|
| 1584 |
This extension requires configuration as to which password encoder to |
| 1585 |
use. Add this to the C<plugins> section of the F<environments/development.yml> |
| 1586 |
file: |
| 1587 |
|
| 1588 |
CryptPassphrase: |
| 1589 |
encoder: |
| 1590 |
module: Argon2 |
| 1591 |
parallelism: 2 |
| 1592 |
|
| 1593 |
From your shell, running the following will produce an encrypted password |
| 1594 |
string: |
| 1595 |
|
| 1596 |
perl -MCrypt::Passphrase -E \ |
| 1597 |
'my $auth=Crypt::Passphrase->new(encoder=>"Argon2"); say $auth->hash_password("test")' |
| 1598 |
|
| 1599 |
(substitute any other password for C<test> you'd rather use) |
| 1600 |
|
| 1601 |
That can then be filled in as the password value in the below SQL. From your shell: |
| 1602 |
|
| 1603 |
sqlite3 db/dlblog.db |
| 1604 |
|
| 1605 |
sqlite> INSERT INTO users (username, password) |
| 1606 |
VALUES ( |
| 1607 |
'admin', |
| 1608 |
'$argon2id$v=19$m=262144,t=3,p=1$07krd3DaNn3b9JplNPSjnA$CiFKqjqgecDiYoV0qq0QsZn2GXmORkia2YIhgn/dbBo' |
| 1609 |
); -- admin/test |
| 1610 |
|
| 1611 |
sqlite> .quit |
| 1612 |
|
| 1613 |
=head2 Dancer2::Plugin::Auth::Tiny |
| 1614 |
|
| 1615 |
We also need to install L<Dancer2::Plugin::Auth::Tiny> From your shell: |
| 1616 |
|
| 1617 |
cpanm Dancer2::Plugin::Auth::Tiny |
| 1618 |
|
| 1619 |
Then add this to your F<cpanfile>: |
| 1620 |
|
| 1621 |
requires "Dancer2::Plugin::Auth::Tiny"; |
| 1622 |
|
| 1623 |
=head2 Implementing Login |
| 1624 |
|
| 1625 |
We need two routes to implement the login process: a GET route to display |
| 1626 |
a login form, and a POST route to process the form data. Before that, we |
| 1627 |
need to include the plugins we need for authentication. Below your other |
| 1628 |
C<use> statements, add the following: |
| 1629 |
|
| 1630 |
use Dancer2::Plugin::Auth::Tiny; |
| 1631 |
use Dancer2::Plugin::CryptPassphrase; |
| 1632 |
|
| 1633 |
We'll need some HTML to create a login form. Add the following to a new |
| 1634 |
template file, F<views/login.tt>: |
| 1635 |
|
| 1636 |
<div id="login"> |
| 1637 |
<% IF login_error %> |
| 1638 |
<div> |
| 1639 |
Invalid username or password |
| 1640 |
</div> |
| 1641 |
<% END %> |
| 1642 |
<form method="post" action="<% request.uri_for('/login') %>"> |
| 1643 |
<div> |
| 1644 |
<label for="username">Username</label> |
| 1645 |
<input type="text" name="username" id="username"> |
| 1646 |
</div> |
| 1647 |
<div> |
| 1648 |
<label for="password">Password</label> |
| 1649 |
<input type="password" name="password" id="password"> |
| 1650 |
</div> |
| 1651 |
<input type="hidden" name="return_url" id="return_url" value="<% return_url %>"> |
| 1652 |
<button type="submit">Login</button> |
| 1653 |
</form> |
| 1654 |
</div> |
| 1655 |
|
| 1656 |
Next, we need a route to display the login template: |
| 1657 |
|
| 1658 |
get '/login' => sub { |
| 1659 |
template 'login' => { return_url => params->{ return_url } }; |
| 1660 |
}; |
| 1661 |
|
| 1662 |
If the user tries to access a route that requires a login, and they aren't |
| 1663 |
currently logged in, they are redirected to this C<get '/login'> |
| 1664 |
route, and the URL they originally accessed is stored in a generic parameter |
| 1665 |
named C<return_url>. Upon a successful login attempt, the user will be |
| 1666 |
redirected to the page they were originally trying to gain access to. |
| 1667 |
C<return_url> is stored in the form as a hidden field. |
| 1668 |
|
| 1669 |
Finally, when a login request is submitted, we attempt to validate the |
| 1670 |
login request via a POST route: |
| 1671 |
|
| 1672 |
post '/login' => sub { |
| 1673 |
my $username = body_parameters->get('username'); |
| 1674 |
my $password = body_parameters->get('password'); |
| 1675 |
my $return_url = body_parameters->get('return_url'); |
| 1676 |
|
| 1677 |
my $user = resultset( 'User' )->find({ username => $username }); |
| 1678 |
if ( $user and verify_password( $password, $user->password) ) { |
| 1679 |
app->change_session_id; |
| 1680 |
session user => $username; |
| 1681 |
info "$username successfully logged in"; |
| 1682 |
return redirect $return_url || '/'; |
| 1683 |
} |
| 1684 |
else { |
| 1685 |
warning "Failed login attempt for $username"; |
| 1686 |
template 'login' => { login_error => 1, return_url => $return_url }; |
| 1687 |
} |
| 1688 |
}; |
| 1689 |
|
| 1690 |
We read the form values passed as body parameters, and attempt to look up |
| 1691 |
a user with the provided username using C<find()> with a special invokation; |
| 1692 |
this time, we want to specifically attempt to find a single row based |
| 1693 |
on the value provided to the C<username> column. |
| 1694 |
|
| 1695 |
If a user is found, we use the C<verify_password()> function from |
| 1696 |
L<Crypt::Passphrase> (provided via L<Dancer2::Plugin::CryptPassphrase>) |
| 1697 |
to try to compare password hashes; the passwords themselves are never |
| 1698 |
directly checked against one another. Instead, the password entered by |
| 1699 |
the user is hashed using the same algorithm as when the password was |
| 1700 |
hashed and stored in the database. C<verify_password()> takes two arguments: |
| 1701 |
the password the user entered, and the password hash we previously saved |
| 1702 |
(stored in C<< $user->password >>). If the hashes match, we have validated |
| 1703 |
our user, and we can proceed to log them in. |
| 1704 |
|
| 1705 |
This is where our session comes into play. We can store the name of the user |
| 1706 |
that just authenticated in our session. Any time this user visits the site |
| 1707 |
again, the session engine looks for a valid session with the ID provied in |
| 1708 |
the cookie, and if a session is found, our application will look up the name |
| 1709 |
of the user stored in that session; further activity will be tracked as |
| 1710 |
that logged in user. |
| 1711 |
|
| 1712 |
To accomplish this, we first should generate a new session ID as a matter |
| 1713 |
of good practice. Since the level of security granted is changing, using |
| 1714 |
a new session ID guarantees another browser or user that may have the |
| 1715 |
same session ID isn't accidentally granted admin permissions to our app |
| 1716 |
(this practice stops a whole class of attacks against your webapp). |
| 1717 |
|
| 1718 |
Next, we stash the logged in username in our session via the C<session> |
| 1719 |
keyword, log an audit message (at the C<info> level) that says a user |
| 1720 |
logged in, and finally redirect them to their intended location (or, back |
| 1721 |
to the post listing by default). On future requests, this browser will |
| 1722 |
be treated as being logged in as the provided username. |
| 1723 |
|
| 1724 |
If the password check isn't successful, best practice is to log a message |
| 1725 |
saying a login attempt failed, then redisplaying the login page with an |
| 1726 |
error. |
| 1727 |
|
| 1728 |
=head2 Implementing Logout |
| 1729 |
|
| 1730 |
To logout a user, we need to remove the session for the logged in user, |
| 1731 |
which creates a new session (containing no information about a logged in |
| 1732 |
user) and issues a new cookie with the new session ID. |
| 1733 |
|
| 1734 |
All that is needed is a simple GET route: |
| 1735 |
|
| 1736 |
get '/logout' => sub { |
| 1737 |
app->destroy_session; |
| 1738 |
redirect uri_for "/"; |
| 1739 |
}; |
| 1740 |
|
| 1741 |
In this route, we ask Dancer2 to destroy the user's session, then redirect |
| 1742 |
them to the landing page. When the landing page request is served, a new |
| 1743 |
session is created, and a new cookie delivered to the user's browser. |
| 1744 |
|
| 1745 |
=head2 Securing Routes |
| 1746 |
|
| 1747 |
We earlier established that blog maintenance capabilities should be |
| 1748 |
restricted to logged in/authenticated admin users. For the Danceyland |
| 1749 |
blog, this amounts to: |
| 1750 |
|
| 1751 |
=over |
| 1752 |
|
| 1753 |
=item * Create |
| 1754 |
|
| 1755 |
=item * Update |
| 1756 |
|
| 1757 |
=item * Delete |
| 1758 |
|
| 1759 |
=back |
| 1760 |
|
| 1761 |
L<Dancer2::Plugin::Auth::Tiny> provides us with a little syntactic sugar |
| 1762 |
to make this happen: C<needs login>. |
| 1763 |
|
| 1764 |
You can decorate the appropriate routes as such: |
| 1765 |
|
| 1766 |
get '/create' => needs login => sub { |
| 1767 |
|
| 1768 |
This tells Dancer2 that when this route is accessed, if we don't have a |
| 1769 |
logged in user, redirect them to the C</login> route. |
| 1770 |
|
| 1771 |
=head2 Recap |
| 1772 |
|
| 1773 |
Your finished application code should look like this: |
| 1774 |
|
| 1775 |
package DLBlog; |
| 1776 |
use Dancer2; |
| 1777 |
use Dancer2::Plugin::DBIx::Class; |
| 1778 |
use Dancer2::Plugin::Auth::Tiny; |
| 1779 |
use Dancer2::Plugin::CryptPassphrase; |
| 1780 |
use Feature::Compat::Try; |
| 1781 |
|
| 1782 |
get '/' => sub { |
| 1783 |
# Give us the most recent first |
| 1784 |
my @entries = resultset('Entry')->search( |
| 1785 |
{}, |
| 1786 |
{ order_by => { -desc => 'created_at' } }, |
| 1787 |
)->all; |
| 1788 |
template 'index', { entries => \@entries }; |
| 1789 |
}; |
| 1790 |
|
| 1791 |
get '/entry/:id[Int]' => sub { |
| 1792 |
my $id = route_parameters->get('id'); |
| 1793 |
my $entry = resultset( 'Entry' )->find( $id ); |
| 1794 |
template 'entry', { entry => $entry }; |
| 1795 |
}; |
| 1796 |
|
| 1797 |
get '/create' => needs login => sub { |
| 1798 |
# Vars are passed to templates automatically |
| 1799 |
template 'create_update', { post_to => uri_for '/create' }; |
| 1800 |
}; |
| 1801 |
|
| 1802 |
post '/create' => needs login => sub { |
| 1803 |
my $params = body_parameters(); |
| 1804 |
var $_ => $params->{ $_ } foreach qw< title summary content >; |
| 1805 |
|
| 1806 |
my @missing = grep { $params->{$_} eq '' } qw< title summary content >; |
| 1807 |
if( @missing ) { |
| 1808 |
var missing => join ",", @missing; |
| 1809 |
warning "Missing parameters: " . var 'missing'; |
| 1810 |
forward '/create', {}, { method => 'GET' }; |
| 1811 |
} |
| 1812 |
|
| 1813 |
my $entry = do { |
| 1814 |
try { |
| 1815 |
resultset('Entry')->create( $params->as_hashref ); |
| 1816 |
} |
| 1817 |
catch( $e ) { |
| 1818 |
error "Database error: $e"; |
| 1819 |
var error_message => 'A database error occurred; your entry could not be created', |
| 1820 |
forward '/create', {}, { method => 'GET' }; |
| 1821 |
} |
| 1822 |
}; |
| 1823 |
|
| 1824 |
debug 'Created entry ' . $entry->id . ' for "' . $entry->title . '"'; |
| 1825 |
redirect uri_for "/entry/" . $entry->id; # redirect does not need a return |
| 1826 |
}; |
| 1827 |
|
| 1828 |
get '/update/:id[Int]' => needs login => sub { |
| 1829 |
my $id = route_parameters->get('id'); |
| 1830 |
my $entry = resultset( 'Entry' )->find( $id ); |
| 1831 |
var $_ => $entry->$_ foreach qw< title summary content >; |
| 1832 |
template 'create_update', { post_to => uri_for "/update/$id" }; |
| 1833 |
}; |
| 1834 |
|
| 1835 |
post '/update/:id[Int]' => needs login => sub { |
| 1836 |
my $id = route_parameters->get('id'); |
| 1837 |
my $entry = resultset( 'Entry' )->find( $id ); |
| 1838 |
if( !$entry ) { |
| 1839 |
status 'not_found'; |
| 1840 |
return "Attempt to update non-existent entry $id"; |
| 1841 |
} |
| 1842 |
|
| 1843 |
my $params = body_parameters(); |
| 1844 |
var $_ => $params->{ $_ } foreach qw< title summary content >; |
| 1845 |
my @missing = grep { $params->{$_} eq '' } qw< title summary content >; |
| 1846 |
if( @missing ) { |
| 1847 |
var missing => join ",", @missing; |
| 1848 |
warning "Missing parameters: " . var 'missing'; |
| 1849 |
forward "/update/$id", {}, { method => 'GET' }; |
| 1850 |
} |
| 1851 |
|
| 1852 |
try { |
| 1853 |
$entry->update( $params->as_hashref ); |
| 1854 |
} |
| 1855 |
catch( $e ) { |
| 1856 |
error "Database error: $e"; |
| 1857 |
var error_message => 'A database error occurred; your entry could not be updated', |
| 1858 |
forward "/update/$id", {}, { method => 'GET' }; |
| 1859 |
} |
| 1860 |
|
| 1861 |
debug 'Updated entry ' . $entry->id . ' for "' . $entry->title . '"'; |
| 1862 |
redirect uri_for "/entry/" . $entry->id; # redirect does not need a return |
| 1863 |
}; |
| 1864 |
|
| 1865 |
get '/delete/:id[Int]' => needs login => sub { |
| 1866 |
my $id = route_parameters->get('id'); |
| 1867 |
my $entry = resultset( 'Entry' )->find( $id ); |
| 1868 |
template 'delete', { entry => $entry }; |
| 1869 |
}; |
| 1870 |
|
| 1871 |
post '/delete/:id[Int]' => needs login => sub { |
| 1872 |
my $id = route_parameters->get('id'); |
| 1873 |
my $entry = resultset( 'Entry' )->find( $id ); |
| 1874 |
if( !$entry ) { |
| 1875 |
status 'not_found'; |
| 1876 |
return "Attempt to delete non-existent entry $id"; |
| 1877 |
} |
| 1878 |
|
| 1879 |
# Always default to not destroying data |
| 1880 |
my $delete_it = body_parameters->get('delete_it') // 0; |
| 1881 |
|
| 1882 |
if( $delete_it ) { |
| 1883 |
$entry->delete; |
| 1884 |
redirect uri_for "/"; |
| 1885 |
} else { |
| 1886 |
# Display our entry again |
| 1887 |
redirect uri_for "/entry/$id"; |
| 1888 |
} |
| 1889 |
}; |
| 1890 |
|
| 1891 |
get '/login' => sub { |
| 1892 |
template 'login' => { return_url => params->{ return_url } }; |
| 1893 |
}; |
| 1894 |
|
| 1895 |
post '/login' => sub { |
| 1896 |
my $username = body_parameters->get('username'); |
| 1897 |
my $password = body_parameters->get('password'); |
| 1898 |
my $return_url = body_parameters->get('return_url'); |
| 1899 |
|
| 1900 |
my $user = resultset( 'User' )->find({ username => $username }); |
| 1901 |
if ( $user and verify_password( $password, $user->password) ) { |
| 1902 |
app->change_session_id; |
| 1903 |
session user => $username; |
| 1904 |
info "$username successfully logged in"; |
| 1905 |
return redirect $return_url || '/'; |
| 1906 |
} |
| 1907 |
else { |
| 1908 |
warning "Failed login attempt for $username"; |
| 1909 |
template 'login' => { login_error => 1, return_url => $return_url }; |
| 1910 |
} |
| 1911 |
}; |
| 1912 |
|
| 1913 |
get '/logout' => sub { |
| 1914 |
app->destroy_session; |
| 1915 |
redirect uri_for "/"; |
| 1916 |
}; |
| 1917 |
|
| 1918 |
true; |
| 1919 |
|
| 1920 |
=head1 Finishing Touches |
| 1921 |
|
| 1922 |
At this point, Danceyland has a fully functional blog engine, and your |
| 1923 |
users are chomping at the bit to start using it. Before we let them loose |
| 1924 |
on your new creation, let's pretty it up, write some tests, and get it |
| 1925 |
deployed to a production environment. |
| 1926 |
|
| 1927 |
=head2 Adding some style |
| 1928 |
|
| 1929 |
We've written all of our views up to this point with basic HTML; no effort |
| 1930 |
has been made to style our blog or make it attractive. That is beyond the |
| 1931 |
scope of this tutorial. |
| 1932 |
|
| 1933 |
If you clone the tutorial repository, you'll notice that all views have |
| 1934 |
styling markup that isn't provided in the tutorial. This was done to |
| 1935 |
show you one way styling could be done, and to give you an attractive |
| 1936 |
example application to learn from. |
| 1937 |
|
| 1938 |
L<Bootstrap|https://getbootstrap.com> was used to provide styling for the |
| 1939 |
tutorial; it's well known, easy to understand, and easy to find help for. |
| 1940 |
If you want to learn more about how Bootstrap works, check out their |
| 1941 |
website for more details. |
| 1942 |
|
| 1943 |
=head1 Testing Your Application |
| 1944 |
|
| 1945 |
When developing your application, writing and running tests helps you |
| 1946 |
work through difficult parts of your application, and allows you to |
| 1947 |
verify that your Dancer2 application is behaving as you designed it |
| 1948 |
to. In a production environment, running tests before installation or |
| 1949 |
upgrade help ensure there are no surprises when you start/restart the |
| 1950 |
application server. Let's see how we can write some basic functionality |
| 1951 |
tests. |
| 1952 |
|
| 1953 |
=head2 Using Test::WWW::Mechanize::PSGI |
| 1954 |
|
| 1955 |
L<Test::WWW::Mechanize::PSGI> lets us test our Dancer2 applications without |
| 1956 |
having to spin up a test web server. It is loaded with convenience methods |
| 1957 |
to make it easy to navigate and test our Plack/PSGI applications. Run the |
| 1958 |
following to install this from your shell: |
| 1959 |
|
| 1960 |
cpanm Test::WWW::Mechanize::PSGI |
| 1961 |
|
| 1962 |
It must also be added to the C<on "test"> section of your F<cpanfile>: |
| 1963 |
|
| 1964 |
requires "Test::WWW::Mechanize::PSGI" => "0"; |
| 1965 |
|
| 1966 |
Before we do any testing for our blog, we'll need to create some testing |
| 1967 |
infrastructure so we don't step on any of our production or test data. |
| 1968 |
We need a testing database to run tests against so we don't corrupt |
| 1969 |
other development or production data. In your shell, run the following: |
| 1970 |
|
| 1971 |
mkdir t/db |
| 1972 |
cp db/dlblog.db t/db/test.db |
| 1973 |
|
| 1974 |
(or, you can use the test database that ships with the DLBlog GitHub |
| 1975 |
repository) |
| 1976 |
|
| 1977 |
You'll also need a config file that is representative of your testing |
| 1978 |
environment. Create F<environments/test.yml> and add the following: |
| 1979 |
|
| 1980 |
logger: "console" |
| 1981 |
log: "warning" |
| 1982 |
show_stacktrace: 0 |
| 1983 |
no_server_tokens: 1 |
| 1984 |
|
| 1985 |
plugins: |
| 1986 |
DBIx::Class: |
| 1987 |
default: |
| 1988 |
dsn: "dbi:SQLite:dbname=t/db/test.db" |
| 1989 |
schema_class: "DLBlog::Schema" |
| 1990 |
dbi_params: |
| 1991 |
RaiseError: 1 |
| 1992 |
AutoCommit: 1 |
| 1993 |
CryptPassphrase: |
| 1994 |
encoder: |
| 1995 |
module: Argon2 |
| 1996 |
parallelism: 2 |
| 1997 |
|
| 1998 |
This is a hybrid of your production and development configs: |
| 1999 |
|
| 2000 |
=over |
| 2001 |
|
| 2002 |
=item * It still logs to the console, but at a higher level so only errors are seen |
| 2003 |
|
| 2004 |
=item * We hide any stacktraces and disable server tokens/headers |
| 2005 |
|
| 2006 |
=item * We tell DBIx::Class to look at our test database |
| 2007 |
|
| 2008 |
=back |
| 2009 |
|
| 2010 |
To run the default tests from your shell: |
| 2011 |
|
| 2012 |
DANCER_ENVIRONMENT=test prove -lv |
| 2013 |
|
| 2014 |
This runs all tests in the F<t/> subdirectory with maximum verbosity, and |
| 2015 |
runs with our test environment configuration. |
| 2016 |
|
| 2017 |
Dancer2 creates applications with two default tests. The first, |
| 2018 |
F<t/001_base.t>, ensures that your Dancer2 application compiles successfully |
| 2019 |
without errors. The other test, F<t/002_index_route.t>, ensures that the |
| 2020 |
default route of your application is accessible. These are the two most |
| 2021 |
basic tests an application can have, and validate very little about the |
| 2022 |
functionality of your app. We're going to make two new tests: one just to |
| 2023 |
test the nuances of the login process (as security is critical), and another |
| 2024 |
to test basic blog functionality. |
| 2025 |
|
| 2026 |
=head2 Login Tests |
| 2027 |
|
| 2028 |
Let's verify the login process behaves as intended. Edit F<t/003_login.t> |
| 2029 |
and add the following: |
| 2030 |
|
| 2031 |
use strict; |
| 2032 |
use warnings; |
| 2033 |
use Test::More; |
| 2034 |
use Test::WWW::Mechanize::PSGI; |
| 2035 |
|
| 2036 |
use DLBlog; |
| 2037 |
my $mech = Test::WWW::Mechanize::PSGI->new( |
| 2038 |
app => DLBlog->to_app, |
| 2039 |
); |
| 2040 |
|
| 2041 |
$mech->get_ok('/create', 'Got /create while not logged in'); |
| 2042 |
$mech->content_contains('Password', '...and was presented with a login page'); |
| 2043 |
$mech->submit_form_ok({ |
| 2044 |
fields => { |
| 2045 |
username => 'admin', |
| 2046 |
password => 'foobar', |
| 2047 |
}}, '...which we gave invalid credentials'); |
| 2048 |
$mech->content_contains('Invalid username or password', '...and gave us an appropriate error'); |
| 2049 |
$mech->submit_form_ok({ |
| 2050 |
fields => { |
| 2051 |
username => 'admin', |
| 2052 |
password => 'test', |
| 2053 |
}}, '...so we give it real credentials'); |
| 2054 |
$mech->content_contains('form', '...and get something that looks like the create form' ); |
| 2055 |
$mech->content_contains('Content', 'Confirmed this is the create form'); |
| 2056 |
|
| 2057 |
done_testing; |
| 2058 |
|
| 2059 |
We load two test modules: L<Test::More>, which provides a basic set of test |
| 2060 |
functionality, and L<Test::WWW::Mechanize::PSGI>, which will do all our heavy |
| 2061 |
lifting. |
| 2062 |
|
| 2063 |
To start, we need to create an instance of a Mechanize object: |
| 2064 |
|
| 2065 |
my $mech = Test::WWW::Mechanize::PSGI->new( |
| 2066 |
app => DLBlog->to_app, |
| 2067 |
); |
| 2068 |
|
| 2069 |
This creates an instance of the Mechanize user agent, and points it at an |
| 2070 |
instance of the Danceyland blog app (C<DLBlog>). |
| 2071 |
|
| 2072 |
We've specified that some routes can't be accessed by unauthorized/non-logged |
| 2073 |
in users. Let's test this: |
| 2074 |
|
| 2075 |
$mech->get_ok('/create', 'Got /create while not logged in'); |
| 2076 |
$mech->content_contains('Password', '...and was presented with a login page'); |
| 2077 |
|
| 2078 |
This tests the C<needs login> condition on the C</create> route. We should |
| 2079 |
be taken to a login page if we haven't logged in. C<get_ok> ensures the |
| 2080 |
route is accessible, and C<content_contains> looks for a password field. |
| 2081 |
|
| 2082 |
We should get an error message for a failed login attempt. Let's stuff |
| 2083 |
the form with invalid credentials and verify that: |
| 2084 |
|
| 2085 |
$mech->submit_form_ok({ |
| 2086 |
fields => { |
| 2087 |
username => 'admin', |
| 2088 |
password => 'foobar', |
| 2089 |
}}, '...which we gave invalid credentials'); |
| 2090 |
$mech->content_contains('Invalid username or password', '...and gave us an appropriate error'); |
| 2091 |
|
| 2092 |
C<submit_form_ok> takes a hashref of fields and puts the specified values |
| 2093 |
into them, then clicks the appropriate submit button. We then check the |
| 2094 |
resulting page content to confirm that we do, in fact, see the invalid |
| 2095 |
username/password error message. |
| 2096 |
|
| 2097 |
We know that login handles failed attempts ok now. How about a login with |
| 2098 |
valid credentials> |
| 2099 |
|
| 2100 |
$mech->submit_form_ok({ |
| 2101 |
fields => { |
| 2102 |
username => 'admin', |
| 2103 |
password => 'test', |
| 2104 |
}}, '...so we give it real credentials'); |
| 2105 |
$mech->content_contains('form', '...and get something that looks like the create form' ); |
| 2106 |
$mech->content_contains('Content', 'Confirmed this is the create form'); |
| 2107 |
|
| 2108 |
We pass the default admin/test credentials, then look at the page we're |
| 2109 |
taken to. The create page should have a form, and one of the fields should |
| 2110 |
be named Content. C<content_contains> looks for both of these on the |
| 2111 |
resulting page, and passes if they are present. |
| 2112 |
|
| 2113 |
Finally, we need to say we're done running tests: |
| 2114 |
|
| 2115 |
done_testing; |
| 2116 |
|
| 2117 |
Now that it's done, let's run just this one test. From your shell: |
| 2118 |
|
| 2119 |
DANCER_ENVIRONMENT=test prove -lv t/003_login.t |
| 2120 |
|
| 2121 |
And you should see the following output: |
| 2122 |
|
| 2123 |
t/003_login.t .. |
| 2124 |
ok 1 - Got /create while not logged in |
| 2125 |
ok 2 - ...and was presented with a login page |
| 2126 |
[DLBlog:2287783] warning @2025-02-06 22:34:25> Failed login attempt for admin in /path/to/DLBlog/lib/DLBlog.pm l. 134 |
| 2127 |
ok 3 - ...which we gave invalid credentials |
| 2128 |
ok 4 - ...and gave us an appropriate error |
| 2129 |
ok 5 - ...so we give it real credentials |
| 2130 |
ok 6 - ...and get something that looks like the create form |
| 2131 |
ok 7 - Confirmed this is the create form |
| 2132 |
1..7 |
| 2133 |
ok |
| 2134 |
All tests successful. |
| 2135 |
Files=1, Tests=7, 1 wallclock secs ( 0.02 usr 0.00 sys + 0.92 cusr 0.10 csys = 1.04 CPU) |
| 2136 |
Result: PASS |
| 2137 |
|
| 2138 |
The labels help us see which tests are running, making it easier to examine |
| 2139 |
failures when they happen. You'll see a log message produced when our login |
| 2140 |
attempt failed, and a C<PASS> at the end showing all tests were successfully |
| 2141 |
run. |
| 2142 |
|
| 2143 |
=head2 Blog Tests |
| 2144 |
|
| 2145 |
Using the same techniques we learned writing the login test, we'll make |
| 2146 |
a test for basic blog functionality. The complete test will run through |
| 2147 |
a basic workflow of the Danceyland blog: |
| 2148 |
|
| 2149 |
=over |
| 2150 |
|
| 2151 |
=item * Login |
| 2152 |
|
| 2153 |
=item * Create an entry |
| 2154 |
|
| 2155 |
=item * Edit an entry |
| 2156 |
|
| 2157 |
=item * Delete an entry |
| 2158 |
|
| 2159 |
=back |
| 2160 |
|
| 2161 |
Add the following to F<t/004_blog.t> in your project directory: |
| 2162 |
|
| 2163 |
use strict; |
| 2164 |
use warnings; |
| 2165 |
use Test::More; |
| 2166 |
use Test::WWW::Mechanize::PSGI; |
| 2167 |
|
| 2168 |
use DLBlog; |
| 2169 |
my $mech = Test::WWW::Mechanize::PSGI->new( |
| 2170 |
app => DLBlog->to_app, |
| 2171 |
); |
| 2172 |
|
| 2173 |
subtest 'Landing page' => sub { |
| 2174 |
$mech->get_ok('/', 'Got landing page'); |
| 2175 |
$mech->title_is('Danceyland Blog', '...for our blog'); |
| 2176 |
$mech->content_contains('Test Blog Post','...and it has a test post'); |
| 2177 |
}; |
| 2178 |
|
| 2179 |
subtest 'Login' => sub { |
| 2180 |
$mech->get_ok('/login', 'Visit login page to make some changes'); |
| 2181 |
$mech->submit_form_ok({ |
| 2182 |
fields => { |
| 2183 |
username => 'admin', |
| 2184 |
password => 'test', |
| 2185 |
}}, '...so we give it a user'); |
| 2186 |
}; |
| 2187 |
|
| 2188 |
subtest 'Create' => sub { |
| 2189 |
$mech->get_ok('/create', 'Write a new blog post'); |
| 2190 |
$mech->submit_form_ok({ |
| 2191 |
fields => { |
| 2192 |
title => 'Another Test Post', |
| 2193 |
summary => 'Writing a blog post can be done by tests too', |
| 2194 |
content => 'You can create blog entries programmatically with Perl!', |
| 2195 |
}}, '...then write another post'); |
| 2196 |
$mech->base_like( qr</entry/\d+$>, '...and get redirected to the new entry' ); |
| 2197 |
}; |
| 2198 |
|
| 2199 |
my $entry_id; |
| 2200 |
subtest 'Update' => sub { |
| 2201 |
($entry_id) = $mech->uri =~ m</(\d+)$>; |
| 2202 |
$mech->get_ok("/update/$entry_id", 'Navigating to the update page for this post'); |
| 2203 |
$mech->submit_form_ok({ |
| 2204 |
fields => { |
| 2205 |
title => 'Yet ANOTHER Test Post', |
| 2206 |
}}, '...then update yet another post'); |
| 2207 |
$mech->base_like( qr</entry/${entry_id}$>, '...and get redirected to the entry page' ); |
| 2208 |
$mech->has_tag('h1','Yet ANOTHER Test Post', '...and it has the updated title'); |
| 2209 |
}; |
| 2210 |
|
| 2211 |
subtest 'Delete' => sub { |
| 2212 |
$mech->get_ok("/delete/$entry_id", "Go delete page for new entry"); |
| 2213 |
$mech->submit_form_ok({ |
| 2214 |
fields => { |
| 2215 |
delete_it => 'yes', |
| 2216 |
}}, '...then delete it!'); |
| 2217 |
$mech->get_ok("/entry/$entry_id", '...then try to navigate to the entry'); |
| 2218 |
$mech->content_contains('Invalid entry','...and see the post is no longer there'); |
| 2219 |
}; |
| 2220 |
|
| 2221 |
done_testing; |
| 2222 |
|
| 2223 |
You'll notice that this time we have organized tests into multiple subtests |
| 2224 |
that keep related tests together. While this isn't necessary, it can be |
| 2225 |
helpful when working on large test files. |
| 2226 |
|
| 2227 |
This test introduces us to some additional types of tests: |
| 2228 |
|
| 2229 |
=over |
| 2230 |
|
| 2231 |
=item * C<base_like> |
| 2232 |
|
| 2233 |
This test method examines the resulting URL from the previous Mechanize |
| 2234 |
operation. In the C<Create> subtest, we submit a blog entry, and we should |
| 2235 |
be taken to the view page for the new entry. By checking the resulting URL, |
| 2236 |
we can verify that we were taken to the view page after the post was created. |
| 2237 |
|
| 2238 |
=item * C<uri> |
| 2239 |
|
| 2240 |
This returns the full URI of the previous Mechanize operation. From this URI, |
| 2241 |
we can extract the ID of the last blog entry we created. We'll need this |
| 2242 |
to test the update and delete operations. |
| 2243 |
|
| 2244 |
=item * C<has_tag> |
| 2245 |
|
| 2246 |
This method looks for a tag matching the type specified, and checks to see |
| 2247 |
if the text in that tag matches what is specified in the test. Our C<h1> on |
| 2248 |
the entry page should have the blog post title, and in the update test, |
| 2249 |
we check to see that the updated title is present. |
| 2250 |
|
| 2251 |
=back |
| 2252 |
|
| 2253 |
Run the test from your shell: |
| 2254 |
|
| 2255 |
DANCER_ENVIRONMENT=test prove -lv t/004_blog.t |
| 2256 |
|
| 2257 |
And you should see the following output: |
| 2258 |
|
| 2259 |
t/004_blog.t .. |
| 2260 |
# Subtest: Landing page |
| 2261 |
ok 1 - Got landing page |
| 2262 |
ok 2 - ...for our blog |
| 2263 |
ok 3 - ...and it has a test post |
| 2264 |
1..3 |
| 2265 |
ok 1 - Landing page |
| 2266 |
# Subtest: Login |
| 2267 |
ok 1 - Visit login page to make some changes |
| 2268 |
ok 2 - ...so we give it a user |
| 2269 |
1..2 |
| 2270 |
ok 2 - Login |
| 2271 |
# Subtest: Create |
| 2272 |
ok 1 - Write a new blog post |
| 2273 |
ok 2 - ...then write another post |
| 2274 |
ok 3 - ...and get redirected to the new entry |
| 2275 |
1..3 |
| 2276 |
ok 3 - Create |
| 2277 |
# Subtest: Update |
| 2278 |
ok 1 - Navigating to the update page for this post |
| 2279 |
ok 2 - ...then update yet another post |
| 2280 |
ok 3 - ...and get redirected to the entry page |
| 2281 |
ok 4 - ...and it has the updated title |
| 2282 |
1..4 |
| 2283 |
ok 4 - Update |
| 2284 |
# Subtest: Delete |
| 2285 |
ok 1 - Go delete page for new entry |
| 2286 |
ok 2 - ...then delete it! |
| 2287 |
ok 3 - ...then try to navigate to the entry |
| 2288 |
ok 4 - ...and see the post is no longer there |
| 2289 |
1..4 |
| 2290 |
ok 5 - Delete |
| 2291 |
1..5 |
| 2292 |
ok |
| 2293 |
All tests successful. |
| 2294 |
Files=1, Tests=5, 1 wallclock secs ( 0.01 usr 0.01 sys + 0.77 cusr 0.10 csys = 0.89 CPU) |
| 2295 |
Result: PASS |
| 2296 |
|
| 2297 |
You'll notice that not only is the code conveniently grouped by subtest, |
| 2298 |
but so is the output. |
| 2299 |
|
| 2300 |
There's a lot more you can test still. Look for some additional ideas at |
| 2301 |
the end of this tutorial. |
| 2302 |
|
| 2303 |
=head1 Deployment |
| 2304 |
|
| 2305 |
We've built the application, and written some basic tests to ensure the |
| 2306 |
application can function properly. Now, let's put it on a server and |
| 2307 |
make it available to the public! |
| 2308 |
|
| 2309 |
=head2 Creating Production Configuration |
| 2310 |
|
| 2311 |
The default Dancer2 configuration provides a lot of information to the |
| 2312 |
developer to assist in debugging while creating an application. In a |
| 2313 |
production environment, there's too much information being given that can |
| 2314 |
be used by someone trying to compromise your application. Let's create |
| 2315 |
an environment specifically for production to turn the level of detail down. |
| 2316 |
|
| 2317 |
If you were using a database server instead of SQLite, you'd want to update |
| 2318 |
database credentials in your production configuration to point to your |
| 2319 |
production database server. |
| 2320 |
|
| 2321 |
Replace your F<environments/production.yml> file with the following: |
| 2322 |
|
| 2323 |
# configuration file for production environment |
| 2324 |
behind_proxy: 1 |
| 2325 |
|
| 2326 |
# only log info, warning and error messsages |
| 2327 |
log: "info" |
| 2328 |
|
| 2329 |
# log message to a file in logs/ |
| 2330 |
logger: "file" |
| 2331 |
|
| 2332 |
# hide errors |
| 2333 |
show_stacktrace: 0 |
| 2334 |
|
| 2335 |
# disable server tokens in production environments |
| 2336 |
no_server_tokens: 1 |
| 2337 |
|
| 2338 |
# Plugin configuration |
| 2339 |
plugins: |
| 2340 |
DBIx::Class: |
| 2341 |
default: |
| 2342 |
dsn: "dbi:SQLite:dbname=db/dlblog.db" |
| 2343 |
schema_class: "DLBlog::Schema" |
| 2344 |
dbi_params: |
| 2345 |
RaiseError: 1 |
| 2346 |
AutoCommit: 1 |
| 2347 |
CryptPassphrase: |
| 2348 |
encoder: |
| 2349 |
module: Argon2 |
| 2350 |
parallelism: 2 |
| 2351 |
|
| 2352 |
Changes include: |
| 2353 |
|
| 2354 |
=over |
| 2355 |
|
| 2356 |
=item * Running behind a reverse proxy |
| 2357 |
|
| 2358 |
We're going to deploy our application in conjunction with NGINX; running |
| 2359 |
in this manner requires Dancer2 to interact and set HTTP headers |
| 2360 |
differently than it would running standalone. This setting tells |
| 2361 |
Dancer2 to behave as it should behind an NGINX (or other) reverse proxy. |
| 2362 |
|
| 2363 |
=item * Logging only informational or more severe messages |
| 2364 |
|
| 2365 |
In a production environment, logging debugging and core Dancer2 messages |
| 2366 |
is rarely needed. |
| 2367 |
|
| 2368 |
=item * Logging to a file |
| 2369 |
|
| 2370 |
Servers will be running in the background, not in a console window. As |
| 2371 |
such, a place to catch log messages will be needed. File logs can also be |
| 2372 |
shipped to another service (such as Kibana) for analysis. |
| 2373 |
|
| 2374 |
=item * No stacktraces |
| 2375 |
|
| 2376 |
If a fatal error occurs, the stacktraces produced by Dancer2 provide a |
| 2377 |
potential attacker with information about the insides of your application. |
| 2378 |
By setting C<show_stacktrace> to C<0>, all errors show only the |
| 2379 |
F<public/500.html> page. |
| 2380 |
|
| 2381 |
=item * Disabling server tokens |
| 2382 |
|
| 2383 |
Setting C<no_server_tokens> prevents Dancer2 from adding the |
| 2384 |
C<X-Powered-By> header and, when using Dancer2's standalone server, from |
| 2385 |
setting the C<Server> header to the Dancer2 version. |
| 2386 |
|
| 2387 |
Does not touch the C<Server> header when running under an external PSGI |
| 2388 |
server. |
| 2389 |
|
| 2390 |
=back |
| 2391 |
|
| 2392 |
Our plugin configuration remains the same from the development environment. |
| 2393 |
|
| 2394 |
=head2 Installing the Danceyland Blog |
| 2395 |
|
| 2396 |
On your production server, make sure you have a version of Perl installed, |
| 2397 |
and copy your project files to the server by whichever means makes sense |
| 2398 |
for your situation. |
| 2399 |
|
| 2400 |
Run the following from within the project directory to install the |
| 2401 |
application's dependencies: |
| 2402 |
|
| 2403 |
cpanm --installdeps . --with-test --with-all-features |
| 2404 |
|
| 2405 |
Get a cup of coffee while this runs; when you come back, resolve any |
| 2406 |
dependency issues, then run your tests to make sure the Danceyland blog |
| 2407 |
is functional: |
| 2408 |
|
| 2409 |
DANCER_ENVIRONMENT=test prove -l |
| 2410 |
|
| 2411 |
Your output should resemble: |
| 2412 |
|
| 2413 |
./t/001_base.t ......... ok |
| 2414 |
./t/002_index_route.t .. ok |
| 2415 |
./t/003_login.t ........ 1/? [DLBlog:2291513] warning @2025-02-06 22:59:09> Failed login attempt for admin in /path/to/DLBlog/lib/DLBlog.pm l. 134 |
| 2416 |
./t/003_login.t ........ ok |
| 2417 |
./t/004_blog.t ......... |
| 2418 |
# Subtest: Landing page |
| 2419 |
./t/004_blog.t ......... 1/? # Subtest: Login |
| 2420 |
./t/004_blog.t ......... 2/? # Subtest: Create |
| 2421 |
# Subtest: Update |
| 2422 |
# Subtest: Delete |
| 2423 |
./t/004_blog.t ......... ok |
| 2424 |
All tests successful. |
| 2425 |
Files=4, Tests=15, 3 wallclock secs ( 0.02 usr 0.00 sys + 2.30 cusr 0.32 csys = 2.64 CPU) |
| 2426 |
Result: PASS |
| 2427 |
|
| 2428 |
=head2 Deploying with a PSGI Server |
| 2429 |
|
| 2430 |
C<plackup>, by defaults, runs a development server for developing your |
| 2431 |
application. It is not suitable for any public-facing deployment. |
| 2432 |
|
| 2433 |
There are a number of great options available on the L<Plack|https://plackperl.org/> |
| 2434 |
website. For our example, we'll use L<Starman>, as it offers reasonable |
| 2435 |
performance and functions on nearly any server OS. |
| 2436 |
|
| 2437 |
We'll pair Starman with L<Server::Starter>, which will give you a robust |
| 2438 |
way to manage server processes. |
| 2439 |
|
| 2440 |
Install both of these modules: |
| 2441 |
|
| 2442 |
cpanm Starman Server::Starter |
| 2443 |
|
| 2444 |
And add them to the blog's F<cpanfile>: |
| 2445 |
|
| 2446 |
requires "Starman"; |
| 2447 |
requires "Server::Starter"; |
| 2448 |
|
| 2449 |
Assuming we're deploying to a Debian server, the following can be used to |
| 2450 |
start the Danceyland blog in the background: |
| 2451 |
|
| 2452 |
sudo start_server \ |
| 2453 |
--daemonize \ |
| 2454 |
--dir=/path/to/DLBlog \ |
| 2455 |
--port=5000 \ |
| 2456 |
--log-file=/var/log/dlblog.log \ |
| 2457 |
--pid-file=/var/run/dlblog.pid \ |
| 2458 |
--status-file=/var/run/dlblog.status \ |
| 2459 |
-- plackup -s Starman--user www-data --group www-data -E production \ |
| 2460 |
bin/app.psgi |
| 2461 |
|
| 2462 |
Once operational, the server can be restarted with: |
| 2463 |
|
| 2464 |
start_server --restart --pid-file=/var/run/dlblog.pid --status-file=/var/run/dlblog.status |
| 2465 |
|
| 2466 |
Or stopped with: |
| 2467 |
|
| 2468 |
start_server --stop --pid-file=/var/run/dlblog.pid |
| 2469 |
|
| 2470 |
=head2 Configuring Reverse Proxy with NGINX |
| 2471 |
|
| 2472 |
Finally, let's put NGINX in front of our Dancer2 application. This will |
| 2473 |
improve the security and performance of our application: |
| 2474 |
|
| 2475 |
server { |
| 2476 |
listen 80; |
| 2477 |
server_name example.com; |
| 2478 |
|
| 2479 |
location / { |
| 2480 |
proxy_pass http://127.0.0.1:5000; |
| 2481 |
proxy_set_header Host $host; |
| 2482 |
proxy_set_header X-Real-IP $remote_addr; |
| 2483 |
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; |
| 2484 |
} |
| 2485 |
} |
| 2486 |
|
| 2487 |
If this server is public facing, you should also configure it with HTTPS; |
| 2488 |
L<Let's Encrypt/https://letsencrypt.org> makes this free and easy. |
| 2489 |
|
| 2490 |
More advanced setups are possible (like serving static content from NGINX |
| 2491 |
instead of Dancer2), but that is beyond the scope of this tutorial. |
| 2492 |
|
| 2493 |
=head1 What You've Built |
| 2494 |
|
| 2495 |
Congratulations! You have built a primitive but very functional blog |
| 2496 |
engine that protects maintenance functions behind a user login, using |
| 2497 |
L<Dancer2> and other plugins and modules in its ecosystem. You've learned |
| 2498 |
a number of important building blocks that will be crucial for building |
| 2499 |
other applications. |
| 2500 |
|
| 2501 |
=head1 Where to Go Next |
| 2502 |
|
| 2503 |
This application can be used as a springboard and reference for future |
| 2504 |
L<Dancer2> projects. There are still a number of improvements and additional |
| 2505 |
features that can be added to this blog. A few ideas include: |
| 2506 |
|
| 2507 |
=over |
| 2508 |
|
| 2509 |
=item Paginate the list of blog entries |
| 2510 |
|
| 2511 |
After a while, the list of blog entries can get long. Using L<Data::Page> |
| 2512 |
or other Perl modules, break the list of entries into reasonable page |
| 2513 |
sizes to more easily and quickly navigate. |
| 2514 |
|
| 2515 |
=item Add a search function to the blog |
| 2516 |
|
| 2517 |
Add a search bar to the UI, then use the C<search()> method in |
| 2518 |
L<DBIx::Class> to find blog entries based on what the used input. |
| 2519 |
|
| 2520 |
=item Improve application security by sanitizing input parameters |
| 2521 |
|
| 2522 |
Using a regex or a validation framework (such as |
| 2523 |
L<Dancer2::Plugin::DataTransposeValidator>), scrub all input before using |
| 2524 |
it in a database operation. |
| 2525 |
|
| 2526 |
=item Use database slugs in URLs instead of IDs |
| 2527 |
|
| 2528 |
A database slug is a human-readable identifier (such as a URL encoding of |
| 2529 |
the entry title) that can be used to identify an entry rather than the |
| 2530 |
numerical ID. They are easier to remember than IDs, are better for SEO of |
| 2531 |
your content, and makes your application more secure by hiding some database |
| 2532 |
implementation details from an attacker (such as a row ID). |
| 2533 |
|
| 2534 |
=item Move business logic to business layer; call business object from Dancer2 |
| 2535 |
|
| 2536 |
In larger applications, business logic (like creating a blog post) may |
| 2537 |
be put in an object (such as L<DBIx::Class::Result> or L<DBIx::Class::ResultSet> |
| 2538 |
objects, or other L<Moo> or L<Moose> objects), and that object gets |
| 2539 |
instantiated and called from Dancer2. This helps to decouple tasks in an |
| 2540 |
application, and allows for better testing of business logic. |
| 2541 |
|
| 2542 |
=item Write more tests to catch error conditions for our blog |
| 2543 |
|
| 2544 |
What happens when you pass a string to a route expecting an ID? What happens |
| 2545 |
when you don't fill out all the fields on the create or update pages? |
| 2546 |
Write tests to check these conditions using what you've learned from |
| 2547 |
writing the existing tests, and make sure the error handling behaves as |
| 2548 |
expected. |
| 2549 |
|
| 2550 |
=back |
| 2551 |
|
| 2552 |
For another example of a blog engine in Dancer2, check out |
| 2553 |
L<Dancer2::Plugin::LiteBlog|LiteBlog> from our project founder, Sukria. |
| 2554 |
|
| 2555 |
Happy Dancing! |
| 2556 |
|
| 2557 |
=head1 AUTHOR |
| 2558 |
|
| 2559 |
Dancer Core Developers |
| 2560 |
|
| 2561 |
=head1 COPYRIGHT AND LICENSE |
| 2562 |
|
| 2563 |
This software is copyright (c) 2026 by Alexis Sukrieh. |
| 2564 |
|
| 2565 |
This is free software; you can redistribute it and/or modify it under |
| 2566 |
the same terms as the Perl 5 programming language system itself. |
| 2567 |
|
| 2568 |
=cut |