Skip to content

Commit

Permalink
Add authentication on home view
Browse files Browse the repository at this point in the history
  • Loading branch information
brylie committed Jan 5, 2024
1 parent 8609e37 commit 7d767ac
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
8 changes: 8 additions & 0 deletions homes/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,14 @@ def members(self) -> QuerySet[user_model]:
"""Returns a QuerySet of all members of this home."""
return user_model.objects.filter(home_user_relations__home=self)

def has_access(self, user: user_model) -> bool:
"""Returns True if the user has access to this home.
- Superusers have access to all homes.
- Members of the home have access to the home.
"""
return user.is_superuser or user in self.members.all()

@property
def current_residents(self) -> models.QuerySet["Resident"]:
"""Returns a QuerySet of all current residents for this home."""
Expand Down
18 changes: 14 additions & 4 deletions homes/views.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
from typing import Any

from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import PermissionDenied
from django.shortcuts import get_object_or_404

from django.views.generic.detail import DetailView
Expand Down Expand Up @@ -37,7 +40,7 @@ def regroup_homes_by_home_group(homes):
return home_groups_with_homes


class HomeGroupListView(TemplateView):
class HomeGroupListView(LoginRequiredMixin, TemplateView):
template_name = "homes/home_group_list.html"

def get_context_data(self, **kwargs: Any) -> dict[str, Any]:
Expand Down Expand Up @@ -74,7 +77,10 @@ def get_context_data(self, **kwargs: Any) -> dict[str, Any]:
return context


class HomeDetailView(DetailView):
# user should be logged in


class HomeDetailView(LoginRequiredMixin, DetailView):
model = Home
context_object_name = "home"

Expand All @@ -89,11 +95,15 @@ def get_object(self, queryset=None):
url_uuid=url_uuid,
) # Filter the queryset based on url_uuid

obj = get_object_or_404(
home = get_object_or_404(
queryset,
) # Get the object or return a 404 error if not found

return obj
# ensure the user has access to the home
if not home.has_access(user=self.request.user):
raise PermissionDenied

return home

def prepare_activity_charts(self, context):
"""Prepare activity charts and add them to the template context."""
Expand Down

0 comments on commit 7d767ac

Please sign in to comment.