Skip to content

Commit

Permalink
feat: add mycarehub oauth provider (#207)
Browse files Browse the repository at this point in the history
  • Loading branch information
Muchogoc committed May 4, 2023
1 parent 0dbabac commit fd0c7d7
Show file tree
Hide file tree
Showing 41 changed files with 588 additions and 1,493 deletions.
1 change: 0 additions & 1 deletion .github/workflows/multitenant-staging.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ on:
push:
branches:
- develop-v2
- deploy-multitenant-k8s

env:
DJANGO_SETTINGS_MODULE: "config.settings.production"
Expand Down
24 changes: 0 additions & 24 deletions config/graphql_auth.py

This file was deleted.

36 changes: 27 additions & 9 deletions config/settings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,6 @@
"mjml",
"oauth2_provider",
"django.contrib.admin",
"graphene_django",
"wagtail.contrib.forms",
"wagtail.contrib.redirects",
"wagtail.embeds",
Expand Down Expand Up @@ -115,6 +114,7 @@
"mycarehub.home.apps.HomeConfig",
"mycarehub.content.apps.ContentConfig",
"mycarehub.clients.apps.ClientsConfig",
"mycarehub.mchprovider",
]
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS

Expand All @@ -129,8 +129,9 @@
"allauth.account.auth_backends.AuthenticationBackend",
]
AUTH_USER_MODEL = "users.User"
LOGIN_REDIRECT_URL = "users:redirect"
LOGIN_URL = "account_login"

LOGIN_REDIRECT_URL = "wagtailadmin_home"
LOGIN_URL = "wagtailadmin_login"

# PASSWORDS
# ------------------------------------------------------------------------------
Expand Down Expand Up @@ -281,20 +282,38 @@

# django-allauth
# ------------------------------------------------------------------------------
ACCOUNT_ALLOW_REGISTRATION = env.bool("DJANGO_ACCOUNT_ALLOW_REGISTRATION", True)
ACCOUNT_ALLOW_REGISTRATION = True
ACCOUNT_AUTHENTICATION_METHOD = "username"
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_EMAIL_VERIFICATION = "mandatory"
ACCOUNT_EMAIL_REQUIRED = False
ACCOUNT_EMAIL_VERIFICATION = "none"
ACCOUNT_ADAPTER = "mycarehub.users.adapters.AccountAdapter"
SOCIALACCOUNT_ADAPTER = "mycarehub.users.adapters.SocialAccountAdapter"
ACCOUNT_LOGOUT_ON_PASSWORD_CHANGE = True
ACCOUNT_SESSION_REMEMBER = None # ask the user 'Remember me'
ACCOUNT_SIGNUP_EMAIL_ENTER_TWICE = True
ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = True
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_USERNAME_MIN_LENGTH = 5
ACCOUNT_DEFAULT_HTTP_PROTOCOL = env.str("DJANGO_ACCOUNT_DEFAULT_HTTP_PROTOCOL", default="https")

SOCIALACCOUNT_ADAPTER = "mycarehub.users.adapters.SocialAccountAdapter"
SOCIALACCOUNT_AUTO_SIGNUP = True
ACCOUNT_DEFAULT_HTTP_PROTOCOL = "https"
SOCIALACCOUNT_EMAIL_VERIFICATION = ACCOUNT_EMAIL_VERIFICATION
SOCIALACCOUNT_EMAIL_REQUIRED = ACCOUNT_EMAIL_REQUIRED
SOCIALACCOUNT_LOGIN_ON_GET = False
SOCIALACCOUNT_PROVIDERS = {
"mycarehub": {
"APP": {
"client_id": env.str("MYCAREHUB_CLIENT_ID", default=""),
"secret": env.str("MYCAREHUB_CLIENT_SECRET", default=""),
},
"VERIFIED_EMAIL": True,
"ACCESS_TOKEN_URL": env.str("MYCAREHUB_ACCESS_TOKEN_URL", default=""),
"AUTHORIZE_URL": env.str("MYCAREHUB_AUTHORIZE_URL", default=""),
"INTROSPECT_URL": env.str("MYCAREHUB_INTROSPECT_URL", default=""),
}
}
SOCIALACCOUNT_QUERY_EMAIL = False
SOCIALACCOUNT_STORE_TOKENS = True

