1
0
mirror of https://gitlab.crans.org/mediatek/med.git synced 2024-12-24 17:42:23 +00:00

Swap AbstractBaseUser to AbstractUser

This commit is contained in:
Alexandre Iooss 2019-08-08 12:16:40 +02:00
parent 0b42060c51
commit 781b2087a3
No known key found for this signature in database
GPG Key ID: 6C79278F3FCDCC02
18 changed files with 242 additions and 243 deletions

View File

@ -35,7 +35,7 @@ SPDX-License-Identifier: GPL-3.0-or-later
<div id="content-related">
<div class="module" id="recent-actions-module">
{% if request_user.is_authenticated %}
<h2>{{ request_user.name }} {{ request_user.last_name }}</h2>
<h2>{{ request_user.first_name }} {{ request_user.last_name }}</h2>
<h3>{% trans 'My profile' %}</h3>
<ul>

View File

@ -40,15 +40,15 @@ def search_result(search, type, request):
recherche = {'users_list': None, 'emprunts_list': None, 'medias_list': None, 'jeux_list': None}
if request.user.has_perms(('perm',)):
query = Q(user__username__icontains=search) | Q(user__name__icontains=search) | Q(
query = Q(user__username__icontains=search) | Q(user__first_name__icontains=search) | Q(
user__last_name__icontains=search)
else:
query = (Q(user__username__icontains=search) | Q(user__name__icontains=search) | Q(
query = (Q(user__username__icontains=search) | Q(user__first_name__icontains=search) | Q(
user__last_name__icontains=search)) & Q(user=request.user)
for i in aff:
if i == '0':
query_user_list = Q(username__icontains=search) | Q(name__icontains=search) | Q(
query_user_list = Q(username__icontains=search) | Q(first_name__icontains=search) | Q(
last_name__icontains=search) & query1
if request.user.has_perms(('perm',)):
recherche['users_list'] = User.objects.filter(query_user_list).order_by('last_name')
@ -63,7 +63,7 @@ def search_result(search, type, request):
if i == '3':
recherche['jeux_list'] = Jeu.objects.filter(
Q(nom__icontains=search) | Q(proprietaire__username__icontains=search) | Q(
proprietaire__name__icontains=search) | Q(proprietaire__last_name__icontains=search))
proprietaire__first_name__icontains=search) | Q(proprietaire__last_name__icontains=search))
for r in recherche:
if recherche[r] is not None:

View File

@ -111,7 +111,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
<div class="panel panel-default">
{% if request_user.is_authenticated %}
<div class="panel-heading">
<h4>{{ request_user.name }} {{ request_user.last_name }}</h4>
<h4>{{ request_user.first_name }} {{ request_user.last_name }}</h4>
</div>
<table class="table">
<tr>
@ -124,7 +124,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
</tr>
<tr>
<th scope="row">Prénom</th>
<td class="text-right">{{ request_user.name }}</td>
<td class="text-right">{{ request_user.first_name }}</td>
</tr>
</table>
{% else %}

View File

@ -1,7 +1,7 @@
# -*- mode: python; coding: utf-8 -*-
# SPDX-License-Identifier: GPL-3.0-or-later
from django.contrib.auth.models import User
from users.models import User
from django.test import TestCase
"""

View File

@ -4,10 +4,9 @@
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import Group
from django.utils.translation import ugettext_lazy as _
from reversion.admin import VersionAdmin
from .forms import UserChangeForm, UserCreationForm
from .models import User, Right, Adhesion, ListRight, Clef, Request
@ -32,31 +31,16 @@ class ListRightAdmin(VersionAdmin):
class UserAdmin(VersionAdmin, BaseUserAdmin):
# The forms to add and change user instances
form = UserChangeForm
add_form = UserCreationForm
# The fields to be used in displaying the User model.
# These override the definitions on the base UserAdmin
# that reference specific fields on auth.User.
list_display = ('username', 'name', 'last_name', 'email', 'is_admin')
list_filter = ()
# Customize admin to add more fields
fieldsets = (
(None, {'fields': ('username', 'password')}),
('Personal info', {'fields': ('name', 'last_name', 'email')}),
('Permissions', {'fields': ('is_admin',)}),
(_('Personal info'), {'fields': ('first_name', 'last_name', 'email',
'telephone', 'address', 'comment')}),
(_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
'groups', 'user_permissions',
'maxemprunt')}),
(_('Important dates'), {'fields': ('last_login', 'date_joined')}),
)
# add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
# overrides get_fieldsets to use this attribute when creating a user.
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'name', 'last_name', 'email', 'is_admin', 'password1', 'password2')}
),
)
search_fields = ('username',)
ordering = ('username',)
filter_horizontal = ()
admin.site.register(User, UserAdmin)
@ -65,9 +49,3 @@ admin.site.register(ListRight, ListRightAdmin)
admin.site.register(Right, RightAdmin)
admin.site.register(Adhesion, AdhesionAdmin)
admin.site.register(Clef, ClefAdmin)
# Now register the new UserAdmin...
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
# ... and, since we're not using Django's built-in permissions,
# unregister the Group model from admin.
admin.site.unregister(Group)

View File

@ -17,96 +17,28 @@ class PassForm(forms.Form):
validators=[MinLengthValidator(8)], widget=forms.PasswordInput)
class UserCreationForm(forms.ModelForm):
"""A form for creating new users. Includes all the required
fields, plus a repeated password."""
password1 = forms.CharField(label='Password', widget=forms.PasswordInput, validators=[MinLengthValidator(8)],
max_length=255)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput,
validators=[MinLengthValidator(8)], max_length=255)
is_admin = forms.BooleanField(label='is admin')
class Meta:
model = User
fields = ('username', 'name', 'last_name', 'email')
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
# Save the provided password in hashed format
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
user.save()
user.is_admin = self.cleaned_data.get("is_admin")
return user
class UserChangeForm(forms.ModelForm):
"""A form for updating users. Includes all the fields on
the user, but replaces the password field with admin's
password hash display field.
"""
password = ReadOnlyPasswordHashField()
is_admin = forms.BooleanField(label='is admin', required=False)
class Meta:
model = User
fields = ('username', 'password', 'name', 'last_name', 'email')
def __init__(self, *args, **kwargs):
super(UserChangeForm, self).__init__(*args, **kwargs)
print("User is admin : %s" % kwargs['instance'].is_admin)
self.initial['is_admin'] = kwargs['instance'].is_admin
def clean_password(self):
# Regardless of what the user provides, return the initial value.
# This is done here, rather than on the field, because the
# field does not have access to the initial value
return self.initial["password"]
def save(self, commit=True):
# Save the provided password in hashed format
user = super(UserChangeForm, self).save(commit=False)
user.is_admin = self.cleaned_data.get("is_admin")
if commit:
user.save()
return user
class BaseInfoForm(ModelForm):
def __init__(self, *args, **kwargs):
super(BaseInfoForm, self).__init__(*args, **kwargs)
self.fields['name'].label = 'Prénom'
self.fields['last_name'].label = 'Nom'
# self.fields['comment'].label = 'Commentaire'
class Meta:
model = User
fields = [
'name',
'first_name',
'username',
'last_name',
'email',
'telephone',
'adresse',
'address',
]
class InfoForm(BaseInfoForm):
class Meta(BaseInfoForm.Meta):
fields = [
'name',
'first_name',
'username',
'last_name',
'email',
'telephone',
'adresse',
'address',
'maxemprunt',
]

View File

@ -3,7 +3,7 @@ msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2019-08-02 14:42+0200\n"
"POT-Creation-Date: 2019-08-08 12:10+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
@ -13,10 +13,46 @@ msgstr ""
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"
#: models.py:195
#: admin.py:37
msgid "Personal info"
msgstr ""
#: admin.py:39
msgid "Permissions"
msgstr ""
#: admin.py:42
msgid "Important dates"
msgstr ""
#: models.py:18
msgid "phone number"
msgstr "numéro de téléphone"
#: models.py:24
msgid "address"
msgstr "adresse"
#: models.py:30
msgid "maximum borrowed"
msgstr "emprunts maximal"
#: models.py:31
msgid "Maximal amount of simultaneous borrowed item authorized."
msgstr "Nombre maximal d'objets empruntés en même temps."
#: models.py:35
msgid "comment"
msgstr "commentaire"
#: models.py:36
msgid "Promotion..."
msgstr ""
#: models.py:96
msgid "right"
msgstr ""
#: models.py:196
#: models.py:97
msgid "rights"
msgstr ""

View File

@ -2,12 +2,11 @@
# Generated by Django 1.10.7 on 2019-08-02 19:12
from __future__ import unicode_literals
from django.contrib.auth.models import UserManager
from django.db import migrations
import users.models
class Migration(migrations.Migration):
dependencies = [
('users', '0011_auto_20190802_1831'),
]
@ -16,7 +15,7 @@ class Migration(migrations.Migration):
migrations.AlterModelManagers(
name='user',
managers=[
('objects', users.models.UserManager()),
('objects', UserManager()),
],
),
migrations.RemoveField(

View File

@ -0,0 +1,20 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.22 on 2019-08-08 09:32
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('users', '0019_auto_20190802_2146'),
]
operations = [
migrations.RenameField(
model_name='user',
old_name='name',
new_name='first_name',
),
]

View File

@ -0,0 +1,20 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.22 on 2019-08-08 09:34
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0020_auto_20190808_1132'),
]
operations = [
migrations.AlterField(
model_name='user',
name='first_name',
field=models.CharField(blank=True, max_length=30, verbose_name='first name'),
),
]

View File

@ -0,0 +1,35 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.22 on 2019-08-08 09:36
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('auth', '0008_alter_user_username_max_length'),
('users', '0021_auto_20190808_1134'),
]
operations = [
migrations.AlterModelOptions(
name='user',
options={'verbose_name': 'user', 'verbose_name_plural': 'users'},
),
migrations.AddField(
model_name='user',
name='groups',
field=models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups'),
),
migrations.AddField(
model_name='user',
name='is_superuser',
field=models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status'),
),
migrations.AddField(
model_name='user',
name='user_permissions',
field=models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions'),
),
]

View File

@ -0,0 +1,20 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.22 on 2019-08-08 10:06
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('users', '0022_auto_20190808_1136'),
]
operations = [
migrations.RenameField(
model_name='user',
old_name='adresse',
new_name='address',
),
]

View File

@ -0,0 +1,35 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.22 on 2019-08-08 10:08
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0023_auto_20190808_1206'),
]
operations = [
migrations.AlterField(
model_name='user',
name='address',
field=models.CharField(blank=True, max_length=255, null=True, verbose_name='address'),
),
migrations.AlterField(
model_name='user',
name='comment',
field=models.CharField(blank=True, help_text='Promotion...', max_length=255, verbose_name='comment'),
),
migrations.AlterField(
model_name='user',
name='maxemprunt',
field=models.IntegerField(default=5, help_text='maximal amount of simultaneous borrowed item authorized', verbose_name='maximum borrowed'),
),
migrations.AlterField(
model_name='user',
name='telephone',
field=models.CharField(blank=True, max_length=15, null=True, verbose_name='phone number'),
),
]

View File

@ -0,0 +1,20 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.22 on 2019-08-08 10:13
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0024_auto_20190808_1208'),
]
operations = [
migrations.AlterField(
model_name='user',
name='maxemprunt',
field=models.IntegerField(default=5, help_text='Maximal amount of simultaneous borrowed item authorized.', verbose_name='maximum borrowed'),
),
]

View File

@ -5,109 +5,40 @@
import datetime
import uuid
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.contrib.auth.validators import ASCIIUsernameValidator, UnicodeUsernameValidator
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils import six, timezone
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from med.settings import MAX_EMPRUNT, REQ_EXPIRE_HRS
class UserManager(BaseUserManager):
use_in_migrations = True
def _create_user(self, username, name, last_name, email, password=None, su=False):
"""
Creates and saves a User with the given username, email and password.
"""
if not username:
raise ValueError('The given username must be set')
email = self.normalize_email(email)
username = self.model.normalize_username(username)
user = self.model(
username=username,
name=name,
last_name=last_name,
email=email,
)
user.set_password(password)
user.save(using=self._db)
if su:
user.make_admin()
return user
def create_user(self, username, name, last_name, email, password=None):
"""
Creates and saves a User with the given username, name, last_name, email,
and password.
"""
return self._create_user(username, name, last_name, email, password, False)
def create_superuser(self, username, name, last_name, email, password):
"""
Creates and saves a superuser with the given username, name, last_name,
email, and password.
"""
return self._create_user(username, name, last_name, email, password, True)
class User(AbstractBaseUser):
username_validator = UnicodeUsernameValidator() if six.PY3 else ASCIIUsernameValidator()
name = models.CharField(max_length=255)
last_name = models.CharField(_('last name'), max_length=30, blank=True)
email = models.EmailField(_('email address'), blank=True)
telephone = models.CharField(max_length=15, null=True, blank=True)
adresse = models.CharField(max_length=255, null=True, blank=True)
maxemprunt = models.IntegerField(default=MAX_EMPRUNT, help_text="Maximum d'emprunts autorisés")
username = models.CharField(
_('username'),
max_length=150,
unique=True,
help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'),
validators=[username_validator],
error_messages={
'unique': _("A user with that username already exists."),
},
class User(AbstractUser):
telephone = models.CharField(
verbose_name=_('phone number'),
max_length=15,
null=True,
blank=True,
)
comment = models.CharField(help_text="Commentaire, promo", max_length=255, blank=True)
is_staff = models.BooleanField(
_('staff status'),
default=False,
help_text=_('Designates whether the user can log into this admin site.'),
address = models.CharField(
verbose_name=_('address'),
max_length=255,
null=True,
blank=True,
)
is_active = models.BooleanField(
_('active'),
default=True,
help_text=_(
'Designates whether this user should be treated as active. '
'Unselect this instead of deleting accounts.'
),
maxemprunt = models.IntegerField(
verbose_name=_('maximum borrowed'),
help_text=_('Maximal amount of simultaneous borrowed item authorized.'),
default=MAX_EMPRUNT,
)
comment = models.CharField(
verbose_name=_('comment'),
help_text=_('Promotion...'),
max_length=255,
blank=True,
)
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
objects = UserManager()
EMAIL_FIELD = 'email'
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['name', 'last_name', 'email']
@property
def is_admin(self):
try:
Right.objects.get(user=self, right__listright='admin')
except Right.DoesNotExist:
return False
return True
@is_admin.setter
def is_admin(self, value):
if value and not self.is_admin:
self.make_admin()
elif not value and self.is_admin:
self.un_admin()
REQUIRED_FIELDS = ['first_name', 'last_name', 'email']
def has_perms(self, perms, obj=None):
for perm in perms:
@ -117,12 +48,6 @@ class User(AbstractBaseUser):
except Right.DoesNotExist:
return False
def get_full_name(self):
return '%s %s' % (self.name, self.last_name)
def get_short_name(self):
return self.name
def has_perm(self, perm, obj=None):
return True
@ -138,27 +63,6 @@ class User(AbstractBaseUser):
last_adh_year = Adhesion.objects.all().order_by('annee_debut').reverse().first()
return last_adh_year and self in last_adh_year.adherent.all()
def get_admin_right(self):
admin, created = ListRight.objects.get_or_create(listright="admin")
return admin
def make_admin(self):
""" Make User admin """
user_admin_right = Right(user=self, right=self.get_admin_right())
user_admin_right.save()
self.is_staff = True
self.save()
def un_admin(self):
try:
user_right = Right.objects.get(user=self, right=self.get_admin_right())
except Right.DoesNotExist:
return
user_right.delete()
def __str__(self):
return self.username
class Request(models.Model):
PASSWD = 'PW'
@ -179,7 +83,7 @@ class Request(models.Model):
+ datetime.timedelta(hours=REQ_EXPIRE_HRS)
if not self.token:
self.token = str(uuid.uuid4()).replace('-', '') # remove hyphens
super(Request, self).save()
super().save()
class Right(models.Model):

View File

@ -40,7 +40,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
</thead>
{% for user in users_list %}
<tr>
<td>{{ user.name }}</td>
<td>{{ user.first_name }}</td>
<td>{{ user.last_name }}</td>
<td>{{ user.username }}</td>
<td>{{ user.email }}</td>

View File

@ -59,7 +59,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
<table class="table table-striped">
<tr>
<th>Prénom</th>
<td>{{ user.name }}</td>
<td>{{ user.first_name }}</td>
<th>Nom</th>
<td>{{ user.last_name }}</td>
</tr>
@ -77,7 +77,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
</tr>
<tr>
<th>Adresse</th>
<td>{{ user.adresse }}</td>
<td>{{ user.address }}</td>
<th>Telephone</th>
<td>{{ user.telephone }}</td>
</tr>

View File

@ -52,7 +52,7 @@ def reset_passwd_mail(req, request):
""" Prend en argument un request, envoie un mail de réinitialisation de mot de pass """
t = loader.get_template('users/email_passwd_request')
c = {
'name': str(req.user.name) + ' ' + str(req.user.last_name),
'name': str(req.user.first_name) + ' ' + str(req.user.last_name),
'asso': ASSO_NAME,
'asso_mail': ASSO_EMAIL,
'site_name': SITE_NAME,
@ -377,7 +377,7 @@ def index_adhesion(request):
@permission_required('perm')
def index(request):
""" Affiche l'ensemble des users, need droit admin """
users_list = User.objects.order_by('name')
users_list = User.objects.order_by('first_name')
paginator = Paginator(users_list, PAGINATION_NUMBER)
page = request.GET.get('page')
try:
@ -395,7 +395,7 @@ def index(request):
@permission_required('perm')
def index_ajour(request):
""" Affiche l'ensemble des users, need droit admin """
users_list = Adhesion.objects.all().order_by('annee_debut').reverse().first().adherent.all().order_by('name')
users_list = Adhesion.objects.all().order_by('annee_debut').reverse().first().adherent.all().order_by('first_name')
paginator = Paginator(users_list, PAGINATION_NUMBER)
page = request.GET.get('page')
try: