Skip to content

Commit

Permalink
remove most LoginRequiredMixin uses & simplify setup() code
Browse files Browse the repository at this point in the history
Since LoginRequiredMiddleware now ensures that the user is authenticated
  • Loading branch information
xavfernandez committed Dec 12, 2024
1 parent 9515c7d commit 8b72762
Show file tree
Hide file tree
Showing 11 changed files with 93 additions and 158 deletions.
51 changes: 21 additions & 30 deletions itou/www/apply/views/process_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,7 @@ def _show_prescriber_answer_form(wizard):
return wizard.job_application.sender_kind == job_applications_enums.SenderKind.PRESCRIBER


class JobApplicationRefuseView(LoginRequiredMixin, NamedUrlSessionWizardView):
class JobApplicationRefuseView(NamedUrlSessionWizardView):
STEP_REASON = "reason"
STEP_JOB_SEEKER_ANSWER = "job-seeker-answer"
STEP_PRESCRIBER_ANSWER = "prescriber-answer"
Expand All @@ -393,11 +393,10 @@ class JobApplicationRefuseView(LoginRequiredMixin, NamedUrlSessionWizardView):
def setup(self, request, *args, **kwargs):
super().setup(request, *args, **kwargs)

if request.user.is_authenticated:
self.job_application = get_object_or_404(
JobApplication.objects.is_active_company_member(request.user).select_related("job_seeker"),
pk=kwargs["job_application_id"],
)
self.job_application = get_object_or_404(
JobApplication.objects.is_active_company_member(request.user).select_related("job_seeker"),
pk=kwargs["job_application_id"],
)

def check_wizard_state(self, *args, **kwargs):
# Redirect to job application details if the state is not refusable
Expand Down Expand Up @@ -727,20 +726,19 @@ class ApplicationOverrideMixin:
additionnal_related_models = []

def setup(self, request, *args, **kwargs):
if request.user.is_authenticated:
self.job_application = get_object_or_404(
JobApplication.objects.is_active_company_member(request.user).select_related(
"job_seeker", "to_company", *self.additionnal_related_models
),
pk=kwargs["job_application_id"],
)
kwargs["job_seeker_public_id"] = self.job_application.job_seeker.public_id
self.job_application = get_object_or_404(
JobApplication.objects.is_active_company_member(request.user).select_related(
"job_seeker", "to_company", *self.additionnal_related_models
),
pk=kwargs["job_application_id"],
)
kwargs["job_seeker_public_id"] = self.job_application.job_seeker.public_id
return super().setup(request, *args, **kwargs)


