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

fix: Added tests for access tokens, validate if test token #824

Merged
merged 2 commits into from
Sep 25, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
3 changes: 3 additions & 0 deletions terraso_backend/apps/auth/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,9 @@ def _get_user_from_jwt(self, request):
except InvalidTokenError as e:
logger.exception("Failure to verify JWT token", extra={"token": token})
raise ValidationError(f"Invalid JWT token: {e}")
except ValueError as e:
logger.exception("Not valid JWT token type", extra={"token": token})
raise ValidationError(f"Invalid JWT token: {e}")

user = self._get_user(decoded_payload["sub"])

Expand Down
6 changes: 5 additions & 1 deletion terraso_backend/apps/auth/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,11 @@ def create_access_token(self, user):

def verify_access_token(self, token):
decoded = self._verify_token(token)
if not decoded["access"] or not decoded["exp"]:
is_access_token = decoded.get("access", False)
is_test_token = decoded.get("test", False)
has_expiration = decoded.get("exp", False)
can_access = is_access_token and (has_expiration or is_test_token)
if not can_access:
raise ValueError("Token is not an access token")
return decoded

Expand Down
86 changes: 86 additions & 0 deletions terraso_backend/tests/auth/test_access_tokens.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# Copyright © 2021-2023 Technology Matters
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see https://www.gnu.org/licenses/.
import pytest
from graphene_django.utils.testing import graphql_query

from apps.auth.services import JWTService

pytestmark = pytest.mark.django_db


@pytest.fixture
def user(users):
return users[0]


@pytest.fixture
def access_token(user):
return JWTService().create_access_token(user)


@pytest.fixture
def test_access_token(user):
return JWTService().create_test_access_token(user)


@pytest.fixture
def invalid_access_token(user):
return JWTService().create_token(user)


@pytest.fixture
def token_client_query(client):
def _client_query(token, *args, **kwargs):
headers = {
"CONTENT_TYPE": "application/json",
"HTTP_AUTHORIZATION": f"Bearer {token}",
}
return graphql_query(*args, **kwargs, headers=headers, client=client)

return _client_query


def execute_query(token_client_query, user, token):
query = (
"""
{users(email: "%s") {
edges {
node {
email
}
}
}}
"""
% user.email
)
response = token_client_query(token, query)
return response.json()


def test_access_token_valid(token_client_query, user, access_token):
response = execute_query(token_client_query, user, access_token)
user_result = response["data"]["users"]["edges"][0]["node"]
assert user_result["email"] == user.email


def test_test_access_token_valid(token_client_query, user, test_access_token):
response = execute_query(token_client_query, user, test_access_token)
user_result = response["data"]["users"]["edges"][0]["node"]
assert user_result["email"] == user.email


def test_access_token_invalid(token_client_query, user, invalid_access_token):
response = execute_query(token_client_query, user, invalid_access_token)
assert response["error"] == "Unauthorized request"