# django-compressor
# ------------------------------------------------------------------------------
Expand Down Expand Up @@ -449,7 +468,6 @@
],
)

GRAPHENE = {"SCHEMA": "mycarehub.schema.schema.schema"}
API_VERSION = "0.0.1"

# debug_toolbar
Expand Down
8 changes: 0 additions & 8 deletions config/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.urls import include, path, re_path
from django.views import defaults as default_views
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import RedirectView, TemplateView
from rest_framework.authtoken.views import obtain_auth_token
from rest_framework.schemas import get_schema_view
Expand All @@ -26,8 +25,6 @@
media_index,
)

from .graphql_auth import DRFAuthenticatedGraphQLView

urlpatterns = [
path("sysadmin/", HomeView.as_view(), name="home"),
re_path(
Expand All @@ -43,11 +40,6 @@
path("users/", include("mycarehub.users.urls", namespace="users")),
path("accounts/", include("allauth.urls")),
path("common/", include("mycarehub.common.urls", namespace="common")),
path(
"graphql",
csrf_exempt(DRFAuthenticatedGraphQLView.as_view(graphiql=True)),
name="graphql",
),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
# Static file serving when using Gunicorn + Uvicorn for local web socket development
Expand Down
15 changes: 0 additions & 15 deletions mycarehub/common/renderers.py

This file was deleted.

54 changes: 2 additions & 52 deletions mycarehub/common/tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,6 @@

from mycarehub.common.constants import WHITELIST_COUNTIES
from mycarehub.common.models import Facility, Organisation, Program, UserFacilityAllotment
from mycarehub.common.serializers import FacilitySerializer

from .test_utils import patch_baker

DIR_PATH = path.join(path.dirname(path.abspath(__file__)))
MEDIA_PATH = path.join(DIR_PATH, "media")
Expand Down Expand Up @@ -87,13 +84,6 @@ def setUp(self):

assert self.client.login(username=username, password="pass123") is True

self.patch_organisation = partial(
patch_baker, values={"organisation": self.global_organisation}
)
self.org_patcher = self.patch_organisation()
self.org_patcher.start()
self.addCleanup(self.org_patcher.stop)

headers = self.extra_headers()
self.client.get = partial(self.client.get, **headers)
self.client.patch = partial(self.client.patch, **headers)
Expand Down Expand Up @@ -375,7 +365,7 @@ def test_delete(self):
)
self.assertEqual(
response.status_code,
302,
200,
)


Expand Down Expand Up @@ -542,50 +532,10 @@ def test_delete(self):
)
self.assertEqual(
response.status_code,
302,
200,
)


class DRFSerializerExcelIOMixinTest(LoggedInMixin, APITestCase):
"""Test suite for excel io mixin API."""

def setUp(self) -> None:
super().setUp()

versions = baker.make(Facility, 10, organisation=self.global_organisation)
self.data = FacilitySerializer(versions, many=True).data

def test_dump_data(self) -> None:
"""Test `dump_data` action."""

url = reverse("api:facility-dump-data")
data = {"dump_fields": ["name", "mfl_code", "county"]}
response = self.client.get(url, data=data)

assert response.status_code == status.HTTP_200_OK
assert response["content-disposition"] == "attachment; filename=facilities.xlsx"
assert response["content-type"] == "application/xlsx; charset=utf-8"

def test_get_available_fields(self) -> None:
"""Test the `get_available_fields` action."""

url = reverse("api:facility-get-available-fields")
response = self.client.get(url)

assert response.status_code == status.HTTP_200_OK, response.json()
assert len(response.data) == 1
assert response.data[0]["id"] == "*"

def test_get_filter_form(self) -> None:
"""Test the `get_filter_form` action."""

url = reverse("api:facility-get-filter-form")
response = self.client.get(url)

assert response.status_code == status.HTTP_200_OK
assert response["content-type"] == "text/html; charset=utf-8"


