Self hosted FLOSS fitness/workout, nutrition and weight tracker
Add support for token authentication to REST API
Roland Geider43e5acb25add
diff --git a/wger/core/templates/user/api_key.html b/wger/core/templates/user/api_key.htmlindex 601ce1017..1e47b4d93 100644--- a/wger/core/templates/user/api_key.html+++ b/wger/core/templates/user/api_key.html@@ -7,65 +7,50 @@{% block content %}+{% with url='/api/v2/' %}<p>{% blocktrans %}Generate an API key if you want to interact with wger via-the <a href="/api/v1/?format=json" rel="nofollow">REST API</a> it provides (for+the <a href="{{url}}" rel="nofollow">REST API</a> it provides (forpublic resources such as the exercises or ingredients, you don't need to provide-anything). You must pass this information together with your username either in-the header or in the request as GET parameters. For example:{% endblocktrans %}-+anything). You must pass this information in the header in the format shown below.{% endblocktrans %}+{% endwith %}++<p>{% blocktrans %}For security reasons, you should only access the API via HTTPS.{% endblocktrans %}</p>+<div class="panel {% if token %}panel-success{% else %}panel-default{% endif %}">+ <div class="panel-heading">+ <h3 class="panel-title">{% trans "Your API key" %}</h3>+ </div>+ <div class="panel-body">+ {% if token %}+ <strong>{{token.key}}</strong>+ {% else %}+ <em>{% trans "You have no API key yet" %}</em>+ {% endif %}+ </div>+</div><pre>-# In header-Authorization: ApiKey {{user.username}}:{% if key %}{{key.key|truncatechars:15}}{% else %}1234567890abcde...{% endif %}--# In GET parameter-https://wger.de/api/v1/workout/?username={{user.username}}&api_key={% if key %}{{key.key|truncatechars:15}}{% else %}1234567890abcde...{% endif %}-</pre>-</p>--<table class="table">- <tr>- <td>- {% trans "Your API key" %}- </td>- <td>- {% if key %}- <strong>{{key.key}}</strong>- {% else %}- <em>{% trans "You have no API key yet" %}</em>- {% endif %}- </td>- </tr>- <tr>- <td>- {% trans "Your username" %}- </td>- <td>- <strong>{{user.username}}</strong>- </td>- </tr>-</table>-+# In the request header+Authorization: Token {% if token %}{{token.key}}{% else %}1234567890abcde...{% endif %}+# Example with curl+curl -X GET https://wger.de/api/v2/workout/ -H 'Authorization: Token {% if token %}{{token.key}}{% else %}1234567890abcde...{% endif %}'+</pre>{% endblock %}-{% block sidebar %}+{% block sidebar %}<h3>{% trans "Options" %}</h3><p>-{% if key %}+{% if token %}<a href="{% url 'core:api-key' %}?new_key=true" class="btn btn-block btn-default">{% trans 'Delete current API key and generate new one' %}</a>{% else %}<a href="{% url 'core:api-key' %}?new_key=true" class="btn btn-block btn-default">{% trans 'Generate new API key' %}</a>{% endif %}</p>--<p><a href="{% url 'software:api' %}" class="btn btn-block btn-default">{% trans 'Documentation' %}</a></p>-{% endblock %}diff --git a/wger/core/tests/test_apikey.py b/wger/core/tests/test_apikey.pyindex 992e2def6..f6847e0e1 100644--- a/wger/core/tests/test_apikey.py+++ b/wger/core/tests/test_apikey.py@@ -17,7 +17,7 @@ import loggingfrom django.core.urlresolvers import reversefrom django.contrib.auth.models import User-from tastypie.models import ApiKey+from rest_framework.authtoken.models import Tokenfrom wger.manager.tests.testcase import WorkoutManagerTestCase@@ -41,14 +41,14 @@ class ApiKeyTestCase(WorkoutManagerTestCase):response = self.client.get(reverse('core:api-key'))self.assertEqual(response.status_code, 200)self.assertContains(response, 'Delete current API key and generate new one')- self.assertTrue(ApiKey.objects.get(user=user))+ self.assertTrue(Token.objects.get(user=user))# User has no keys- ApiKey.objects.get(user=user).delete()+ Token.objects.get(user=user).delete()response = self.client.get(reverse('core:api-key'))self.assertEqual(response.status_code, 200)self.assertContains(response, 'You have no API key yet')- self.assertRaises(ApiKey.DoesNotExist, ApiKey.objects.get, user=user)+ self.assertRaises(Token.DoesNotExist, Token.objects.get, user=user)def test_api_key_page_generation(self):'''@@ -57,7 +57,7 @@ class ApiKeyTestCase(WorkoutManagerTestCase):self.user_login('test')user = User.objects.get(username='test')- key_before = ApiKey.objects.get(user=user)+ key_before = Token.objects.get(user=user)response = self.client.get(reverse('core:api-key'), {'new_key': True})self.assertEqual(response.status_code, 302)@@ -65,7 +65,7 @@ class ApiKeyTestCase(WorkoutManagerTestCase):self.assertEqual(response.status_code, 200)self.assertContains(response, 'Delete current API key and generate new one')- key_after = ApiKey.objects.get(user=user)+ key_after = Token.objects.get(user=user)self.assertTrue(key_after)# New key is different from the one beforediff --git a/wger/core/views/user.py b/wger/core/views/user.pyindex da8b591c9..6a88cb5f7 100644--- a/wger/core/views/user.py+++ b/wger/core/views/user.py@@ -31,7 +31,7 @@ from django.contrib.auth.models import User as Django_Userfrom django.contrib.auth.views import login as django_loginviewfrom django.contrib import messages-from tastypie.models import ApiKey+from rest_framework.authtoken.models import Tokenfrom wger.core.models import Languagefrom wger.utils.constants import USER_TAB@@ -203,20 +203,18 @@ def api_key(request):context.update(csrf(request))try:- key = ApiKey.objects.get(user=request.user)- except ApiKey.DoesNotExist:- key = False+ token = Token.objects.get(user=request.user)+ except Token.DoesNotExist:+ token = Falseif request.GET.get('new_key'):- if key:- key.delete()+ if token:+ token.delete()- key = ApiKey()- key.user = request.user- key.save()+ token = Token.objects.create(user=request.user)# Redirect to get rid of the GET parameterreturn HttpResponseRedirect(reverse('core:api-key'))- context['key'] = key+ context['token'] = tokenreturn render(request, 'user/api_key.html', context)diff --git a/wger/manager/fixtures/test-apikeys.json b/wger/manager/fixtures/test-apikeys.jsonindex 158bc7b20..a9d51b841 100644--- a/wger/manager/fixtures/test-apikeys.json+++ b/wger/manager/fixtures/test-apikeys.json@@ -1,7 +1,7 @@[{"pk": 1,- "model": "tastypie.apikey",+ "model": "authtoken.token","fields": {"user": 1,"key": "apikey-admin",@@ -10,7 +10,7 @@},{"pk": 2,- "model": "tastypie.apikey",+ "model": "authtoken.token","fields": {"user": 2,"key": "apikey-test",@@ -19,7 +19,7 @@},{"pk": 3,- "model": "tastypie.apikey",+ "model": "authtoken.token","fields": {"user": 3,"key": "apikey-demo",diff --git a/wger/settings_global.py b/wger/settings_global.pyindex a0faaee12..e1ad2018a 100644--- a/wger/settings_global.py+++ b/wger/settings_global.py@@ -226,6 +226,7 @@ INSTALLED_APPS = (# REST framework'rest_framework',+ 'rest_framework.authtoken')@@ -339,4 +340,9 @@ REST_FRAMEWORK = {'DEFAULT_PERMISSION_CLASSES': ('wger.utils.permissions.WgerPermission',),'PAGINATE_BY': 20,'PAGINATE_BY_PARAM': 'limit', # Allow client to override, using `?limit=xxx`.+ 'DEFAULT_AUTHENTICATION_CLASSES': (+ 'rest_framework.authentication.BasicAuthentication',+ 'rest_framework.authentication.SessionAuthentication',+ 'rest_framework.authentication.TokenAuthentication',+ )}\ No newline at end of file