Sunday 28 July 2013

The dumb code festival - 4

Authentication and authorization is something every framework must manage. Because they're boring and frameworks exist to manage boring things.
When a user can be considered authenticated? The easiest way to check it it searching is its session for a user key with some interesting value. Is this secure? Enough, because we're talking about server-side session, something a user can't touch, we have to trust it well... until a new security flaw is found in one of the layer of our system.

The "auth" thing is a pattern well known in the web world and you can find many solutions for it, looking for "Dancer::Plugin::Auth" you'll find a lot of stuff. Unfortunately Dancer2 is still a young project so the only tool we have is the Dancer2::Plugin::Auth::Tiny from Golden.
We'll not use it. Ok, the plugin is a very good piece of software but its main purpose is define which routes need login to redirect on login page the not authenticated users. I think that this is made useless by the Dancer2 App scope.
In a situation where routes for logged users and routes for not-logged users are mixed up probably D2::P::A::Tiny is the right solution, but here we have an app where every route needs auth so we'll solve our problem just with a before hook defined in the app itself.

But we have to start from: how to open the doors to a logged user? Login went well, user and password were right, what the server will do? As I said before, it will write in the user session the username.

session 'user' => $the_username;

This is what our hook will check:


Yes, just this. The most common mistake is forgetting that the login route has to skip the check because is the only page allowed for not logged users. In every other case the hook does NOTHING for logged users and redirect to the login page the guests.

I made it more longer than what is needed because I like to talk and write and because sometimes I think that also obvious things need some explanation, somewhere. Conclusion is that using the snippets from the dump code festival you have the start situation for an admin tool you can use for every purpose. Probably, working on it, you'll find a lot o things to improve it or make it smarter. But this is just the first step, the dump step, so it's right as it is.

Monday 22 July 2013

The dumb code festival - 3

In the first two chapters of our dump code festival we just did a lot of frontend developement, something completely independent from the framework we are using and with no server-side logic.
Well, today frontend developement is very important and HTML::FormFu is a very complex and obscure thing so I think it's not so bad we spent all this time on it.

You know? I'm trying to make HTML::FormFu "cooperate" with Twitter Bootstrap. Yes, it's possible and easy enough, but you have to do tricks and you'll never have all the freedom you probably want. However, letting twitter bootstrap render the form make it nicer than not doing it, so... give it a try.

But now we have to talk about logic.
Business logic in a login form is triggered just on submit, when data start its voyage to the server and the server is committed to give an answer to the user. It's like going to the oracle. Yes, the oracle with eyes turned up to the sky and funny clothes, not the oracle database server.

Easiest and probably most elegant way to manage a login form is making is action calling again the login page. This is the meaning of the any keyword we used last time to define the route. You arrive on the login route with a GET (obtaining the form), you process the submitted data with a POST on the same route.

