1

I want to create a very simple API, with only one endpoint. I want to send to an API a json like : {"provider" : "com.facebook.orca", "code" : "1", "color" : "#FFFFF" }

Then, I want to use a python library to control a device in my room(python-yeelight). I want to use this with a Auth token or a username/password authenticate.

What I found on Django Rest Framework was way too complicated for what I need(which is accepting a POST and returning a "success" or "failure" message.

Thank you!

7
  • OK. So where are you having problems doing this in basic Django? Commented Apr 21, 2017 at 14:17
  • I need to create a model, a serializer, some fields, meta, etc. All of which are not needed. But I still need the Auth(can't use csrf_token) Commented Apr 21, 2017 at 14:19
  • I don't understand that reply. You've said you don't want to use django-rest-framework, which is fine; so you don't need to create any of those things. So, what have you actually done, and what problem are you having? Commented Apr 21, 2017 at 14:21
  • Because without that framework I don't know how to use basic Auth / Auth key. Django uses crsf token by default, which I cannot use. Commented Apr 21, 2017 at 14:28
  • But CSRF has nothing whatsoever to do with authentication, so I don't know why you are mentioning it. Commented Apr 21, 2017 at 14:30

1 Answer 1

1

You can create a method decorator to implement basic authentication. Wrap all your django views using this decorator.

def token_required(function):
    def wrap(request, *args, **kwargs):
        auth_token = request.META.get('HTTP_AUTHORIZATION_TOKEN')
        if auth_token:
            try:
                token = Tokens.objects.get(token=auth_token)
                user = token.user
            except Tokens.DoesNotExist:
                user=None
        else:
            r = {
                    'status': -1,
                    'message': 'Please provide a valid token.'
                }
            return HttpResponse(json.dumps(r), content_type="application/json")
        if user:
            request.user = user
            return function(request, *args, **kwargs)
        else:
            r = {
                        'status': -2,
                        'message': 'User not Authorised, Please login'
                }
            return HttpResponse(json.dumps(r), content_type="application/json")
    return wrap

Now all your requests must contain a header as shown below to views wrapped by this decorator to detect the user inside views.

AUTHORIZATION-TOKEN : some_token_value

Your tokens model will look something like as shown below.

class Tokens(models.Model):
    user = models.OneToOneField(User, related_name="tokens",null=False)
    token = models.CharField(max_length=255, unique=True)

    def save(self, *args, **kwargs):
        if self.token is None or self.token == "":
            import uuid
            self.token=uuid.uuid4().hex
        super(Tokens, self).save(*args, **kwargs)

Sample use of decorator:

@csrf_exempt
@token_required
def your_view(request):
    pass

I guess this should help you out.

Sign up to request clarification or add additional context in comments.

3 Comments

I will try it, thank you. Where should I place the custom function? In views.py is it OK?
Yeah. It will be inside your views.py file.
Ok, I copied the whole code. How exactly do I pass the username / password in the POST? From the code it seems that I should pass in Headers the HTTP_AUTHORIZATION_TOKEN. But how do I obtain that? (I am sorry, I am used to PHP / Laravel, first time with Django)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.