Django decorators

I am developing a page with Django and I had one interesting requirement: limit the number of users. The idea is to let a fixed number of users use the site and show a message telling the others to wait. I will like to share how I did it.

We need to check in every view used by a user. Instead of repeating the same code, the easiest way is to add a decorator for each function. Is really similar to AoP.

decorators.py:

from django.conf import settings
from django.shortcuts import redirect

MAX_NUMBERS_OF_USERS = getattr(settings, 'MAX_NUMBERS_OF_USERS', 100)

def check_user(view_function):
    def _wrapped_view_func(request, *args, **kwargs):
        auth_user = request.user
        
        if auth_user.id <= MAX_NUMBERS_OF_USERS:
            return view_function(request, *args, **kwargs)
        return redirect('coming_soon')
    return _wrapped_view_func

views.py:

from app.decorators import check_user
from django.contrib.auth.decorators import login_required
from django.shortcuts import render

@login_required
@check_user
def restricted_view(request):
    #Do stuff

def coming_soon(request):
    return render(request, 'coming_soon.html', {})

And that’s it ! Easy, clean and simple ! You can do more complex stuffs like logging.

Advertisements

Configure Juniper VPN Web Client Ubuntu 14.04 64 bits

So i am doing a project with Mercado Libre and they use Juniper VPN.

I love to code using Linux, it has a lot of advantages. At this moment I am using Ubuntu 14.04 64 bits.

Mercado Libre sent me the instructions on how to connect with my login/password. So I followed them, but thanks to the awesome people of Juniper, they does not have support for Linux 64 bits. At least they have this guide.

That guide did not work for me. I had to struggle and read a lot over the internet, view system logs, etc. After one day I was able to connect, so this are the instructions i followed:

  1. sudo dpkg –add-architecture i386
  2. sudo aptitude purge firefox
  3. sudo aptitude install firefox:i386 icedtea-7-plugin:i386 openjdk-7-jdk:i386
  4. Open Firefox, enter the login/password/token, then it will load the plugin and ask to allow and accept a lot of things, click all yes and that is it. You need to make sure Firefox have all the permissions to run the java applet.

That guide works if you are running the client directly from the computer, not from the browser. We just need to be sure that Firefox will load the Juniper VPN applet running on a 32 bits JVM.