8
0
Fork 0
mirror of https://gitlab2.federez.net/re2o/re2o synced 2024-11-22 11:23:10 +00:00

[users] PEP8 on main files

This commit is contained in:
Alexandre Iooss 2018-10-28 15:32:31 +01:00
parent a9ec23c260
commit 05dc3fd800
8 changed files with 193 additions and 187 deletions

View file

@ -27,6 +27,7 @@ Here are defined some functions to check acl on the application.
"""
from django.utils.translation import ugettext as _
def can_view(user):
"""Check if an user can view the application.
@ -40,4 +41,3 @@ def can_view(user):
can = user.has_module_perms('users')
return can, None if can else _("You don't have the right to view this"
" application.")

View file

@ -28,10 +28,16 @@ où on fait appel à UserChange et ServiceUserChange, forms custom
from __future__ import unicode_literals
from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import Group
from reversion.admin import VersionAdmin
from .forms import (
UserChangeForm,
UserCreationForm,
ServiceUserChangeForm,
ServiceUserCreationForm
)
from .models import (
User,
EMailAddress,
@ -49,12 +55,6 @@ from .models import (
LdapServiceUserGroup,
LdapUserGroup
)
from .forms import (
UserChangeForm,
UserCreationForm,
ServiceUserChangeForm,
ServiceUserCreationForm
)
class LdapUserAdmin(admin.ModelAdmin):

View file

@ -34,25 +34,21 @@ Modification, creation de :
from __future__ import unicode_literals
from django import forms
from django.forms import ModelForm, Form
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from django.core.validators import MinLengthValidator
from django.utils import timezone
from django.contrib.auth.models import Group, Permission
from django.utils.translation import ugettext_lazy as _
from django.core.validators import MinLengthValidator
from django.forms import ModelForm, Form
from django.utils import timezone
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from machines.models import Interface, Machine, Nas
from topologie.models import Port
from preferences.models import OptionalUser
from re2o.utils import remove_user_room, get_input_formats_help_text
from re2o.mixins import FormRevMixin
from re2o.field_permissions import FieldPermissionFormMixin
from machines.models import Interface, Nas
from preferences.models import GeneralOption
from .widgets import DateTimePicker
from preferences.models import OptionalUser
from re2o.field_permissions import FieldPermissionFormMixin
from re2o.mixins import FormRevMixin
from re2o.utils import remove_user_room
from topologie.models import Port
from .models import (
User,
ServiceUser,
@ -65,6 +61,7 @@ from .models import (
Adherent,
Club
)
from .widgets import DateTimePicker
class PassForm(FormRevMixin, FieldPermissionFormMixin, forms.ModelForm):
@ -310,6 +307,7 @@ class AdherentForm(FormRevMixin, FieldPermissionFormMixin, ModelForm):
"""Formulaire de base d'edition d'un user. Formulaire de base, utilisé
pour l'edition de self par self ou un cableur. On formate les champs
avec des label plus jolis"""
def __init__(self, *args, **kwargs):
prefix = kwargs.pop('prefix', self.Meta.model.__name__)
super(AdherentForm, self).__init__(*args, prefix=prefix, **kwargs)
@ -344,7 +342,6 @@ class AdherentForm(FormRevMixin, FieldPermissionFormMixin, ModelForm):
'room',
]
def clean_telephone(self):
"""Verifie que le tel est présent si 'option est validée
dans preferences"""
@ -368,16 +365,17 @@ class AdherentForm(FormRevMixin, FieldPermissionFormMixin, ModelForm):
remove_user_room(self.cleaned_data.get('room'))
return
class AdherentCreationForm(AdherentForm):
"""Formulaire de création d'un user.
AdherentForm auquel on ajoute une checkbox afin d'éviter les
doublons d'utilisateurs"""
# Champ permettant d'éviter au maxium les doublons d'utilisateurs
former_user_check_info = _("If you already have an account, please use it. "\
+ "If your lost access to it, please consider "\
+ "using the forgotten password button on the "\
+ "login page or contacting support.")
former_user_check_info = _("If you already have an account, please use it. "
"If your lost access to it, please consider "
"using the forgotten password button on the "
"login page or contacting support.")
former_user_check = forms.BooleanField(required=True, help_text=former_user_check_info)
former_user_check.label = _("I certifie that I have not had an account before")
@ -389,9 +387,11 @@ class AdherentCreationForm(AdherentForm):
def __init__(self, *args, **kwargs):
super(AdherentCreationForm, self).__init__(*args, **kwargs)
class AdherentEditForm(AdherentForm):
"""Formulaire d'édition d'un user.
AdherentForm incluant la modification des champs gpg et shell"""
def __init__(self, *args, **kwargs):
super(AdherentEditForm, self).__init__(*args, **kwargs)
self.fields['gpg_fingerprint'].widget.attrs['placeholder'] = _("Leave empty if you don't have any GPG key.")
@ -419,10 +419,12 @@ class AdherentEditForm(AdherentForm):
'gpg_fingerprint'
]
class ClubForm(FormRevMixin, FieldPermissionFormMixin, ModelForm):
"""Formulaire de base d'edition d'un user. Formulaire de base, utilisé
pour l'edition de self par self ou un cableur. On formate les champs
avec des label plus jolis"""
def __init__(self, *args, **kwargs):
prefix = kwargs.pop('prefix', self.Meta.model.__name__)
super(ClubForm, self).__init__(*args, prefix=prefix, **kwargs)
@ -462,6 +464,7 @@ class ClubForm(FormRevMixin, FieldPermissionFormMixin, ModelForm):
class ClubAdminandMembersForm(FormRevMixin, ModelForm):
"""Permet d'éditer la liste des membres et des administrateurs
d'un club"""
class Meta:
model = Club
fields = ['administrators', 'members']
@ -478,6 +481,7 @@ class ClubAdminandMembersForm(FormRevMixin, ModelForm):
class PasswordForm(FormRevMixin, ModelForm):
""" Formulaire de changement brut de mot de passe.
Ne pas utiliser sans traitement"""
class Meta:
model = User
fields = ['password', 'pwd_ntlm']
@ -516,12 +520,14 @@ class ServiceUserForm(FormRevMixin, ModelForm):
class EditServiceUserForm(ServiceUserForm):
"""Formulaire d'edition de base d'un service user. Ne permet
d'editer que son group d'acl et son commentaire"""
class Meta(ServiceUserForm.Meta):
fields = ['access_group', 'comment']
class StateForm(FormRevMixin, ModelForm):
""" Changement de l'état d'un user"""
class Meta:
model = User
fields = ['state']
@ -552,6 +558,7 @@ class GroupForm(FieldPermissionFormMixin, FormRevMixin, ModelForm):
class SchoolForm(FormRevMixin, ModelForm):
"""Edition, creation d'un école"""
class Meta:
model = School
fields = ['name']
@ -564,6 +571,7 @@ class SchoolForm(FormRevMixin, ModelForm):
class ShellForm(FormRevMixin, ModelForm):
"""Edition, creation d'un école"""
class Meta:
model = ListShell
fields = ['shell']
@ -595,6 +603,7 @@ class ListRightForm(FormRevMixin, ModelForm):
class NewListRightForm(ListRightForm):
"""Ajout d'un groupe/list de droit """
class Meta(ListRightForm.Meta):
fields = ('name', 'unix_name', 'gid', 'critical', 'permissions',
'details')
@ -641,6 +650,7 @@ class DelSchoolForm(Form):
class BanForm(FormRevMixin, ModelForm):
"""Creation, edition d'un objet bannissement"""
def __init__(self, *args, **kwargs):
prefix = kwargs.pop('prefix', self.Meta.model.__name__)
super(BanForm, self).__init__(*args, prefix=prefix, **kwargs)
@ -655,6 +665,7 @@ class BanForm(FormRevMixin, ModelForm):
class WhitelistForm(FormRevMixin, ModelForm):
"""Creation, edition d'un objet whitelist"""
def __init__(self, *args, **kwargs):
prefix = kwargs.pop('prefix', self.Meta.model.__name__)
super(WhitelistForm, self).__init__(*args, prefix=prefix, **kwargs)
@ -669,6 +680,7 @@ class WhitelistForm(FormRevMixin, ModelForm):
class EMailAddressForm(FormRevMixin, ModelForm):
"""Create and edit a local email address"""
def __init__(self, *args, **kwargs):
prefix = kwargs.pop('prefix', self.Meta.model.__name__)
super(EMailAddressForm, self).__init__(*args, prefix=prefix, **kwargs)
@ -685,6 +697,7 @@ class EMailAddressForm(FormRevMixin, ModelForm):
class EmailSettingsForm(FormRevMixin, FieldPermissionFormMixin, ModelForm):
"""Edit email-related settings"""
def __init__(self, *args, **kwargs):
prefix = kwargs.pop('prefix', self.Meta.model.__name__)
super(EmailSettingsForm, self).__init__(*args, prefix=prefix, **kwargs)
@ -721,7 +734,9 @@ class InitialRegisterForm(forms.Form):
port = Port.objects.filter(switch__interface__ipv4__ipv4=switch_ip, port=switch_port).first()
# If a port exists, checking there is a room AND radius
if port:
if port.get_port_profile.radius_type != 'NO' and port.get_port_profile.radius_mode == 'STRICT' and hasattr(port, 'room'):
if (port.get_port_profile.radius_type != 'NO'
and port.get_port_profile.radius_mode == 'STRICT'
and hasattr(port, 'room')):
# Requesting user is not in this room ?
if self.user.room != port.room:
self.new_room = port.room

