How to protect forms from CSRF attacks

Problem

How to make sure a POST form submission genuinely originates from a form created by the application,
and is not a Cross-Site Request Forgery.

Solution

We keep a unique csrf_token that is rendered as a hidden field inside post forms and can not be guessed by CSRF attackers.
This token gets checked during POST methods.

We need 4 things:

A csrf_token() function - to use inside form templates. It either returns the existing session.csrf_token or generates a new one.

A @csrf_protected decorator for POST() methods. It pops session.csrf_token and compares it with the csrf_token
input we expect to get from a genuine form (see <input type="hidden" ...> below.
Whether the test succeeds or fails, this will make sure that next time csrf_token() is called (most probably - from
inside a form's template), a new token will be generated.

Make csrf_token() available to templates by adding it to the globals of our render object.

Add <input type="hidden" name="csrf_token" value="$csrf_token()"/> to the forms in the templates.