Search code examples
djangodjango-formshidden-fieldcode-access-securitydjango-models

Django/Forms: How can i validate initial data against received data (if match)?


Let's say that I'm creating a form and I'm passing some hidden values through bound, that must not be changed. My question is how can I test if a malicious user has changed this hidden values? I'm not sure what exactly does bound data in a form and the difference between initial.

In the Django's forms.py is a property called changed_data but I don't know if can help or not.

Code for demonstration:

forms.py

class ConfirmForm(forms.Form):
    client_id = forms.CharField(widget=forms.HiddenInput())
    identifier = forms.CharField(widget=forms.HiddenInput())

    def clean(self):
        # Maybe here the validation process of cliend_id and identifier like:
        clean_client_id = self.cleaned_data.get('client_id')
        clean_identifier = self.cleaned_data.get('identifier')
        if last_client_id == clean_client_id and 
           last_identifier == clean_identifier:
            return self.cleaned_data
        else:
            raise forms.ValidationError("False data.")

views.py

def form_confirm_handler(request):
    if request.method == 'POST':
        form = ConfirmForm(request.POST)
        if form.is_valid():
            #Do something...
            return redirect('home:index')

    #The following values are not fixed. Are generated variables!
    bound_data = {'client_id':'123456','identifier':'wuiy5895'}
    form = ConfirmForm(bound_data)
    return render(request, 'client/theform.html', {'form':form})

html template

<form action="{% url 'client:confirm' %}" method="post">
    <p>Do you really want to proceed?</p>
    {% csrf_token %}
    {{ form.client_id }}
    {{ form.identifier }}
    <button id="submit" type="submit" name="submit" class="btn" value="accept">Accept</button>
    <button id="cancel" type="submit" name="cancel" class="btn btn-primary" value="cancel">Cancel</button>
</form>

Thanks in advance!


Solution

  • I found 4 (easy) possible solutions to this problem.

    The most valid solution for Django is this:

    class TheFormName():
        client_id = forms.CharField(show_hidden_initial=True, widget=forms.HiddenInput())
        identifier = forms.CharField(show_hidden_initial=True, widget=forms.HiddenInput())
    
    def clean(self):
        if self.has_changed():
            raise forms.ValidationError('Fields are not valid.')
    
        return self.cleaned_data
    

    The second solution is by using the changed_data to see what has changed:

    def clean(self):
        for field_name in self.changed_data:
            # loop through the fields which have changed
            print "field {} has changed. New value {}".format(field_name, cleaned_data['field_name']
    

    For my case is translated to this, but is exactly the same as the has_changed() method:

    def clean(self):
        if len(self.changed_data) > 0:
            raise forms.ValidationError('Fields are not valid.')
    
        return self.cleaned_data
    

    Another solution that looks more like a hack is:

    self.cleaned_data['cliend_id'] == self.instance.cliend_id
    self.cleaned_data['identifier'] == self.instance.identifier
    

    And the final solution a bit more complex is by using sessions inside clean() method (and outside of view). Example from Django Docs:

    from django.contrib.sessions.backends.db import SessionStore
    import datetime
    s = SessionStore()
    s['last_login'] = datetime.datetime(2005, 8, 20, 13, 35, 10)
    s.save()
    s.session_key
    >>> '2b1189a188b44ad18c35e113ac6ceead'
    
    s = SessionStore(session_key='2b1189a188b44ad18c35e113ac6ceead')
    s['last_login']
    

    Also useful is this post In Django 1.4, do Form.has_changed() and Form.changed_data, which are undocumented, work as expected? provided by @LarsVegas