View file

@ -42,50 +42,45 @@ models sql classiques. Seuls certains champs essentiels sont
dupliqués.
"""
from __future__ import unicode_literals
import re
import uuid
import datetime
import re
import sys
import traceback
import uuid
from django.db import models
from django.db.models import Q
import ldapdb.models.fields
from django import forms
from django.forms import ValidationError
from django.db.models.signals import post_save, post_delete, m2m_changed
from django.dispatch import receiver
from django.utils.functional import cached_property
from django.template import Context, loader
from django.core.mail import send_mail
from django.core.urlresolvers import reverse
from django.db import transaction
from django.utils import timezone
from django.contrib.auth.models import (
AbstractBaseUser,
BaseUserManager,
PermissionsMixin,
Group
)
from django.core.mail import send_mail
from django.core.urlresolvers import reverse
from django.core.validators import RegexValidator
import traceback
from django.db import models
from django.db import transaction
from django.db.models import Q
from django.db.models.signals import post_save, post_delete, m2m_changed
from django.dispatch import receiver
from django.forms import ValidationError
from django.template import Context, loader
from django.utils import timezone
from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy as _
from reversion import revisions as reversion
import ldapdb.models
import ldapdb.models.fields
from re2o.settings import LDAP, GID_RANGES, UID_RANGES
from re2o.login import hashNT
from re2o.field_permissions import FieldPermissionModelMixin
from re2o.mixins import AclMixin, RevMixin
from cotisations.models import Cotisation, Facture, Paiement, Vente
from machines.models import Domain, Interface, Machine, regen
from preferences.models import GeneralOption, AssoOption, OptionalUser
from preferences.models import OptionalMachine, MailMessageOption
from re2o.field_permissions import FieldPermissionModelMixin
from re2o.login import hashNT
from re2o.mixins import AclMixin, RevMixin
from re2o.settings import LDAP, GID_RANGES, UID_RANGES
# Utilitaires généraux
@ -93,8 +88,8 @@ from preferences.models import OptionalMachine, MailMessageOption
def linux_user_check(login):
""" Validation du pseudo pour respecter les contraintes unix"""
UNIX_LOGIN_PATTERN = re.compile("^[a-zA-Z][a-zA-Z0-9-]*[$]?$")
return UNIX_LOGIN_PATTERN.match(login)
unix_login_pattern = re.compile("^[a-zA-Z][a-zA-Z0-9-]*[$]?$")
return unix_login_pattern.match(login)
def linux_user_validator(login):
@ -117,7 +112,7 @@ def get_fresh_user_uid():
used_uids = list(User.objects.values_list('uid_number', flat=True))
except:
used_uids = []
free_uids = [id for id in uids if id not in used_uids]
free_uids = [uid for uid in uids if uid not in used_uids]
return min(free_uids)
@ -128,7 +123,7 @@ def get_fresh_gid():
int(max(GID_RANGES['posix']))
))
used_gids = list(ListRight.objects.values_list('gid', flat=True))
free_gids = [id for id in gids if id not in used_gids]
free_gids = [gid for gid in gids if gid not in used_gids]
return min(free_gids)
@ -296,7 +291,8 @@ class User(RevMixin, FieldPermissionModelMixin, AbstractBaseUser,
@cached_property
def get_mail(self):
"""Return the mail address choosen by the user"""
if not OptionalUser.get_cached_value('local_email_accounts_enabled') or not self.local_email_enabled or self.local_email_redirect:
if (not OptionalUser.get_cached_value('local_email_accounts_enabled')
or not self.local_email_enabled or self.local_email_redirect):
return str(self.email)
else:
return str(self.emailaddress_set.get(local_part=self.pseudo.lower()))
@ -336,7 +332,8 @@ class User(RevMixin, FieldPermissionModelMixin, AbstractBaseUser,
def set_active(self):
"""Enable this user if he subscribed successfully one time before"""
if self.state == self.STATE_NOT_YET_ACTIVE:
if self.facture_set.filter(valid=True).filter(Q(vente__type_cotisation='All') | Q(vente__type_cotisation='Adhesion')).exists():
if self.facture_set.filter(valid=True).filter(
Q(vente__type_cotisation='All') | Q(vente__type_cotisation='Adhesion')).exists():
self.state = self.STATE_ACTIVE
self.save()
@ -741,7 +738,7 @@ class User(RevMixin, FieldPermissionModelMixin, AbstractBaseUser,
def set_password(self, password):
""" A utiliser de préférence, set le password en hash courrant et
dans la version ntlm"""
super().set_password(password)
super(User).set_password(password)
self.pwd_ntlm = hashNT(password)
return
@ -885,10 +882,9 @@ class User(RevMixin, FieldPermissionModelMixin, AbstractBaseUser,
return True, None
@staticmethod
def can_change_local_email_redirect(user_request, *_args, **_kwargs):
def can_change_local_email_redirect(*_args, **_kwargs):
""" Check if a user can change local_email_redirect.
:param user_request: The user who request
:returns: a message and a boolean which is True if the user has
the right to change a redirection
"""
@ -898,7 +894,7 @@ class User(RevMixin, FieldPermissionModelMixin, AbstractBaseUser,
)
@staticmethod
def can_change_local_email_enabled(user_request, *_args, **_kwargs):
def can_change_local_email_enabled(*_args, **_kwargs):
""" Check if a user can change internal address.
:param user_request: The user who request
@ -1399,7 +1395,6 @@ class ListShell(RevMixin, AclMixin, models.Model):
verbose_name = _("shell")
verbose_name_plural = _("shells")
def get_pretty_name(self):
"""Return the canonical name of the shell"""
return self.shell.split("/")[-1]
@ -1586,7 +1581,7 @@ class Request(models.Model):
created_at = models.DateTimeField(auto_now_add=True, editable=False)
expires_at = models.DateTimeField()
def save(self):
def save(self, **kwargs):
if not self.expires_at:
self.expires_at = (timezone.now() +
datetime.timedelta(
@ -1682,7 +1677,7 @@ class LdapUser(ldapdb.models.Model):
self.sn = self.name
self.uid = self.name
self.sambaSID = self.uidNumber
super(LdapUser, self).save(*args, **kwargs)
super(LdapUser, self).save()
class LdapUserGroup(ldapdb.models.Model):
@ -1885,4 +1880,3 @@ class EMailAddress(RevMixin, AclMixin, models.Model):
if "@" in self.local_part:
raise ValidationError(_("The local part must not contain @."))
super(EMailAddress, self).clean(*args, **kwargs)

View file

@ -27,6 +27,7 @@ Serializers for the User app
"""
from rest_framework import serializers
from users.models import Club, Adherent

View file

@ -23,13 +23,9 @@
The tests for the Users module.
"""
import os.path
from django.test import TestCase
from django.conf import settings
from . import models
import volatildap
from . import models
class SchoolTestCase(TestCase):
@ -84,4 +80,3 @@ class LdapServiceUserTestCase(TestCase):
user_password="{SSHA}AbCdEfGhIjKlMnOpQrStUvWxYz987654"
)
self.assertEqual(g.name, 'users_test_ldapserviceuser')

View file

@ -36,30 +36,24 @@ des whitelist, des services users et des écoles
from __future__ import unicode_literals
from django.urls import reverse
from django.shortcuts import get_object_or_404, render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required, permission_required
from django.db.models import ProtectedError, Count, Max
from django.utils import timezone
from django.db import transaction
from django.db.models import ProtectedError, Count, Max
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import get_object_or_404, render, redirect
from django.urls import reverse
from django.utils import timezone
from django.utils.translation import ugettext as _
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from reversion import revisions as reversion
from cotisations.models import Facture, Paiement
from cotisations.utils import find_payment_method
from machines.models import Machine
from preferences.models import OptionalUser, GeneralOption, AssoOption
from re2o.views import form
from re2o.utils import (
all_has_access,
SortTable,
re2o_paginator
)
from re2o.acl import (
can_create,
can_edit,
@ -69,22 +63,13 @@ from re2o.acl import (
can_view_all,
can_change
)
from cotisations.utils import find_payment_method
from topologie.models import Port
from .serializers import MailingSerializer, MailingMemberSerializer
from .models import (
User,
Ban,
Whitelist,
School,
ListRight,
Request,
ServiceUser,
Adherent,
Club,
ListShell,
EMailAddress,
from re2o.utils import (
all_has_access,
SortTable,
re2o_paginator
)
from re2o.views import form
from topologie.models import Port
from .forms import (
BanForm,
WhitelistForm,
@ -109,6 +94,20 @@ from .forms import (
GroupForm,
InitialRegisterForm
)
from .models import (
User,
Ban,
Whitelist,
School,
ListRight,
Request,
ServiceUser,
Adherent,
Club,
ListShell,
EMailAddress,
)
from .serializers import MailingSerializer, MailingMemberSerializer
@can_create(Adherent)
@ -116,8 +115,8 @@ def new_user(request):
""" Vue de création d'un nouvel utilisateur,
envoie un mail pour le mot de passe"""
user = AdherentCreationForm(request.POST or None, user=request.user)
GTU_sum_up = GeneralOption.get_cached_value('GTU_sum_up')
GTU = GeneralOption.get_cached_value('GTU')
gtu_sum_up = GeneralOption.get_cached_value('GTU_sum_up')
gtu = GeneralOption.get_cached_value('GTU')
if user.is_valid():
user = user.save()
user.reset_passwd_mail(request)
@ -130,8 +129,8 @@ def new_user(request):
return form(
{
'userform': user,
'GTU_sum_up': GTU_sum_up,
'GTU': GTU,
'GTU_sum_up': gtu_sum_up,
'GTU': gtu,
'showCGU': True,
'action_name': _("Commit")
},
@ -1083,18 +1082,21 @@ def process_passwd(request, req):
request
)
@login_required
def initial_register(request):
switch_ip = request.GET.get('switch_ip', None)
switch_port = request.GET.get('switch_port', None)
client_mac = request.GET.get('client_mac', None)
u_form = InitialRegisterForm(request.POST or None, user=request.user, switch_ip=switch_ip, switch_port=switch_port, client_mac=client_mac)
u_form = InitialRegisterForm(request.POST or None, user=request.user, switch_ip=switch_ip, switch_port=switch_port,
client_mac=client_mac)
if not u_form.fields:
messages.error(request, _("Incorrect URL, or already registered device"))
return redirect(reverse(
'users:profil',
kwargs={'userid': str(request.user.id)}
))
port = None # TODO: local variable initialized only if condition succeed
if switch_ip and switch_port:
port = Port.objects.filter(switch__interface__ipv4__ipv4=switch_ip, port=switch_port).first()
if u_form.is_valid():
@ -1189,4 +1191,3 @@ def ml_club_members(request, ml_name):
)
seria = MailingMemberSerializer(members, many=True)
return JSONResponse(seria.data)

View file

@ -1,18 +1,17 @@
from django.forms.widgets import Input
from django.forms.utils import flatatt
from django.utils.safestring import mark_safe
from django.template import Context, Template
from django.template.loader import get_template
from django.conf import settings
from django.utils.translation import ugettext_lazy as _, get_language_bidi
from django.forms.utils import flatatt
from django.forms.widgets import Input
from django.template import Context
from django.template.loader import get_template
from django.utils.dates import (
WEEKDAYS,
WEEKDAYS_ABBR,
MONTHS,
MONTHS_3,
MONTHS_AP,
MONTHS_ALT
MONTHS_3
)
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _, get_language_bidi
def list2str(str_iterable):
"""
@ -23,10 +22,12 @@ def list2str(str_iterable):
"""
return '["' + '", "'.join(str_iterable) + '"]'
class DateTimePicker(Input):
is_localized = False
def render(self, name, value, attrs=None):
super().render(name, value, attrs)
def render(self, name, value, attrs=None, **kwargs):
super(DateTimePicker).render(name, value, attrs)
flat_attrs = flatatt(attrs)
context = Context({
'name': name,
@ -47,4 +48,3 @@ class DateTimePicker(Input):
})
template = get_template('users/datetimepicker.html')
return template.render(context)