Reputation: 21
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!
Upvotes: 1
Views: 794
Reputation: 3386
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.
Upvotes: 1