def test_organisation_registration(user_with_all_permissions, client):
client.force_login(user_with_all_permissions)
url = reverse("api:organisations-general")
Expand Down
2 changes: 1 addition & 1 deletion mycarehub/common/tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ def test_timezone(self):
# It is already timezone aware
assert timezone.is_aware(instance.created)
created_naive_datetime = datetime.datetime.now()
instance.create = created_naive_datetime # This should not even update
instance.created = created_naive_datetime # This should not even update
instance.save()
assert timezone.is_aware(instance.created)

Expand Down
28 changes: 0 additions & 28 deletions mycarehub/common/tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
"""Define utilities used in test."""
from functools import partial
from unittest.mock import patch

from model_bakery import baker


def compare_dict(dict1, dict2):
Expand All @@ -25,30 +21,6 @@ def compare_dict(dict1, dict2):
return True


def mock_baker(values):
"""Create test fixture."""
assert isinstance(values, dict), (
"Expects " "{field_name, field_value} dict. " f"Found {type(values)}"
)

class _Baker(baker.Baker):
fields = values

def _get_field_names(self):
return [each.name for each in self.get_fields()]

def _make(self, *args, **attrs):
for field_name, value in self.fields.items():
if field_name in self._get_field_names():
attrs.setdefault(field_name, value)
return super()._make(*args, **attrs)

return _Baker


patch_baker = partial(patch, "model_bakery.baker.Baker", new_callable=mock_baker)


def make_transitions(obj, transitions, note={}):
"""Change state of organisation."""
for each in transitions:
Expand Down
34 changes: 1 addition & 33 deletions mycarehub/common/tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@
from django.urls import reverse
from rest_framework import status

from mycarehub.common.models import Facility
from mycarehub.common.serializers import FacilitySerializer
from mycarehub.common.views import DRFSerializerExcelIOMixin, HomeView
from mycarehub.utils.excel_utils import DRFSerializerExcelIO, DRFSerializerExcelIOTemplate
from mycarehub.common.views import HomeView

pytestmark = pytest.mark.django_db

Expand Down Expand Up @@ -46,32 +43,3 @@ def test_user_facility_allotment_view(user_with_all_permissions, client):
url = reverse("common:user_facility_allotments")
response = client.get(url)
assert response.status_code == status.HTTP_200_OK


def test_drf_excel_io_mixin_get_filter_form(rf, user_with_all_permissions):
url = reverse("api:facility-dump-data")
request = rf.get(url)
request.user = user_with_all_permissions
response = DRFSerializerExcelIOMixin.as_view(
{"get": "get_filter_form"},
excel_io_class=DRFSerializerExcelIO,
excel_io_template_class=DRFSerializerExcelIOTemplate,
queryset=Facility.objects.mycarehub_facilities(),
serializer_class=FacilitySerializer,
)(request=request)

assert response.status_code == status.HTTP_200_OK


def test_graphql_view_initialization(user_with_all_permissions, client):
client.force_login(user_with_all_permissions)
url = reverse("graphql")
response = client.post(
url,
data={"query": "query { hello }"},
content_type="application/json",
accept="application/json",
)

print(response.content)
assert response.status_code == status.HTTP_200_OK
8 changes: 1 addition & 7 deletions mycarehub/common/views/base_views/drf_base_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,14 @@
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from mycarehub.utils.excel_utils import AuditSerializerExcelIO

from ..mixins import AuditSerializerExcelIOMixin


class BaseView(ModelViewSet, AuditSerializerExcelIOMixin):
class BaseView(ModelViewSet):
"""Base class for most application views.
This view's `create` method has been extended to support the creation of
a single or multiple records.
"""

excel_io_class = AuditSerializerExcelIO

def create(self, request, *args, **kwargs):
"""Create and persist single or multiple records."""

Expand Down
4 changes: 0 additions & 4 deletions mycarehub/common/views/mixins/__init__.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
from .drf_mixins import AuditSerializerExcelIOMixin, DRFSerializerExcelIOMixin, ExcelIOMixin
from .vanilla_mixins import ApprovedMixin, BaseFormMixin

__all__ = [
"ApprovedMixin",
"AuditSerializerExcelIOMixin",
"BaseFormMixin",
"DRFSerializerExcelIOMixin",
"ExcelIOMixin",
]
Loading

0 comments on commit fd0c7d7

Please sign in to comment.