hobo/tests_authentic/test_rest_authentication.py

74 lines
2.6 KiB
Python

import pytest
import urllib
from rest_framework.exceptions import AuthenticationFailed
from django.contrib.auth import get_user_model
from django.test import RequestFactory
from tenant_schemas.utils import tenant_context
from hobo import signature, rest_authentication
pytestmark = pytest.mark.django_db
def test_publik_authentication(tenant, settings):
settings.HOBO_ANONYMOUS_SERVICE_USER_CLASS = \
'hobo.rest_authentication.AnonymousAdminServiceUser'
with tenant_context(tenant):
key = settings.KNOWN_SERVICES['welco']['other']['secret']
settings.HOBO_ROLE_EXPORT = False
User = get_user_model()
user = User.objects.create(username='foo', password='foo')
ORIG = 'other.example.net'
AUTH_QUERY = '&NameID=%s&orig=%s' % (user.uuid, urllib.quote(ORIG))
URL = '/api/?coucou=zob'
factory = RequestFactory()
request = factory.get(signature.sign_url(URL + AUTH_QUERY, key))
publik_authentication = rest_authentication.PublikAuthentication()
result = publik_authentication.authenticate(request)
assert result is not None
assert isinstance(result, tuple)
assert len(result) == 2
assert result[0] == user
assert result[1] is None
# Test anonymous user
AUTH_QUERY = '&orig=%s' % urllib.quote(ORIG)
request = factory.get(signature.sign_url(URL + AUTH_QUERY, key))
publik_authentication = rest_authentication.PublikAuthentication()
result = publik_authentication.authenticate(request)
assert result is not None
assert isinstance(result, tuple)
assert len(result) == 2
assert result[0].__class__ is rest_authentication.AnonymousAdminServiceUser
assert result[0].is_authenticated
assert result[0].is_staff
assert result[1] is None
# Test user named after service orig
service_user = User.objects.create(username=ORIG)
AUTH_QUERY = '&orig=%s' % urllib.quote(ORIG)
request = factory.get(signature.sign_url(URL + AUTH_QUERY, key))
publik_authentication = rest_authentication.PublikAuthentication()
result = publik_authentication.authenticate(request)
assert result is not None
assert isinstance(result, tuple)
assert len(result) == 2
assert result[0] == service_user
assert result[1] is None
# Failure
request = factory.get(signature.sign_url(URL + AUTH_QUERY, key + 'zob'))
publik_authentication = rest_authentication.PublikAuthentication()
with pytest.raises(AuthenticationFailed):
publik_authentication.authenticate(request)