Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add auth validation in Django

I have a django application and I want to add my own auth validation and check if the user is expired (check the expiration date from some of my models). I want to raise a ValidationError in the login page with appropriate message if user is expired. What's the best way to do that?

Thanks, Alex

like image 720
alexarsh Avatar asked Nov 29 '25 01:11

alexarsh


1 Answers

If you REALLY want to do your own custom authentication, you should read custom backends in the Django Documentation.

You probably don't want to do your own though. It sucks. Really. Unless there is a really really good reason, you should avoid your own authentication. The main reason being, that many django apps stop working if you don't use the built in User model. If you need to authenticate against an existing source, that's a valid reason for creating your own backend. But there are pitfalls, and you still probably want to use the built in User model for your custom backend.

You should tell us why you want to do your own custom authentication, and perhaps we can help you achieve your requirement, without writing a custom backend.

Edit

Ok, I think I understand what you mean now. What (I think) you want, is a custom authentication form. We currently use custom form (though we have a different unavoidable backend), so you should be able to use the following quite easily.

from django.contrib.auth.forms import AuthenticationForm
from django import forms
from myproject.myapp.models import MyClass

class CustomAuthForm(AuthenticationForm):

    def clean(self):
        cleaned_data = super(CustomAuthForm, self).clean()
        user = self.user_cache # set by super class
        if user.my_class.expired:
            raise forms.ValidationError('This User has Expired!')
        return cleaned_data

Then, to use this custom authentication form, you need a URL in your urls.py:

from myproject.myapp.forms import CustomAuthForm

url(r'^login/$', 'django.contrib.auth.views.login', name='login', 
    kwargs={'template_name':'youproject/login.html', 'authentication_form':CustomAuthForm}),

I see now that your question originally stated you wanted custom validation, not authentication. My apology for not reading your question correctly.

like image 102
Josh Smeaton Avatar answered Nov 30 '25 16:11

Josh Smeaton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!