1
0
mirror of https://gitlab.crans.org/bde/nk20 synced 2024-11-26 10:27:07 +00:00
nk20/apps/member/views.py

389 lines
14 KiB
Python
Raw Normal View History

2020-02-18 20:30:26 +00:00
# Copyright (C) 2018-2020 by BDE ENS Paris-Saclay
2019-08-10 17:01:15 +00:00
# SPDX-License-Identifier: GPL-3.0-or-later
2020-02-18 20:30:26 +00:00
2020-03-07 21:28:59 +00:00
import io
from PIL import Image
from dal import autocomplete
from django.conf import settings
from django.contrib import messages
2019-08-10 17:01:15 +00:00
from django.contrib.auth.mixins import LoginRequiredMixin
2020-03-07 21:28:59 +00:00
from django.contrib.auth.models import User
2020-03-19 15:12:52 +00:00
from django.contrib.auth.views import LoginView
2020-03-07 21:28:59 +00:00
from django.core.exceptions import ValidationError
from django.db.models import Q
from django.http import HttpResponseRedirect
2020-02-17 22:30:55 +00:00
from django.shortcuts import redirect
2020-03-07 21:28:59 +00:00
from django.urls import reverse_lazy
2019-08-10 17:01:15 +00:00
from django.utils.translation import gettext_lazy as _
2020-03-07 21:28:59 +00:00
from django.views.generic import CreateView, DetailView, UpdateView, TemplateView, DeleteView
2020-02-28 12:37:31 +00:00
from django.views.generic.edit import FormMixin
from django_tables2.views import SingleTableView
2020-02-17 18:25:33 +00:00
from rest_framework.authtoken.models import Token
from note.forms import ImageForm
#from note.forms import AliasForm, ImageForm
2020-02-18 20:14:29 +00:00
from note.models import Alias, NoteUser
from note.models.transactions import Transaction
2020-02-28 12:37:31 +00:00
from note.tables import HistoryTable, AliasTable
2020-03-20 13:43:35 +00:00
from permission.backends import PermissionBackend
2020-03-20 17:13:34 +00:00
2020-03-07 21:28:59 +00:00
from .filters import UserFilter, UserFilterFormHelper
2020-03-19 15:12:52 +00:00
from .forms import SignUpForm, ProfileForm, ClubForm, MembershipForm, MemberFormSet, FormSetHelper, \
CustomAuthenticationForm
2020-03-07 21:28:59 +00:00
from .models import Club, Membership
2020-02-18 11:31:15 +00:00
from .tables import ClubTable, UserTable
2019-09-23 10:50:14 +00:00
2020-02-18 11:31:15 +00:00
2020-03-19 15:12:52 +00:00
class CustomLoginView(LoginView):
form_class = CustomAuthenticationForm
def form_valid(self, form):
self.request.session['permission_mask'] = form.cleaned_data['permission_mask'].rank
return super().form_valid(form)
2019-08-11 22:30:29 +00:00
class UserCreateView(CreateView):
2019-08-11 14:22:52 +00:00
"""
Une vue pour inscrire un utilisateur et lui créer un profile
"""
form_class = SignUpForm
2019-08-11 14:22:52 +00:00
success_url = reverse_lazy('login')
2020-02-18 11:31:15 +00:00
template_name = 'member/signup.html'
second_form = ProfileForm
2019-08-11 14:22:52 +00:00
2020-02-18 11:31:15 +00:00
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
2020-02-03 18:24:23 +00:00
context["profile_form"] = self.second_form()
2019-08-11 14:22:52 +00:00
return context
2019-08-11 15:39:05 +00:00
def form_valid(self, form):
profile_form = ProfileForm(self.request.POST)
if form.is_valid() and profile_form.is_valid():
2020-03-09 17:08:37 +00:00
user = form.save(commit=False)
user.profile = profile_form.save(commit=False)
user.save()
user.profile.save()
2019-08-11 15:39:05 +00:00
return super().form_valid(form)
2019-08-11 21:25:27 +00:00
2020-02-18 11:31:15 +00:00
class UserUpdateView(LoginRequiredMixin, UpdateView):
2020-02-03 18:25:05 +00:00
model = User
2020-02-18 11:31:15 +00:00
fields = ['first_name', 'last_name', 'username', 'email']
2020-02-03 18:25:05 +00:00
template_name = 'member/profile_update.html'
2020-02-27 19:56:06 +00:00
context_object_name = 'user_object'
2020-03-03 13:25:16 +00:00
profile_form = ProfileForm
2020-02-18 11:31:15 +00:00
def get_context_data(self, **kwargs):
2020-02-03 18:25:05 +00:00
context = super().get_context_data(**kwargs)
2020-03-03 13:25:16 +00:00
context['profile_form'] = self.profile_form(instance=context['user_object'].profile)
2020-02-21 10:17:14 +00:00
context['title'] = _("Update Profile")
2020-02-03 18:25:05 +00:00
return context
def get_form(self, form_class=None):
2020-02-17 10:36:46 +00:00
form = super().get_form(form_class)
if 'username' not in form.data:
return form
new_username = form.data['username']
2020-02-17 10:36:46 +00:00
# Si l'utilisateur cherche à modifier son pseudo, le nouveau pseudo ne doit pas être proche d'un alias existant
2020-02-18 11:31:15 +00:00
note = NoteUser.objects.filter(
alias__normalized_name=Alias.normalize(new_username))
2020-02-27 19:56:06 +00:00
if note.exists() and note.get().user != self.object:
2020-02-18 11:31:15 +00:00
form.add_error('username',
_("An alias with a similar name already exists."))
return form
2020-02-03 18:25:05 +00:00
def form_valid(self, form):
2020-02-18 11:31:15 +00:00
profile_form = ProfileForm(
data=self.request.POST,
2020-02-27 19:56:06 +00:00
instance=self.object.profile,
2020-02-18 11:31:15 +00:00
)
2020-02-03 18:25:05 +00:00
if form.is_valid() and profile_form.is_valid():
new_username = form.data['username']
alias = Alias.objects.filter(name=new_username)
2020-02-17 10:36:46 +00:00
# Si le nouveau pseudo n'est pas un de nos alias, on supprime éventuellement un alias similaire pour le remplacer
if not alias.exists():
2020-02-18 11:31:15 +00:00
similar = Alias.objects.filter(
normalized_name=Alias.normalize(new_username))
if similar.exists():
similar.delete()
2020-02-17 10:36:46 +00:00
user = form.save(commit=False)
2020-02-18 11:31:15 +00:00
profile = profile_form.save(commit=False)
2020-02-03 18:25:05 +00:00
profile.user = user
profile.save()
2020-02-17 10:36:46 +00:00
user.save()
2020-02-03 18:25:05 +00:00
return super().form_valid(form)
def get_success_url(self, **kwargs):
2020-02-18 11:31:15 +00:00
if kwargs:
return reverse_lazy('member:user_detail',
kwargs={'pk': kwargs['id']})
2020-02-03 18:25:05 +00:00
else:
2020-03-07 21:28:59 +00:00
return reverse_lazy('member:user_detail', args=(self.object.id,))
2020-02-18 11:31:15 +00:00
2020-02-03 18:25:05 +00:00
2020-02-18 11:31:15 +00:00
class UserDetailView(LoginRequiredMixin, DetailView):
"""
2020-02-21 10:53:37 +00:00
Affiche les informations sur un utilisateur, sa note, ses clubs...
"""
2020-02-25 21:55:27 +00:00
model = User
context_object_name = "user_object"
template_name = "member/profile_detail.html"
2020-02-18 11:31:15 +00:00
def get_queryset(self, **kwargs):
return super().get_queryset().filter(PermissionBackend.filter_queryset(self.request.user, User, "view"))
2020-02-18 11:31:15 +00:00
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
2020-02-25 21:55:27 +00:00
user = context['user_object']
history_list = \
Transaction.objects.all().filter(Q(source=user.note) | Q(destination=user.note)).order_by("-id")
context['history_list'] = HistoryTable(history_list)
club_list = \
Membership.objects.all().filter(user=user).only("club")
context['club_list'] = ClubTable(club_list)
return context
2019-08-11 22:30:29 +00:00
2020-02-18 11:31:15 +00:00
class UserListView(LoginRequiredMixin, SingleTableView):
"""
Affiche la liste des utilisateurs, avec une fonction de recherche statique
"""
2019-09-23 10:50:14 +00:00
model = User
table_class = UserTable
template_name = 'member/user_list.html'
filter_class = UserFilter
formhelper_class = UserFilterFormHelper
2020-02-18 11:31:15 +00:00
def get_queryset(self, **kwargs):
qs = super().get_queryset().filter(PermissionBackend.filter_queryset(self.request.user, User, "view"))
2020-02-18 11:31:15 +00:00
self.filter = self.filter_class(self.request.GET, queryset=qs)
2019-09-23 10:50:14 +00:00
self.filter.form.helper = self.formhelper_class()
return self.filter.qs
2020-02-18 11:31:15 +00:00
def get_context_data(self, **kwargs):
2019-09-23 10:50:14 +00:00
context = super().get_context_data(**kwargs)
context["filter"] = self.filter
return context
2020-03-25 17:00:40 +00:00
class ProfileAliasView(LoginRequiredMixin, DetailView):
model = User
template_name = 'member/profile_alias.html'
context_object_name = 'user_object'
2020-03-07 21:28:59 +00:00
def get_context_data(self, **kwargs):
2020-02-28 12:37:31 +00:00
context = super().get_context_data(**kwargs)
2020-03-25 17:00:40 +00:00
note = context['object'].note
2020-02-28 15:12:35 +00:00
context["aliases"] = AliasTable(note.alias_set.all())
2020-02-28 12:37:31 +00:00
return context
2020-03-07 21:28:59 +00:00
class PictureUpdateView(LoginRequiredMixin, FormMixin, DetailView):
2020-03-04 15:34:12 +00:00
form_class = ImageForm
2020-03-07 21:28:59 +00:00
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context['form'] = self.form_class(self.request.POST, self.request.FILES)
2020-03-04 15:34:12 +00:00
return context
2020-03-07 21:28:59 +00:00
2020-03-04 15:34:12 +00:00
def get_success_url(self):
return reverse_lazy('member:user_detail', kwargs={'pk': self.object.id})
2020-03-07 21:28:59 +00:00
def post(self, request, *args, **kwargs):
form = self.get_form()
2020-03-04 15:34:12 +00:00
self.object = self.get_object()
if form.is_valid():
return self.form_valid(form)
else:
print('is_invalid')
print(form)
return self.form_invalid(form)
2020-03-07 21:28:59 +00:00
def form_valid(self, form):
image_field = form.cleaned_data['image']
2020-03-05 22:32:01 +00:00
x = form.cleaned_data['x']
y = form.cleaned_data['y']
w = form.cleaned_data['width']
h = form.cleaned_data['height']
# image crop and resize
image_file = io.BytesIO(image_field.read())
2020-03-07 21:28:59 +00:00
# ext = image_field.name.split('.')[-1].lower()
# TODO: support GIF format
image = Image.open(image_file)
2020-03-07 21:28:59 +00:00
image = image.crop((x, y, x + w, y + h))
image_clean = image.resize((settings.PIC_WIDTH,
2020-03-07 21:28:59 +00:00
settings.PIC_RATIO * settings.PIC_WIDTH),
Image.ANTIALIAS)
image_file = io.BytesIO()
2020-03-07 21:28:59 +00:00
image_clean.save(image_file, "PNG")
image_field.file = image_file
# renaming
2020-03-07 16:58:41 +00:00
filename = "{}_pic.png".format(self.object.note.pk)
image_field.name = filename
self.object.note.display_image = image_field
2020-03-04 15:34:12 +00:00
self.object.note.save()
return super().form_valid(form)
2020-03-25 15:58:15 +00:00
class ProfilePictureUpdateView(PictureUpdateView):
model = User
template_name = 'member/profile_picture_update.html'
context_object_name = 'user_object'
2020-03-07 21:28:59 +00:00
2020-03-25 15:58:15 +00:00
2020-02-17 20:32:08 +00:00
class ManageAuthTokens(LoginRequiredMixin, TemplateView):
2020-02-17 18:25:33 +00:00
"""
2020-02-17 20:32:08 +00:00
Affiche le jeton d'authentification, et permet de le regénérer
2020-02-17 18:25:33 +00:00
"""
2020-02-17 20:32:08 +00:00
model = Token
template_name = "member/manage_auth_tokens.html"
2020-02-17 18:25:33 +00:00
2020-02-17 22:30:55 +00:00
def get(self, request, *args, **kwargs):
2020-02-18 11:31:15 +00:00
if 'regenerate' in request.GET and Token.objects.filter(
user=request.user).exists():
2020-02-17 18:25:33 +00:00
Token.objects.get(user=self.request.user).delete()
2020-02-18 11:31:15 +00:00
return redirect(reverse_lazy('member:auth_token') + "?show",
permanent=True)
2020-02-17 18:25:33 +00:00
2020-02-17 22:30:55 +00:00
return super().get(request, *args, **kwargs)
2020-02-17 20:32:08 +00:00
2020-02-17 22:30:55 +00:00
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
2020-02-18 11:31:15 +00:00
context['token'] = Token.objects.get_or_create(
user=self.request.user)[0]
2020-02-17 18:25:33 +00:00
return context
2020-02-18 11:31:15 +00:00
2020-02-08 19:39:37 +00:00
class UserAutocomplete(autocomplete.Select2QuerySetView):
"""
2020-02-08 20:40:32 +00:00
Auto complete users by usernames
2020-02-08 19:39:37 +00:00
"""
2020-03-07 21:28:59 +00:00
2020-02-08 19:39:37 +00:00
def get_queryset(self):
2020-02-08 20:40:32 +00:00
"""
Quand une personne cherche un utilisateur par pseudo, une requête est envoyée sur l'API dédiée à l'auto-complétion.
Cette fonction récupère la requête, et renvoie la liste filtrée des utilisateurs par pseudos.
"""
# Un utilisateur non connecté n'a accès à aucune information
if not self.request.user.is_authenticated:
return User.objects.none()
qs = User.objects.filter(PermissionBackend.filter_queryset(self.request.user, User, "view")).all()
2020-02-08 19:39:37 +00:00
if self.q:
2020-03-10 16:16:03 +00:00
qs = qs.filter(username__regex="^" + self.q)
2020-02-08 19:39:37 +00:00
return qs
2020-02-18 11:31:15 +00:00
2020-02-18 20:14:29 +00:00
# ******************************* #
# CLUB #
# ******************************* #
2019-08-11 22:30:29 +00:00
2020-02-18 11:31:15 +00:00
class ClubCreateView(LoginRequiredMixin, CreateView):
2019-08-11 21:25:27 +00:00
"""
Create Club
"""
model = Club
form_class = ClubForm
success_url = reverse_lazy('member:club_list')
2020-03-25 15:58:15 +00:00
2020-02-18 11:31:15 +00:00
def form_valid(self, form):
2019-08-11 21:25:27 +00:00
return super().form_valid(form)
2020-02-18 11:31:15 +00:00
class ClubListView(LoginRequiredMixin, SingleTableView):
2019-08-11 21:25:27 +00:00
"""
List existing Clubs
2019-08-11 21:25:27 +00:00
"""
model = Club
2019-08-15 19:49:32 +00:00
table_class = ClubTable
2019-08-11 22:30:29 +00:00
def get_queryset(self, **kwargs):
return super().get_queryset().filter(PermissionBackend.filter_queryset(self.request.user, Club, "view"))
2020-02-18 11:31:15 +00:00
class ClubDetailView(LoginRequiredMixin, DetailView):
2019-08-11 21:25:27 +00:00
model = Club
2020-02-18 11:31:15 +00:00
context_object_name = "club"
def get_queryset(self, **kwargs):
return super().get_queryset().filter(PermissionBackend.filter_queryset(self.request.user, Club, "view"))
2020-02-18 11:31:15 +00:00
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
club = context["club"]
2020-03-07 21:28:59 +00:00
club_transactions = \
Transaction.objects.all().filter(Q(source=club.note) | Q(destination=club.note))
2019-08-15 21:11:52 +00:00
context['history_list'] = HistoryTable(club_transactions)
club_member = \
Membership.objects.all().filter(club=club)
2019-08-15 21:11:52 +00:00
# TODO: consider only valid Membership
context['member_list'] = club_member
return context
class ClubAliasView(LoginRequiredMixin, DetailView):
2020-03-25 17:00:40 +00:00
model = Club
template_name = 'member/club_alias.html'
context_object_name = 'club'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
note = context['object'].note
context["aliases"] = AliasTable(note.alias_set.all())
return context
2020-03-25 17:00:40 +00:00
2020-03-25 15:58:15 +00:00
class ClubUpdateView(LoginRequiredMixin, UpdateView):
model = Club
context_object_name = "club"
form_class = ClubForm
template_name = "member/club_form.html"
success_url = reverse_lazy("member:club_detail")
class ClubPictureUpdateView(PictureUpdateView):
model = Club
template_name = 'member/club_picture_update.html'
context_object_name = 'club'
def get_success_url(self):
return reverse_lazy('member:club_detail', kwargs={'pk': self.object.id})
2020-02-18 11:31:15 +00:00
class ClubAddMemberView(LoginRequiredMixin, CreateView):
model = Membership
form_class = MembershipForm
template_name = 'member/add_members.html'
2020-02-18 11:31:15 +00:00
def get_queryset(self, **kwargs):
return super().get_queryset().filter(PermissionBackend.filter_queryset(self.request.user, Membership, "view")
| PermissionBackend.filter_queryset(self.request.user, Membership,
"change"))
2020-02-18 11:31:15 +00:00
def get_context_data(self, **kwargs):
2020-03-25 16:42:54 +00:00
club = Club.objects.get(pk=self.kwargs["pk"])
context = super().get_context_data(**kwargs)
context['formset'] = MemberFormSet()
context['helper'] = FormSetHelper()
2020-03-25 16:42:54 +00:00
context['club'] = club
2020-02-21 17:28:21 +00:00
context['no_cache'] = True
return context
2020-02-18 11:31:15 +00:00
def post(self, request, *args, **kwargs):
2020-02-18 20:47:03 +00:00
return
# TODO: Implement POST
# formset = MembershipFormset(request.POST)
# if formset.is_valid():
# return self.form_valid(formset)
# else:
# return self.form_invalid(formset)
2020-02-18 11:31:15 +00:00
def form_valid(self, formset):
formset.save()
return super().form_valid(formset)