Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added authentication using a query param #64

Merged
merged 5 commits into from
Dec 7, 2020
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

### Added

- nothing added
- Added the capability to authenticate using `c_auth_with_token` query parameter in urls when using HTTP headers is not possible (webhooks).

### Changed

Expand Down
15 changes: 14 additions & 1 deletion concrete_datastore/api/v1/authentication.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# coding: utf-8
import uuid
import pendulum

from django.utils.translation import ugettext_lazy as _
from django.conf import settings

Expand Down Expand Up @@ -95,3 +95,16 @@ def authenticate_credentials(self, key):
expire_secure_token(secure_token)

return (token.user, token)


class URLTokenExpiryAuthentication(TokenExpiryAuthentication):
def authenticate(self, request):
token = request.GET.get('c_auth_with_token', b'')
if token == b'':
return

if len(token) != 40:
msg = _('Invalid token : {}'.format(repr(token)))
raise exceptions.AuthenticationFailed(msg)

return self.authenticate_credentials(token)
13 changes: 6 additions & 7 deletions concrete_datastore/api/v1/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@
from concrete_datastore.api.v1.authentication import (
TokenExpiryAuthentication,
expire_secure_token,
URLTokenExpiryAuthentication,
)
from concrete_datastore.concrete.automation.signals import user_logged_in
from concrete_datastore.concrete.meta import list_of_meta
Expand Down Expand Up @@ -420,8 +421,7 @@ def post(self, request, *args, **kwargs):
user = UserModel.objects.get(email=email.lower())
except ObjectDoesNotExist:
log_request = (
base_message
+ f"Connection attempt to unknown user {email}"
base_message + f"Connection attempt to unknown user {email}"
)
logger_api_auth.info(log_request)
return Response(
Expand All @@ -433,8 +433,7 @@ def post(self, request, *args, **kwargs):
)
if user.level == 'blocked':
log_request = (
base_message
+ f"Connection attempt to blocked user {email}"
base_message + f"Connection attempt to blocked user {email}"
)
logger_api_auth.info(log_request)
return Response(
Expand Down Expand Up @@ -1007,9 +1006,7 @@ def create_user(self, request, serializer, divider=None):
email_body = email_format.format(link=link)

if settings.AUTH_CONFIRM_EMAIL_ENABLE is True:
confirmation = user.get_or_create_confirmation(
redirect_to=link
)
confirmation = user.get_or_create_confirmation(redirect_to=link)

if confirmation.link_sent is False:
confirmation.send_link(body=email_body)
Expand Down Expand Up @@ -1158,6 +1155,7 @@ class AccountMeApiView(
authentication_classes = (
authentication.SessionAuthentication,
TokenExpiryAuthentication,
URLTokenExpiryAuthentication,
)
permission_classes = (UserAccessPermission,)
api_namespace = DEFAULT_API_NAMESPACE
Expand Down Expand Up @@ -1512,6 +1510,7 @@ class ApiModelViewSet(PaginatedViewSet, viewsets.ModelViewSet):
authentication.BasicAuthentication,
authentication.SessionAuthentication,
TokenExpiryAuthentication,
URLTokenExpiryAuthentication,
)

def dispatch(self, request, *args, **kwargs):
Expand Down
14 changes: 13 additions & 1 deletion docs/authentication.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
## Authentication

### Usage with HTTP Headers

**Note** : HTTPS shall be used to ensure privacy

It's a Token authentication system. When the user logs in, a token is generated and associated to the user. By sending a HTTP request with the token, the server knows which user made the request.

**Headers:**
Expand All @@ -8,6 +12,14 @@ It's a Token authentication system. When the user logs in, a token is generated
{"Authorization": "Token [Token]"}
```

### Usage with token in URL

**Note** : HTTPS shall be used to ensure privacy

Use the query param `c_auth_with_token=<token value>` in any URL

Ex. `/api/v1.1/project/?c_auth_with_token=xxxxx`

### Register

#### Request
Expand Down Expand Up @@ -390,7 +402,7 @@ Used to reset your own password.
"url_format": "[valid url_format]"
}
```
The url_format will be used to send the reset password email with a link to allow the user to reset his own password. It should be a string containing `"{email}"` and `"{token}"`. Example: `"/redirection-url/{email}/{token}"`.
The url_format will be used to send the reset password email with a link to allow the user to reset his own password. It should be a string containing `"{email}"` and `"{token}"`. Example: `"/redirection-url/{email}/{token}"`.

Default value: `"/#/reset-password/{token}/{email}/"`.

Expand Down
45 changes: 45 additions & 0 deletions tests/tests_api_v1_1/test_api_v1_1_auth_by_token_in_url.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# coding: utf-8
import pendulum
from rest_framework.test import APITestCase
from rest_framework import status
from django.contrib.auth import authenticate, get_user_model
from django.test import Client
from concrete_datastore.concrete.models import User, UserConfirmation
from django.test import override_settings


@override_settings(DEBUG=True)
class AuthTestCase(APITestCase):
def setUp(self):
self.user = User.objects.create_user("[email protected]")
self.user.set_password("plop")
self.user.save()
confirmation = UserConfirmation.objects.create(user=self.user)
confirmation.confirmed = True
confirmation.save()
url = "/api/v1.1/auth/login/"
resp = self.client.post(
url, {"email": "[email protected]", "password": "plop"}
)
self.token = resp.data["token"]

def test_token_authentication_in_url(self):
project_collections = "/api/v1.1/project/"
client = Client()

# Use without token to access the url_that_required_auth (401)
resp = client.post(project_collections)
self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED)

# Use token without settings headers
project_collections = "/api/v1.1/project/?c_auth_with_token={}".format(
self.token
)
resp = client.post(
project_collections,
)

self.assertEqual(
resp.status_code,
status.HTTP_201_CREATED,
)