tags:

views:

18

answers:

2

Hi,

I've got a django app whose views currently use the @login_required decorator.

What's the easiest/best way to add extra logic to the login system? I want to add extra constraints such as that their subscription to the site is still valid. If it has expired I want to direct them to a page that says their subscription has expired and that they'll need to pay again.

Ideally a signal would be great, but I can't find any kind of post_login signal. Failing that I suppose my options are to write my own login handler, or to have some kind of check_valid_user() method that I call inside each of my views. I don't favour the latter since another dev could forget to add it, and users could get content for free.

What approach would people recommend?

Thanks

A: 

Authentication backends aren't that difficult. I've written a custom one.

PeterP
+1  A: 

You can write own login view or better own authbackend(second example).

from django.contrib.auth.views import login as core_login

#myapp/views.py
@ratelimit_post(minutes = 1, requests = 4, key_field = 'username')

def login(request,template_name):
    from django.contrib.auth import authenticate
    user = authenticate(username='john', password='secret')
    template_name = "template_name" + "aaaaa"
    return core_login(request, template_name)


#myapp/ursl.py
#override default url
  ...
  (r'^accounts/login/$', 'myapp.views.login', {'template_name': 'profile/login.html'}), 
  ...



#backends/authemailbackend.py
from django.contrib.auth import authenticate
user = authenticate(username='john', password='secret')
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
from django.forms.fields import email_re

class EmailBackend(ModelBackend):
    def authenticate(self, username=None, password=None):
        if email_re.search(username):
            try:
                user = User.objects.get(email=username)
                if user.check_password(password):
                    return user
            except User.DoesNotExist:
                return None
        return None 
~                                                                                                                                                                                     
~                           

#settings.py
AUTHENTICATION_BACKENDS = (
    "myapp.backends.authemailbackend.EmailBackend",
    "django.contrib.auth.backends.ModelBackend",
)
iddqd