class JobApplicationExternalTransferStep2View(ApplicationOverrideMixin, ApplicationJobsView):
def dispatch(self, request, *args, **kwargs):
if request.user.is_authenticated and self.company in request.organizations:
if self.company in request.organizations:
# This is not an external transfer
url = reverse(
"apply:job_application_internal_transfer",
Expand Down Expand Up @@ -785,7 +783,7 @@ class JobApplicationExternalTransferStep3View(ApplicationOverrideMixin, Applicat
form_class = TransferJobApplicationForm

def dispatch(self, request, *args, **kwargs):
if request.user.is_authenticated and not self.apply_session.exists():
if not self.apply_session.exists():
return HttpResponseRedirect(
reverse(
"apply:job_application_external_transfer_step_2",
Expand Down Expand Up @@ -841,11 +839,7 @@ def get_back_url(self):

class JobApplicationExternalTransferStepEndView(ApplicationEndView):
def setup(self, request, *args, **kwargs):
job_app_qs = JobApplication.objects.all()
if request.user.is_authenticated:
# Only check the user's ownership if he's authenticated
# because if he's not he will be redirected to login so we don't care
job_app_qs = JobApplication.objects.prescriptions_of(request.user, request.current_organization)
job_app_qs = JobApplication.objects.prescriptions_of(request.user, request.current_organization)

job_application = get_object_or_404(job_app_qs, pk=kwargs["job_application_id"])

Expand All @@ -863,20 +857,17 @@ def get_context_data(self, **kwargs):
}


class JobApplicationInternalTranferView(LoginRequiredMixin, TemplateView):
class JobApplicationInternalTranferView(TemplateView):
template_name = "apply/process_internal_transfer.html"

def setup(self, request, *args, **kwargs):
super().setup(request, *args, **kwargs)

if request.user.is_authenticated:
self.job_application = get_object_or_404(
JobApplication.objects.is_active_company_member(request.user).select_related(
"job_seeker", "to_company"
),
pk=kwargs["job_application_id"],
)
self.company = get_object_or_404(Company.objects.with_has_active_members(), pk=kwargs["company_pk"])
self.job_application = get_object_or_404(
JobApplication.objects.is_active_company_member(request.user).select_related("job_seeker", "to_company"),
pk=kwargs["job_application_id"],
)
self.company = get_object_or_404(Company.objects.with_has_active_members(), pk=kwargs["company_pk"])

def get_context_data(self, **kwargs):
return super().get_context_data(**kwargs) | {
Expand Down
89 changes: 31 additions & 58 deletions itou/www/apply/views/submit_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

from dateutil.relativedelta import relativedelta
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import PermissionDenied
from django.core.files.storage import storages
from django.forms import ValidationError
Expand Down Expand Up @@ -81,7 +80,7 @@ def _get_job_seeker_to_apply_for(request):
return job_seeker


class ApplyStepBaseView(LoginRequiredMixin, TemplateView):
class ApplyStepBaseView(TemplateView):
def __init__(self):
super().__init__()
self.company = None
Expand All @@ -100,36 +99,27 @@ def setup(self, request, *args, **kwargs):
)
self.apply_session = SessionNamespace(request.session, f"job_application-{self.company.pk}")
self.hire_process = kwargs.pop("hire_process", False)
self.prescription_process = (
not self.hire_process
and request.user.is_authenticated
and (
request.user.is_prescriber
or (request.user.is_employer and self.company != request.current_organization)
)
self.prescription_process = not self.hire_process and (
request.user.is_prescriber or (request.user.is_employer and self.company != request.current_organization)
)
self.auto_prescription_process = (
not self.hire_process
and request.user.is_authenticated
and request.user.is_employer
and self.company == request.current_organization
not self.hire_process and request.user.is_employer and self.company == request.current_organization
)

super().setup(request, *args, **kwargs)

def dispatch(self, request, *args, **kwargs):
if not self.is_gps:
if request.user.is_authenticated:
if self.hire_process and request.user.kind != UserKind.EMPLOYER:
raise PermissionDenied("Seuls les employeurs sont autorisés à déclarer des embauches")
elif self.hire_process and not self.company.has_member(request.user):
raise PermissionDenied("Vous ne pouvez déclarer une embauche que dans votre structure.")
elif request.user.kind not in [
UserKind.JOB_SEEKER,
UserKind.PRESCRIBER,
UserKind.EMPLOYER,
]:
raise PermissionDenied("Vous n'êtes pas autorisé à déposer de candidature.")
if self.hire_process and request.user.kind != UserKind.EMPLOYER:
raise PermissionDenied("Seuls les employeurs sont autorisés à déclarer des embauches")
elif self.hire_process and not self.company.has_member(request.user):
raise PermissionDenied("Vous ne pouvez déclarer une embauche que dans votre structure.")
elif request.user.kind not in [
UserKind.JOB_SEEKER,
UserKind.PRESCRIBER,
UserKind.EMPLOYER,
]:
raise PermissionDenied("Vous n'êtes pas autorisé à déposer de candidature.")

if not self.company.has_active_members:
raise PermissionDenied(
Expand Down Expand Up @@ -191,9 +181,6 @@ def __init__(self):

def setup(self, request, *args, **kwargs):
super().setup(request, *args, **kwargs)
if not request.user.is_authenticated:
# Do nothing, LoginRequiredMixin will raise in dispatch()
return

self.job_seeker = get_object_or_404(
User.objects.filter(kind=UserKind.JOB_SEEKER), public_id=kwargs["job_seeker_public_id"]
Expand Down Expand Up @@ -352,10 +339,7 @@ def __init__(self):

def setup(self, request, *args, **kwargs):
super().setup(request, *args, **kwargs)

if request.user.is_authenticated:
# Otherwise LoginRequiredMixin will raise in dispatch()
self.previous_applications = self.get_previous_applications_queryset()
self.previous_applications = self.get_previous_applications_queryset()

def get_next_url(self):
if self.hire_process:
Expand Down Expand Up @@ -452,7 +436,7 @@ def get_context_data(self, **kwargs):

class RequireApplySessionMixin:
def dispatch(self, request, *args, **kwargs):
if request.user.is_authenticated and not self.apply_session.exists():
if not self.apply_session.exists():
return HttpResponseRedirect(
reverse(
"apply:application_jobs",
Expand Down Expand Up @@ -495,22 +479,20 @@ def get_next_url(self):
)

def dispatch(self, request, *args, **kwargs):
if request.user.is_authenticated:
# Otherwise LoginRequiredMixin will raise in dispatch()
bypass_eligibility_conditions = [
# Don't perform an eligibility diagnosis is the SIAE doesn't need it,
not self.company.is_subject_to_eligibility_rules,
# Only "authorized prescribers" can perform an eligibility diagnosis.
not (
request.user.is_prescriber
and request.current_organization
and request.current_organization.is_authorized
),
# No need for eligibility diagnosis if the job seeker already have a PASS IAE
self.job_seeker.has_valid_approval,
]
if any(bypass_eligibility_conditions):
return HttpResponseRedirect(self.get_next_url())
bypass_eligibility_conditions = [
# Don't perform an eligibility diagnosis is the SIAE doesn't need it,
not self.company.is_subject_to_eligibility_rules,
# Only "authorized prescribers" can perform an eligibility diagnosis.
not (
request.user.is_prescriber
and request.current_organization
and request.current_organization.is_authorized
),
# No need for eligibility diagnosis if the job seeker already have a PASS IAE
self.job_seeker.has_valid_approval,
]
if any(bypass_eligibility_conditions):
return HttpResponseRedirect(self.get_next_url())

return super().dispatch(request, *args, **kwargs)

Expand Down Expand Up @@ -560,10 +542,6 @@ def __init__(self):

def setup(self, request, *args, **kwargs):
super().setup(request, *args, **kwargs)
if not request.user.is_authenticated:
# Do nothing, LoginRequiredMixin will raise in dispatch()
return

if self.company.kind != CompanyKind.GEIQ:
raise Http404("This form is only for GEIQ")

Expand All @@ -589,7 +567,7 @@ def get_next_url(self):

def dispatch(self, request, *args, **kwargs):
# GEIQ eligibility form during job application process is only available to authorized prescribers
if request.user.is_authenticated and not request.user.is_prescriber_with_authorized_org:
if not request.user.is_prescriber_with_authorized_org:
return HttpResponseRedirect(self.get_next_url())

return super().dispatch(request, *args, **kwargs)
Expand Down Expand Up @@ -652,11 +630,6 @@ def get_form_kwargs(self):

def setup(self, request, *args, **kwargs):
super().setup(request, *args, **kwargs)

if not request.user.is_authenticated:
# Do nothing, LoginRequiredMixin will raise in dispatch()
return

self.form = self.form_class(**self.get_form_kwargs())

def get_next_url(self, job_application):
Expand Down
47 changes: 20 additions & 27 deletions itou/www/approvals_views/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.auth.mixins import UserPassesTestMixin
from django.core.exceptions import PermissionDenied
from django.core.files.storage import default_storage
from django.db import IntegrityError
Expand Down Expand Up @@ -53,7 +53,7 @@
logger = logging.getLogger(__name__)


class ApprovalBaseViewMixin(LoginRequiredMixin):
class ApprovalBaseViewMixin:
model = Approval

def __init__(self):
Expand All @@ -62,11 +62,10 @@ def __init__(self):

def setup(self, request, *args, **kwargs):
super().setup(request, *args, **kwargs)
if request.user.is_authenticated:
self.siae = get_current_company_or_404(request)
self.siae = get_current_company_or_404(request)

if not self.siae.is_subject_to_eligibility_rules:
raise PermissionDenied
if not self.siae.is_subject_to_eligibility_rules:
raise PermissionDenied

def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
Expand Down Expand Up @@ -126,7 +125,7 @@ def get_context_data(self, **kwargs):
return context


class ApprovalDetailView(LoginRequiredMixin, UserPassesTestMixin, DetailView):
class ApprovalDetailView(UserPassesTestMixin, DetailView):
model = Approval
queryset = Approval.objects.select_related("user__jobseeker_profile").prefetch_related(
# Useful for get_suspensions method and the approval remainder field
Expand All @@ -138,10 +137,8 @@ class ApprovalDetailView(LoginRequiredMixin, UserPassesTestMixin, DetailView):
template_name = "approvals/details.html"

def test_func(self):
return self.request.user.is_authenticated and (
# More checks are performed in get_context_data method
self.request.user.is_prescriber or self.request.user.is_employer or self.request.user.is_job_seeker
)
# More checks are performed in get_context_data method
return self.request.user.is_prescriber or self.request.user.is_employer or self.request.user.is_job_seeker

def get_prolongation_and_requests(self, approval):
def _format_for_template(user, org):
Expand Down Expand Up @@ -406,11 +403,10 @@ def _clear_errors(self):
def setup(self, request, approval_id, *args, **kwargs):
super().setup(request, *args, **kwargs)

if request.user.is_authenticated:
self.siae = get_current_company_or_404(request)
if not self.siae.is_subject_to_eligibility_rules:
raise PermissionDenied()
self.approval = get_object_or_404(Approval, pk=approval_id)
self.siae = get_current_company_or_404(request)
if not self.siae.is_subject_to_eligibility_rules:
raise PermissionDenied()
self.approval = get_object_or_404(Approval, pk=approval_id)

if not self.approval.can_be_prolonged:
raise PermissionDenied()
Expand Down Expand Up @@ -507,20 +503,17 @@ def prolongation_request_report_file(request, prolongation_request_id):
return HttpResponseRedirect(default_storage.url(prolongation_request.report_file_id))


class ProlongationRequestViewMixin(LoginRequiredMixin):
class ProlongationRequestViewMixin:
def setup(self, request, *args, **kwargs):
super().setup(request, *args, **kwargs)

if request.user.is_authenticated:
self.prolongation_request = get_object_or_404(
ProlongationRequest.objects.filter(
prescriber_organization=get_current_org_or_404(request)
).select_related(
"approval__user",
"deny_information",
),
pk=kwargs["prolongation_request_id"],
)
self.prolongation_request = get_object_or_404(
ProlongationRequest.objects.filter(prescriber_organization=get_current_org_or_404(request)).select_related(
"approval__user",
"deny_information",
),
pk=kwargs["prolongation_request_id"],
)

def get_context_data(self, **kwargs):
return super().get_context_data(**kwargs) | {
Expand Down
5 changes: 2 additions & 3 deletions itou/www/dashboard/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from django.contrib import auth, messages
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import PermissionDenied
from django.db.models import F
from django.http import Http404, HttpResponseForbidden, HttpResponseRedirect
Expand Down Expand Up @@ -388,11 +387,11 @@ def api_token(request, template_name="dashboard/api_token.html"):
return render(request, template_name, context)


class AccountMigrationView(LoginRequiredMixin, TemplateView):
class AccountMigrationView(TemplateView):
template_name = "account/activate_inclusion_connect_account.html"

def dispatch(self, request, *args, **kwargs):
if request.user.is_authenticated and request.user.kind not in MATOMO_ACCOUNT_TYPE:
if request.user.kind not in MATOMO_ACCOUNT_TYPE:
return HttpResponseRedirect(reverse("dashboard:index"))
return super().dispatch(request, *args, **kwargs)

Expand Down
Loading

0 comments on commit 8b72762

Please sign in to comment.