Search code examples
djangodjango-formsdjango-viewsdjango-authenticationdjango-login

Authenticating a User, without using Django rest framework?


Hey everyone I have a couple questions in regards to refactoring some old api endpoints as far as authentication goes. I have a view for example...

@csrf_exempt
# PARAMETERS: username, password
def submit_offer(request):
    """Submit an offer"""
    username = request.GET.get("username")
    password = request.GET.get("password")
    # Authenticate user to set instance.user value into BuyerForm
    user = authenticate(username=username, password=password)
    if not user:
        # Always want our potential Buyer to be logged in & authenticated
        return JsonResponse({'message': 'Please login to continue.'})
    if request.method == 'POST':
        form = BuyerForm(request.POST, request.FILES)
        if form.is_valid():
            instance = form.save(commit=False)
            # sets current user as Buyer.user
            instance.user = user
            instance.save()
            return JsonResponse({'success': True}, status=200)
        else:
            data = form.errors.as_json()
            return JsonResponse(data, status=400, safe=False)
    else:
        return JsonResponse(data={'status': 403})

Now every view that uses a form, and needs to grab the instance.user, has the same lines of code below...now I thought using request.user would do the job, but when testing that way I am getting back an AnonymousUser, which is kind of confusing me?

username = request.GET.get("username")
password = request.GET.get("password")
# Authenticate user to set instance.user value into BuyerForm
user = authenticate(username=username, password=password)

Now is there a better way to authenticate the user, like in a regular django view using request.user, rather than having to manually authenticate the user in each view? (edited)


Solution

  • password = request.GET.get("password").

    This is very vulnerable way to design a django app.

    Please see Accessing Username and Password in django request header returns None

    BTW, write a custom middle ware and put your code there.

    username = get_username_from_header
    password = get_password_from_header
    # Authenticate user to set instance.user value into BuyerForm
    user = authenticate(username=username, password=password)
    # Attach user to request 
    request.user = user
    

    As each request are being passed through the middle-ware, you can access the user from each view.