0

I am trying to learn to use django class based views . I want to make a GET request and do some operations only if the user is super user , but when I call this API using curl , it always uses AnonymousUser irrespective of what I send via the CURL command.

views.py

class handle_request(View):

    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        return super(handle_request, self).dispatch(request, *args, **kwargs)

    def get(self, request):
        print "GET request made"
        print request.user # <-- this is always AnonymousUser
        if not request.user.is_superuser:
            return HttpResponse("User is not permitted this action",status=403)
        else: 
            # Do something

urls.py

urlpatterns = [
    url(r'^$', handle_request.as_view()),
    url(r'^db', hello.views.db, name='db'),
    url(r'^admin/', include(admin.site.urls)),
]

curl command

curl -u test:testpass http://0.0.0.0:5000

what is the correct way to pass username and password to class based django view ?

g4ur4v
  • 3,210
  • 5
  • 32
  • 57
  • You would need to write some middleware that will authenticate the user for any request by passing the credentials, it is not automatic. – dotcomly May 28 '16 at 20:48
  • even if I don't write custom middleware, shouldn't username be available in the request body in views ? – g4ur4v May 28 '16 at 20:57
  • If you log in. Have you? – Daniel Roseman May 28 '16 at 20:59
  • It works if I call this api from browser after logging in admin site from browser first. – g4ur4v May 28 '16 at 21:04
  • 1
    The -u flag is for HTTP Basic / Digest Auth (https://en.wikipedia.org/wiki/Basic_access_authentication) which is not the default Django auth. You can add it with https://docs.djangoproject.com/en/dev/howto/auth-remote-user/ but you will need to configure your http server to manage authentication. Here is an answer using curl to authenticate with standard user/pass http://stackoverflow.com/questions/21306515/how-to-curl-an-authenticated-django-app – dotcomly May 28 '16 at 21:08
  • @dotcomly - thanks . curl solution mentioned in http://stackoverflow.com/questions/21306515/how-to-curl-an-authenticated-django-app is working – g4ur4v May 28 '16 at 21:35

0 Answers0