Let's say i have a form that does something in database and requires user authentication that has been sent by POST, is it possible inside request someone evil to change the user in order to exploit the system?
The following example creates an item in database but requires a logged in user. Can someone send other user's data in request.user?
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from items_core.models import Item
from items.forms import CreateItemForm
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
@login_required
def create(request):
errors = None
if request.method == 'POST':
form = CreateItemForm(request.POST)
if form.is_valid():
try:
Item.objects.get(
name = form.cleaned_data['name'],
user = request.user
)
errors = 'Item already exist. Please provide other name.'
except Item.DoesNotExist:
Item.objects.create(
name = form.cleaned_data['name'],
user = request.user
)
return redirect('items:list')
form = CreateItemForm()
else:
form = CreateItemForm()
template = {
'form':form,
'items':Item.objects.filter(user=request.user),
'request':request,
'errors':errors
}
return render(request, 'items/item_create.html', template)
Thanks!
The request.user
object is of type SimpleLazyObject
which is added by the auth middleware
to the requestobject.
SimpleLazyObject(LazyObject):
is used to delay the instantiation of the wrapped class
At the time of requesting the actual logged in user, get_user
method gets called.
def get_user(request):
if not hasattr(request, '_cached_user'):
request._cached_user = auth.get_user(request)
return request._cached_user
Here, auth.get_user()
would inturn validate this way:
backend_path = request.session[BACKEND_SESSION_KEY]
backend = load_backend(backend_path)
user = backend.get_user(user_id) or AnonymousUser()
Hence if the request.user
object is tampered with, this validation would fail as the session data validation would fail
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With