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

Production Release 24.46.0 #2594

Merged
merged 9 commits into from
Nov 11, 2024
2 changes: 1 addition & 1 deletion care/facility/api/viewsets/mixins/access.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

class UserAccessMixin:
def get_queryset(self):
queryset = self.queryset
queryset = super().get_queryset()
model = self.queryset.__dict__["model"]

if not self.request.user.is_superuser:
Expand Down
13 changes: 6 additions & 7 deletions care/facility/api/viewsets/patient_consultation.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,9 @@ def get_permissions(self):
return super().get_permissions()

def get_queryset(self):
queryset = super().get_queryset()
if self.serializer_class == PatientConsultationSerializer:
self.queryset = self.queryset.prefetch_related(
queryset = queryset.prefetch_related(
"assigned_to",
Prefetch(
"assigned_to__skills",
Expand All @@ -95,13 +96,11 @@ def get_queryset(self):
"current_bed__assets__current_location",
)
if self.request.user.is_superuser:
return self.queryset
return queryset
if self.request.user.user_type >= User.TYPE_VALUE_MAP["StateLabAdmin"]:
return self.queryset.filter(
patient__facility__state=self.request.user.state
)
return queryset.filter(patient__facility__state=self.request.user.state)
if self.request.user.user_type >= User.TYPE_VALUE_MAP["DistrictLabAdmin"]:
return self.queryset.filter(
return queryset.filter(
patient__facility__district=self.request.user.district
)
allowed_facilities = get_accessible_facilities(self.request.user)
Expand All @@ -111,7 +110,7 @@ def get_queryset(self):
)
# A user should be able to see all consultations part of their home facility
applied_filters |= Q(facility=self.request.user.home_facility)
return self.queryset.filter(applied_filters)
return queryset.filter(applied_filters)

@transaction.non_atomic_requests
def create(self, request, *args, **kwargs) -> Response:
Expand Down
2 changes: 1 addition & 1 deletion care/facility/api/viewsets/patient_external_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ class PatientExternalTestViewSet(
parser_classes = (MultiPartParser, FormParser, JSONParser)

def get_queryset(self):
queryset = self.queryset
queryset = super().get_queryset()
if not self.request.user.is_superuser:
if self.request.user.user_type >= User.TYPE_VALUE_MAP["StateLabAdmin"]:
queryset = queryset.filter(district__state=self.request.user.state)
Expand Down
2 changes: 1 addition & 1 deletion care/facility/api/viewsets/patient_otp_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class OTPPatientDataViewSet(RetrieveModelMixin, ListModelMixin, GenericViewSet):

def get_queryset(self):
is_otp_login = getattr(self.request.user, "is_alternative_login", False)
queryset = self.queryset
queryset = super().get_queryset()
if is_otp_login:
queryset = queryset.filter(phone_number=self.request.user.phone_number)
else:
Expand Down
7 changes: 4 additions & 3 deletions care/facility/api/viewsets/shifting.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,16 +109,17 @@ class ShiftingViewSet(
filterset_class = ShiftingFilterSet

def get_queryset(self) -> QuerySet:
queryset = super().get_queryset()
if self.action == "list":
self.queryset = self.queryset.select_related(
queryset = queryset.select_related(
"origin_facility",
"shifting_approving_facility",
"assigned_facility",
"patient",
)

else:
self.queryset = self.queryset.select_related(
queryset = queryset.select_related(
"origin_facility",
"origin_facility__ward",
"origin_facility__local_body",
Expand Down Expand Up @@ -148,7 +149,7 @@ def get_queryset(self) -> QuerySet:
"created_by",
"last_edited_by",
)
return self.queryset
return queryset

def get_serializer_class(self):
serializer_class = self.serializer_class
Expand Down
11 changes: 11 additions & 0 deletions care/facility/management/commands/load_redis_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,17 @@ class Command(BaseCommand):
help = "Loads static data to redis"

def handle(self, *args, **options):
try:
deleted_count = cache.delete_pattern("care_static_data*", itersize=25_000)
self.stdout.write(
f"Deleted {deleted_count} keys with prefix 'care_static_data'"
)
except Exception as e:
self.stdout.write(
f"Failed to delete keys with prefix 'care_static_data': {e}"
)
return

if cache.get("redis_index_loading"):
self.stdout.write("Redis Index already loading, skipping")
return
Expand Down
7 changes: 5 additions & 2 deletions care/facility/tasks/cleanup.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
from datetime import timedelta

from celery import shared_task
from django.conf import settings
from django.utils import timezone

from care.facility.models.notification import Notification


@shared_task
def delete_old_notifications():
ninety_days_ago = timezone.now() - timedelta(days=90)
Notification.objects.filter(created_date__lte=ninety_days_ago).delete()
retention_days = settings.NOTIFICATION_RETENTION_DAYS

threshold_date = timezone.now() - timedelta(days=retention_days)
Notification.objects.filter(created_date__lte=threshold_date).delete()
11 changes: 9 additions & 2 deletions care/facility/tasks/redis_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@

@shared_task
def load_redis_index():
try:
deleted_count = cache.delete_pattern("care_static_data*", itersize=25_000)
logger.info("Deleted %s keys with prefix 'care_static_data'", deleted_count)
except Exception as e:
logger.error("Failed to delete keys with prefix 'care_static_data': %s", e)
return

if cache.get("redis_index_loading"):
logger.info("Redis Index already loading, skipping")
return
Expand All @@ -37,9 +44,9 @@ def load_redis_index():
if load_static_data:
load_static_data()
except ModuleNotFoundError:
logger.info("Module %s not found", module_path)
logger.debug("Module %s not found", module_path)
except Exception as e:
logger.info("Error loading static data for %s: %s", plug.name, e)
logger.error("Error loading static data for %s: %s", plug.name, e)

cache.delete("redis_index_loading")
logger.info("Redis Index Loaded")
7 changes: 5 additions & 2 deletions care/facility/tests/test_delete_older_notifications_task.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from datetime import timedelta

from django.conf import settings
from django.test import TestCase
from django.utils import timezone
from freezegun import freeze_time
Expand All @@ -10,8 +11,10 @@

class DeleteOldNotificationsTest(TestCase):
def test_delete_old_notifications(self):
# notifications created 90 days ago
with freeze_time(timezone.now() - timedelta(days=90)):
retention_days = settings.NOTIFICATION_RETENTION_DAYS

# notifications created at the threshold of retention
with freeze_time(timezone.now() - timedelta(days=retention_days)):
notification1 = Notification.objects.create()
notification2 = Notification.objects.create()

Expand Down
1 change: 1 addition & 0 deletions care/facility/tests/test_patient_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ class ExpectedCreatedByObjectKeys(Enum):
LAST_NAME = "last_name"
USER_TYPE = "user_type"
LAST_LOGIN = "last_login"
READ_PROFILE_PICTURE_URL = "read_profile_picture_url"


class PatientNotesTestCase(TestUtils, APITestCase):
Expand Down
Empty file added care/security/__init__.py
Empty file.
11 changes: 11 additions & 0 deletions care/security/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _


class SecurityConfig(AppConfig):
name = "care.security"
verbose_name = _("Security Management")

def ready(self):
# import care.security.signals # noqa F401
pass
Empty file.
88 changes: 88 additions & 0 deletions care/security/authorization/base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
from care.security.permissions.base import PermissionController


class PermissionDeniedError(Exception):
pass


class AuthorizationHandler:
"""
This is the base class for Authorization Handlers
Authorization handler must define a list of actions that can be performed and define the methods that
actually perform the authorization action.

All Authz methods would be of the signature ( user, obj , **kwargs )
obj refers to the obj which the user is seeking permission to. obj can also be a string or any datatype as long
as the logic can handle the type.

Queries are actions that return a queryset as the response.
"""

actions = []
queries = []

def check_permission(self, user, obj):
if not PermissionController.has_permission(user, obj):
raise PermissionDeniedError

return PermissionController.has_permission(user, obj)


class AuthorizationController:
"""
This class abstracts all security related operations in care
This includes Checking if A has access to resource X,
Filtering query-sets for list based operations and so on.
Security Controller implicitly caches all cachable operations and expects it to be invalidated.

SecurityController maintains a list of override Classes, When present,
The override classes are invoked first and then the predefined classes.
The overridden classes can choose to call the next function in the hierarchy if needed.
"""

override_authz_controllers: list[
AuthorizationHandler
] = [] # The order is important
# Override Security Controllers will be defined from plugs
internal_authz_controllers: list[AuthorizationHandler] = []

cache = {}

@classmethod
def build_cache(cls):
for controller in (
cls.internal_authz_controllers + cls.override_authz_controllers
):
for action in controller.actions:
if "actions" not in cls.cache:
cls.cache["actions"] = {}
cls.cache["actions"][action] = [
*cls.cache["actions"].get(action, []),
controller,
]

@classmethod
def get_action_controllers(cls, action):
return cls.cache["actions"].get(action, [])

@classmethod
def check_action_permission(cls, action, user, obj):
"""
TODO: Add Caching and capability to remove cache at both user and obj level
"""
if not cls.cache:
cls.build_cache()
controllers = cls.get_action_controllers(action)
for controller in controllers:
permission_fn = getattr(controller, action)
result, _continue = permission_fn(user, obj)
if not _continue:
return result
if not result:
return result
return True

@classmethod
def register_internal_controller(cls, controller: AuthorizationHandler):
# TODO : Do some deduplication Logic
cls.internal_authz_controllers.append(controller)
22 changes: 22 additions & 0 deletions care/security/authorization/facility.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from care.abdm.utils.api_call import Facility
from care.facility.models import FacilityUser
from care.security.authorization.base import (
AuthorizationHandler,
PermissionDeniedError,
)


class FacilityAccess(AuthorizationHandler):
actions = ["can_read_facility"]
queries = ["allowed_facilities"]

def can_read_facility(self, user, facility_id):
self.check_permission(user, facility_id)
# Since the old method relied on a facility-user relationship, check that
# This can be removed when the migrations have been completed
if not FacilityUser.objects.filter(facility_id=facility_id, user=user).exists():
raise PermissionDeniedError
return True, True

def allowed_facilities(self, user):
return Facility.objects.filter(users__id__exact=user.id)
Empty file.
Empty file.
65 changes: 65 additions & 0 deletions care/security/management/commands/sync_permissions_roles.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
from django.core.management import BaseCommand
from django.db import transaction

from care.security.models import PermissionModel, RoleModel, RolePermission
from care.security.permissions.base import PermissionController
from care.security.roles.role import RoleController
from care.utils.lock import Lock


class Command(BaseCommand):
"""
This command syncs roles, permissions and role-permission mapping to the database.
This command should be run after all deployments and plug changes.
This command is idempotent, multiple instances running the same command is automatically blocked with redis.
"""

help = "Syncs permissions and roles to database"

def handle(self, *args, **options):
permissions = PermissionController.get_permissions()
roles = RoleController.get_roles()
with transaction.atomic(), Lock("sync_permissions_roles", 900):
# Create, update permissions and delete old permissions
PermissionModel.objects.all().update(temp_deleted=True)
for permission, metadata in permissions.items():
permission_obj = PermissionModel.objects.filter(slug=permission).first()
if not permission_obj:
permission_obj = PermissionModel(slug=permission)
permission_obj.name = metadata.name
permission_obj.description = metadata.description
permission_obj.context = metadata.context.value
permission_obj.temp_deleted = False
permission_obj.save()
PermissionModel.objects.filter(temp_deleted=True).delete()
# Create, update roles and delete old roles
RoleModel.objects.all().update(temp_deleted=True)
for role in roles:
role_obj = RoleModel.objects.filter(
name=role.name, context=role.context.value
).first()
if not role_obj:
role_obj = RoleModel(name=role.name, context=role.context.value)
role_obj.description = role.description
role_obj.is_system = True
role_obj.temp_deleted = False
role_obj.save()
RoleModel.objects.filter(temp_deleted=True).delete()
# Sync permissions to role
RolePermission.objects.all().update(temp_deleted=True)
role_cache = {}
for permission, metadata in permissions.items():
permission_obj = PermissionModel.objects.filter(slug=permission).first()
for role in metadata.roles:
if role.name not in role_cache:
role_cache[role.name] = RoleModel.objects.get(name=role.name)
obj = RolePermission.objects.filter(
role=role_cache[role.name], permission=permission_obj
).first()
if not obj:
obj = RolePermission(
role=role_cache[role.name], permission=permission_obj
)
obj.temp_deleted = False
obj.save()
RolePermission.objects.filter(temp_deleted=True).delete()
Loading
Loading