The four needed steps are:

  1. Create the form object
  2. obtain the DATA inserted from the user
  3. process the data
  4. Do something with the data (yes, you can throw it away and laugh, but this way you'll never become a professional programmer)

As you can see the code is very simple and it's just HTML::FormFu syntax mixed up with very few Dancer2 magic.
We saw the first two lines in the last chapter. They, with the last one, make the form appear on the screen. The params keyword retriver all the variables arrived with the request, it's a pointer to an hash that's suitable for the $form->process. Process takes every key in the hash and put it in the field of the form with the same name, triggering contraints, validators, inflators etc. etc. The result of this computation is in the submitted_and_valid variable that can be easly tested to see if the data can be processed.

Staying in the same route makes all the messages easy to manage. The process can find a violeted contraint, for example (as an empty field, as we configured), then it can write the error message directly in the form and the rendering, on the bottom of the route, will make it automatically visible.

In the GET scenario no param is present, process receive an undef and do nothing to change the form. The render will display the form untouched, ready to be used.

What about the login_valid? It's up to you, you have to decide when a user is good and when it's not.
This is a easy and dumb implementation:



Users and passwords are on a little DB table, accessible using the Dancer2::Plugin::DBIC (as always). Remember: just the MD5 for your password IS NOT a secure way to store it. But, as I said, this is just an example.

Well, there's just one more thing to say, probably the most interesting because it's the one about Dancer2 structure and server-side logic. It's just this: now we have a login page, what we need is that it appears every time someone try to navigate our admin panel. EVERY TIME.

Tuesday 16 July 2013

Dancer2::Plugin::Multilang

So, my wonderful Dancer2 plugin to manage multilanguage sites is released on github!

I wrote in this blog something I learned developing it, so I think that this place is the right one to make the announce.

I tryed to design this plugin as "plug-and-play" as possible. With it, you should be able to make your site multilanguage with no other effort then... translate the contents.

Netx step is releasing it on CPAN but I never did something like that so I have to learn how. I hope to learn it well enough to come back and writing about it in my blog, but now I don't have enough time to do it, so this topic has to wait a little.

In the meantime download, try, fork and play with my plugin as long as you want. Feedbacks (yes, bad feedbacks too) are welcome!

Sunday 14 July 2013

The dumb code festival - 2

Let us spend some more words about forms and HTML::FormFu. In the preview chapter we just scratched the surface of it, doing something too essential to be enough, even in a dumb code festival.

Form is a way to have a structured stream of input coming from a human being to a machine. Human beings are bad doing data input. They insert bad data, they're lazy, they use funny mysterious languages like english and they're often stupid. You can't trust them, you have to constraint them, filter their input, inflate it and validate. (you would also bring them all and in the darkness bind them but this is not a tutorial suited for that).

Keeping us near the little example we're working on, a login, box, what kind of bad input we should manage? Luckly, very little, the only bad thing a user could try is to submit the form with no data inside. We could ignore this case, obviously it will led to a bad login, but let us make HTML::FormFu manage it for us.

Very little code added, just a contraints field with an element. The element is defined by a type and a message to me thrown up when constraint is violeted.

An interesting thing about: where that "Requeired" word come from? How can I know which words can do this kind of magic? Is there a sort of grimorioum for them?
Obviously not, the keyword you put in the type is just the name of a perl package, in the HTML::FormFu::Constraint namespace. The one invoked here is this.
What does this mean? It means that you can look at the available constraints just surfing the CPAN for contrainst classes and that you can use constraints created by your own just giving them the HTML::FormFu::Constraint namespace and putting them in the configuration file as "official" ones.
And yes, filters, inflaters and validators follow the same logic!

Just updating the form configuration you have managed the empty fields case. HTML::FormFu will reject the submission and will display errors on screen if the user try to submit without writing anything (lazy, lazy human!).

Now two important downsides:

  1. Validation is server-side. The form is submitted, POST data elaborated, page reloaded with errors. If you're aiming to a validation with no page refresh and client-side javascript magic you're looking in the wrong place.
  2. HTML produced by FormFu is the HTML it likes. You could not like it. You could think is a little old-style, too rude and simple. For example, I hate it doesn't use the Label for attribute.
    You can decide to work "around it" knowing how it is and putting javascript and CSS to make it looks good. The harder way is going down in the HTML::FormFu classes and redefine the rendering. This thing is not enough dumb for this article.
But... probably after so many words you want to see your form, don't you?
Open your Dancer App and render it!


The any key to acquire GET and POST will come useful in the future. Remember that the login.yml will be searched in you app root, the same directory where the Dancer config.yml is placed. Subdirectories are allowed (and recommended).
Remember to have in your template a [% form %] token where the box will be displayed.

This piece of code is very stupid, nearly useless, because there's no logic. But it's just the second part and we have a lot of things to talk about.

Saturday 13 July 2013

The dumb code festival - 1

One thing I usually miss when I google things about Dancer2 (or other coding stuff) is examples of simple working code doing normal things. Every time you find just little snippets that do just a thing in a way that will be useless to you ore code doing wonderful, exciting things you don't need.
For Dancer2 we have this article from Sukrieh himself that is very useful to learn how Dancer2 works, but... just this.

I want to put in this blog all the things I don't find in internet so I decided to start some articles about an obvious, stupid thing you all do blind and tied up while singing Yellow Submarine. Just because I think that out there there's someone who's not singing loud enough.

Let's talk about a little adminitration panel for your website. I'm not interestend in what your website do, there're a lot of things an administration panel has to do anyway. The most important thing is that it has to keep out all the non-authorized people and let the authorized in.

Authorized people will enter somewhere username and password. There're a lot of ways to do this (and some plugin from Dancer that could be easly migrated to Dancer2) but we'll to it from scratch in the most obvious way: a login page.

A login page is just a form with you fields, a big red button and a lot of threatening messages when you do wrong things.

Talking about forms, perl and frameworks, you should learn about HTML::FormFu, one of the most used libraries for forms in perl.
Using it, you'll translate all the logic you want in the form in a configuration file, adding to it, eventually, some libraries for validation, filtering and so on, downloaded from CPAN or written by you.
You could think this is too much complex and without real gain for your coding, especially when you are dealing with little forms.
My advice is to always follow this design path for two important reasons:

  1. If you don't use it with simple problems, you'll NEVER use it in complex one. Don't lie.
  2. In every case templating the form is keep separated from coding is logic, something you must do if you want to write tidy code.
A login box using HTML::FormFu at his minimum potential has a config file (login.yml) like this:


You can make it a little more beautiful, but all the logic you need is here.

For this time we'll stop here, i wrote the introduction to this experiment, so the article is already long enough. Numbers near the title means that we'll go on. I hope that I'll create something useful with this, useful for the internet and also for me, to make my mind a little more clear about what I do.

Wednesday 3 July 2013

Database around the clock

Probably this article is about something that everyone in the world knows. Problem is I did mistakes about this TWO times, without learning from them, so writing down it could be useful for this head of mine to remember how to do things right.

Writing a timestamp whenever a database row is created or updated is a standard task and everyone need it.  Many database systems can do it by themselves (MySQL), dumber ones cannot (SQLite). Are we interested in this? Obviously not, DBIX::Class (the one and only) give us a good abstraction about that and it's easy to use.

When you know the trap to avoid.

Syntax to have a timestamp that set itself on create is really simple. In your model class:


__PACKAGE__->add_columns(
  "timestamp",
  { data_type => "datetime", is_nullable => 0, set_on_create => 1 },
);


It's something so used that there's a flag to manage it. You set it to true, the timestamp will be written.

IF and only IF you remember this:

__PACKAGE__->load_components("TimeStamp");

and you installed DBIx::Class::Timestamp!

Are you hearing the Wotan worshipper roaring? Why should he? It's a procedure so clean!

Well, perl is a language that worship optimization (more than Wotan! Grrrrr). Often optimization means a fine grane library control. So in many important modules you see methods different from use... to load libraries. Most of these methods have a little side-effect: they don't give errors.
In this particular case you can write the first piece of code, forget the second or write the second and forget to install the library. The code will run. What will happen about the timestamp? Absolutly nothing.

But now I wrote this. Now this thing is encarved in my blog and in my mind. I will never be tricked again.

What were we talking about?