Protect your secret page

So we created a login page, but it wasn’t that useful, was it? Anyone could bypass our security. We need to protect our secret page. To do this, you need to know about Python decorators. If you watch the video above, I give you a quick introduction.  If you want to read more, go here. We will create our own decorator, that will protect the secret page.

First, add this to the top of your file:

This is the decorator function:

If you understood how decorators work, this is a very simple example. All it checks for is: Is logged_in in the session? If so, it allows us to call the current function. Otherwise, it will force the login function to be called ( return redirect(url_for(‘login’)) ). We just need to add this decorator right below our secret function:

That’s it. try to access now, without first logging in. It will force you to the login page.

One thought on “Protect your secret page”

  1. Nice tutorial. I don’t usually do web development, but flask seems to be a nice framework for back-end servers.

    Some comments on the decorators: AFAICT you don’t HAVE to use them. You could just as well call a method in every ‘secret’ page that checks for the session and redirects as necessary. Also, renaming the variables in the ‘login_required’ to something like ‘inner_func’ and ‘wrapper’ might make things easier to understand for others.

Leave a Reply

Your email address will not be published. Required fields are marked *