plateforme-corres2math/apps/registration/views.py

305 lines
11 KiB
Python
Raw Normal View History

2020-09-27 10:36:37 +00:00
import os
from corres2math.tokens import email_validation_token
2020-09-22 17:37:37 +00:00
from django.conf import settings
from django.contrib.auth.mixins import LoginRequiredMixin
2020-09-22 10:27:03 +00:00
from django.contrib.auth.models import User
2020-09-27 14:52:52 +00:00
from django.core.exceptions import PermissionDenied, ValidationError
2020-09-22 10:27:03 +00:00
from django.db import transaction
2020-09-27 10:49:10 +00:00
from django.http import FileResponse, Http404
from django.shortcuts import redirect, resolve_url
2020-09-22 10:27:03 +00:00
from django.urls import reverse_lazy
2020-09-22 17:37:37 +00:00
from django.utils.http import urlsafe_base64_decode
from django.utils.translation import gettext_lazy as _
2020-09-27 10:49:10 +00:00
from django.views.generic import CreateView, DetailView, RedirectView, TemplateView, UpdateView, View
from magic import Magic
from participation.models import Phase
2020-09-24 09:44:43 +00:00
2020-09-24 20:40:10 +00:00
from .forms import CoachRegistrationForm, PhotoAuthorizationForm, SignupForm, StudentRegistrationForm, UserForm
from .models import StudentRegistration
2020-09-22 10:27:03 +00:00
class SignupView(CreateView):
2020-10-30 18:46:46 +00:00
"""
Signup, as a participant or a coach.
"""
2020-09-22 10:27:03 +00:00
model = User
form_class = SignupForm
template_name = "registration/signup.html"
2020-11-02 09:58:00 +00:00
extra_context = dict(title=_("Sign up"))
2020-09-22 10:27:03 +00:00
def dispatch(self, request, *args, **kwargs):
"""
The signup view is available only during the first phase.
"""
current_phase = Phase.current_phase()
if not current_phase or current_phase.phase_number >= 2:
raise PermissionDenied(_("You can't register now."))
return super().dispatch(request, *args, **kwargs)
2020-09-22 10:27:03 +00:00
def get_context_data(self, **kwargs):
context = super().get_context_data()
context["student_registration_form"] = StudentRegistrationForm(self.request.POST or None)
context["coach_registration_form"] = CoachRegistrationForm(self.request.POST or None)
del context["student_registration_form"].fields["team"]
del context["student_registration_form"].fields["email_confirmed"]
del context["coach_registration_form"].fields["team"]
del context["coach_registration_form"].fields["email_confirmed"]
2020-09-22 10:27:03 +00:00
return context
@transaction.atomic
def form_valid(self, form):
role = form.cleaned_data["role"]
if role == "participant":
registration_form = StudentRegistrationForm(self.request.POST)
else:
registration_form = CoachRegistrationForm(self.request.POST)
del registration_form.fields["team"]
del registration_form.fields["email_confirmed"]
2020-09-22 10:27:03 +00:00
if not registration_form.is_valid():
return self.form_invalid(form)
ret = super().form_valid(form)
registration = registration_form.instance
registration.user = form.instance
registration.save()
return ret
def get_success_url(self):
2020-09-24 12:15:42 +00:00
return reverse_lazy("registration:email_validation_sent")
2020-09-22 17:37:37 +00:00
class UserValidateView(TemplateView):
"""
A view to validate the email address.
"""
title = _("Email validation")
template_name = 'registration/email_validation_complete.html'
2020-11-02 09:58:00 +00:00
extra_context = dict(title=_("Validate email"))
2020-09-22 17:37:37 +00:00
def get(self, *args, **kwargs):
"""
With a given token and user id (in params), validate the email address.
"""
assert 'uidb64' in kwargs and 'token' in kwargs
self.validlink = False
user = self.get_user(kwargs['uidb64'])
token = kwargs['token']
# Validate the token
if user is not None and email_validation_token.check_token(user, token):
self.validlink = True
user.registration.email_confirmed = True
2020-09-24 12:15:42 +00:00
user.registration.save()
2020-09-22 17:37:37 +00:00
return self.render_to_response(self.get_context_data(), status=200 if self.validlink else 400)
def get_user(self, uidb64):
"""
Get user from the base64-encoded string.
"""
try:
# urlsafe_base64_decode() decodes to bytestring
uid = urlsafe_base64_decode(uidb64).decode()
user = User.objects.get(pk=uid)
except (TypeError, ValueError, OverflowError, User.DoesNotExist, ValidationError):
user = None
return user
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['user_object'] = self.get_user(self.kwargs["uidb64"])
context['login_url'] = resolve_url(settings.LOGIN_URL)
if self.validlink:
context['validlink'] = True
else:
context.update({
'title': _('Email validation unsuccessful'),
'validlink': False,
})
return context
class UserValidationEmailSentView(TemplateView):
"""
Display the information that the validation link has been sent.
"""
template_name = 'registration/email_validation_email_sent.html'
2020-11-02 09:58:00 +00:00
extra_context = dict(title=_('Email validation email sent'))
2020-09-22 17:37:37 +00:00
class UserResendValidationEmailView(LoginRequiredMixin, DetailView):
"""
Rensend the email validation link.
"""
model = User
2020-11-02 09:58:00 +00:00
extra_context = dict(title=_("Resend email validation link"))
2020-09-22 17:37:37 +00:00
def get(self, request, *args, **kwargs):
user = self.get_object()
2020-09-24 12:15:42 +00:00
user.registration.send_email_validation_link()
return redirect('registration:email_validation_sent')
2020-09-24 16:39:55 +00:00
class MyAccountDetailView(LoginRequiredMixin, RedirectView):
2020-10-30 18:46:46 +00:00
"""
Redirect to our own profile detail page.
"""
2020-09-24 16:39:55 +00:00
def get_redirect_url(self, *args, **kwargs):
return reverse_lazy("registration:user_detail", args=(self.request.user.pk,))
class UserDetailView(LoginRequiredMixin, DetailView):
2020-10-30 18:46:46 +00:00
"""
Display the detail about a user.
"""
2020-09-24 16:39:55 +00:00
model = User
context_object_name = "user_object"
2020-09-24 16:39:55 +00:00
template_name = "registration/user_detail.html"
2020-09-27 14:35:31 +00:00
def dispatch(self, request, *args, **kwargs):
user = request.user
if not user.is_authenticated:
return self.handle_no_permission()
2020-10-30 18:46:46 +00:00
# Only an admin or the concerned user can see the information
2020-09-27 14:35:31 +00:00
if not user.registration.is_admin and user.pk != kwargs["pk"]:
raise PermissionDenied
return super().dispatch(request, *args, **kwargs)
2020-11-02 09:58:00 +00:00
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["title"] = _("Detail of user {user}").format(user=str(self.object.registration))
return context
2020-09-24 16:39:55 +00:00
class UserUpdateView(LoginRequiredMixin, UpdateView):
2020-10-30 18:46:46 +00:00
"""
Update the detail about a user and its registration.
"""
2020-09-24 16:39:55 +00:00
model = User
form_class = UserForm
template_name = "registration/update_user.html"
2020-09-27 14:35:31 +00:00
def dispatch(self, request, *args, **kwargs):
user = request.user
if not user.registration.is_admin and user.pk != kwargs["pk"]:
raise PermissionDenied
return super().dispatch(request, *args, **kwargs)
2020-09-24 16:39:55 +00:00
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
user = self.get_object()
2020-11-02 09:58:00 +00:00
context["title"] = _("Update user {user}").format(user=str(self.object.registration))
2020-09-24 16:39:55 +00:00
context["registration_form"] = user.registration.form_class(data=self.request.POST or None,
instance=self.object.registration)
if not user.registration.is_admin:
if "team" in context["registration_form"].fields:
del context["registration_form"].fields["team"]
del context["registration_form"].fields["email_confirmed"]
2020-09-24 16:39:55 +00:00
return context
@transaction.atomic
def form_valid(self, form):
user = form.instance
registration_form = user.registration.form_class(data=self.request.POST or None,
instance=self.object.registration)
if not user.registration.is_admin:
if "team" in registration_form.fields:
del registration_form.fields["team"]
del registration_form.fields["email_confirmed"]
2020-09-24 16:39:55 +00:00
if not registration_form.is_valid():
return self.form_invalid(form)
registration_form.save()
return super().form_valid(form)
def get_success_url(self):
return reverse_lazy("registration:user_detail", args=(self.object.pk,))
2020-09-24 20:40:10 +00:00
class UserUploadPhotoAuthorizationView(LoginRequiredMixin, UpdateView):
2020-10-30 18:46:46 +00:00
"""
A participant can send its photo authorization.
"""
2020-09-24 20:40:10 +00:00
model = StudentRegistration
form_class = PhotoAuthorizationForm
template_name = "registration/upload_photo_authorization.html"
2020-11-02 09:58:00 +00:00
extra_context = dict(title=_("Upload photo authorization"))
2020-09-24 20:40:10 +00:00
2020-09-27 14:35:31 +00:00
def dispatch(self, request, *args, **kwargs):
user = request.user
if not user.registration.is_admin and user.registration.pk != kwargs["pk"]:
raise PermissionDenied
return super().dispatch(request, *args, **kwargs)
2020-09-27 10:36:37 +00:00
@transaction.atomic
def form_valid(self, form):
old_instance = StudentRegistration.objects.get(pk=self.object.pk)
if old_instance.photo_authorization:
old_instance.photo_authorization.delete()
return super().form_valid(form)
2020-09-24 20:40:10 +00:00
def get_success_url(self):
return reverse_lazy("registration:user_detail", args=(self.object.user.pk,))
2020-09-27 10:36:37 +00:00
class PhotoAuthorizationView(LoginRequiredMixin, View):
2020-10-30 18:46:46 +00:00
"""
Display the sent photo authorization.
"""
2020-09-27 10:36:37 +00:00
def get(self, request, *args, **kwargs):
filename = kwargs["filename"]
path = f"media/authorization/photo/{filename}"
if not os.path.exists(path):
raise Http404
student = StudentRegistration.objects.get(photo_authorization__endswith=filename)
2020-09-27 14:35:31 +00:00
user = request.user
if not user.registration.is_admin and user.pk != student.user.pk:
raise PermissionDenied
2020-10-30 18:46:46 +00:00
# Guess mime type of the file
2020-09-27 10:36:37 +00:00
mime = Magic(mime=True)
mime_type = mime.from_file(path)
ext = mime_type.split("/")[1].replace("jpeg", "jpg")
2020-10-30 18:46:46 +00:00
# Replace file name
2020-09-27 10:36:37 +00:00
true_file_name = _("Photo authorization of {student}.{ext}").format(student=str(student), ext=ext)
return FileResponse(open(path, "rb"), content_type=mime_type, filename=true_file_name)
2020-10-19 14:08:42 +00:00
class UserImpersonateView(LoginRequiredMixin, RedirectView):
2020-10-30 18:46:46 +00:00
"""
An administrator can log in through this page as someone else, and act as this other person.
"""
2020-10-19 14:08:42 +00:00
def dispatch(self, request, *args, **kwargs):
if self.request.user.registration.is_admin:
if not User.objects.filter(pk=kwargs["pk"]).exists():
raise Http404
session = request.session
session["admin"] = request.user.pk
session["_fake_user_id"] = kwargs["pk"]
return super().dispatch(request, *args, **kwargs)
def get_redirect_url(self, *args, **kwargs):
return reverse_lazy("registration:user_detail", args=(kwargs["pk"],))
class ResetAdminView(LoginRequiredMixin, View):
"""
Return to admin view, clear the session field that let an administrator to log in as someone else.
"""
def dispatch(self, request, *args, **kwargs):
user = request.user
if not user.is_authenticated:
return self.handle_no_permission()
if "_fake_user_id" in request.session:
del request.session["_fake_user_id"]
2020-11-02 11:08:01 +00:00
return redirect(request.GET.get("path", reverse_lazy("index")))