refactor Accounts

parent bd37436d
Pipeline #552 failed with stage
in 3 seconds
...@@ -7,10 +7,10 @@ from django.utils.translation import gettext_lazy as _ ...@@ -7,10 +7,10 @@ from django.utils.translation import gettext_lazy as _
class CustomUserManager(UserManager): class CustomUserManager(UserManager):
def get_or_none(self, **kwargs): def get_or_none(self, **kwargs):
'''Devuelve el usuario con las propiedades indicadas. """Devuelve el usuario con las propiedades indicadas.
Si no se encuentra, devuelve `None`. Si no se encuentra, devuelve `None`.
''' """
try: try:
return self.get(**kwargs) return self.get(**kwargs)
except CustomUser.DoesNotExist: except CustomUser.DoesNotExist:
...@@ -18,6 +18,8 @@ class CustomUserManager(UserManager): ...@@ -18,6 +18,8 @@ class CustomUserManager(UserManager):
class CustomUser(AbstractUser): class CustomUser(AbstractUser):
AbstractUser._meta.get_field('username').verbose_name = _('NIP') # Cambio verbose_name
AbstractUser._meta.get_field('last_name').verbose_name = _('primer apellido') # Cambio verbose_name
# Campos sobrescritos # Campos sobrescritos
first_name = models.CharField(_('first name'), max_length=50, blank=True) # era: max_length=30 first_name = models.CharField(_('first name'), max_length=50, blank=True) # era: max_length=30
# Campos adicionales # Campos adicionales
...@@ -35,21 +37,25 @@ class CustomUser(AbstractUser): ...@@ -35,21 +37,25 @@ class CustomUser(AbstractUser):
departamento_id_nks = models.CharField(_('Cód. departamentos'), max_length=127, blank=True, null=True) departamento_id_nks = models.CharField(_('Cód. departamentos'), max_length=127, blank=True, null=True)
colectivos = models.CharField(max_length=127, blank=True, null=True) colectivos = models.CharField(max_length=127, blank=True, null=True)
@property
def full_name(self):
"""Devuelve el nombre completo (nombre y los dos apellidos)."""
return ' '.join(part.strip() for part in (self.first_name, self.last_name, self.last_name_2) if part)
# Metodos sobrescritos # Metodos sobrescritos
def get_full_name(self): def get_full_name(self):
'''Devuelve el nombre completo (nombre y los dos apellidos).''' """Devuelve el nombre completo (nombre y los dos apellidos)."""
full_name = '%s %s %s' % (self.first_name, self.last_name, self.last_name_2) return self.full_name
return full_name.strip()
# Métodos adicionales # Métodos adicionales
def __str__(self): def __str__(self):
return self.username return self.username
def get_colectivo_principal(self): def get_colectivo_principal(self):
'''Devuelve el colectivo principal del usuario. """Devuelve el colectivo principal del usuario.
Se determina usando el orden de prelación PDI > ADS > PAS > EST. Se determina usando el orden de prelación PDI > ADS > PAS > EST.
''' """
colectivos_del_usuario = json.loads(self.colectivos) if self.colectivos else [] colectivos_del_usuario = json.loads(self.colectivos) if self.colectivos else []
for col in ('PDI', 'ADS', 'PAS', 'EST'): for col in ('PDI', 'ADS', 'PAS', 'EST'):
if col in colectivos_del_usuario: if col in colectivos_del_usuario:
......
...@@ -14,7 +14,7 @@ from django.core.validators import ValidationError, validate_email ...@@ -14,7 +14,7 @@ from django.core.validators import ValidationError, validate_email
def get_identidad(strategy, response, user, *args, **kwargs): def get_identidad(strategy, response, user, *args, **kwargs):
'''Actualiza el usuario con los datos obtenidos de Gestión de Identidades.''' """Actualiza el usuario con los datos obtenidos de Gestión de Identidades."""
wsdl = get_config('WSDL_IDENTIDAD') wsdl = get_config('WSDL_IDENTIDAD')
session = Session() session = Session()
...@@ -24,8 +24,9 @@ def get_identidad(strategy, response, user, *args, **kwargs): ...@@ -24,8 +24,9 @@ def get_identidad(strategy, response, user, *args, **kwargs):
client = zeep.Client(wsdl=wsdl, transport=zeep.transports.Transport(session=session)) client = zeep.Client(wsdl=wsdl, transport=zeep.transports.Transport(session=session))
except RequestConnectionError: except RequestConnectionError:
raise RequestConnectionError('No fue posible conectarse al WS de Identidades.') raise RequestConnectionError('No fue posible conectarse al WS de Identidades.')
except: # noqa: E722 except Exception as e:
raise print(e)
raise e
response = client.service.obtenIdentidad(user.username) response = client.service.obtenIdentidad(user.username)
if response.aviso: if response.aviso:
...@@ -63,7 +64,7 @@ def get_identidad(strategy, response, user, *args, **kwargs): ...@@ -63,7 +64,7 @@ def get_identidad(strategy, response, user, *args, **kwargs):
def is_email_valid(email): def is_email_valid(email):
'''Validate email address''' """Validate email address"""
try: try:
validate_email(email) validate_email(email)
except ValidationError: except ValidationError:
......
# third-party
from annoying.functions import get_config from annoying.functions import get_config
from social_django.utils import load_backend, load_strategy
# Django
from django.contrib.auth import logout from django.contrib.auth import logout
from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponse from django.http import HttpResponse
...@@ -7,11 +11,10 @@ from django.urls import reverse, reverse_lazy ...@@ -7,11 +11,10 @@ from django.urls import reverse, reverse_lazy
from django.utils.decorators import method_decorator from django.utils.decorators import method_decorator
from django.views.decorators.cache import never_cache from django.views.decorators.cache import never_cache
from django.views.generic.base import RedirectView, View from django.views.generic.base import RedirectView, View
from social_django.utils import load_backend, load_strategy
def metadata_xml(request): def metadata_xml(request):
'''Muestra los metadatos para el Proveedor de Identidad (IdP) de SAML.''' """Muestra los metadatos para el Proveedor de Identidad (IdP) de SAML."""
complete_url = reverse('social:complete', args=('saml',)) complete_url = reverse('social:complete', args=('saml',))
saml_backend = load_backend(load_strategy(request), 'saml', redirect_uri=complete_url) saml_backend = load_backend(load_strategy(request), 'saml', redirect_uri=complete_url)
metadata, errors = saml_backend.generate_metadata_xml() metadata, errors = saml_backend.generate_metadata_xml()
...@@ -21,7 +24,7 @@ def metadata_xml(request): ...@@ -21,7 +24,7 @@ def metadata_xml(request):
class UserdataView(LoginRequiredMixin, View): class UserdataView(LoginRequiredMixin, View):
'''Muestra los datos del usuario.''' """Muestra los datos del usuario."""
def get(self, request, *args, **kwargs): def get(self, request, *args, **kwargs):
context = {} context = {}
...@@ -33,11 +36,11 @@ class UserdataView(LoginRequiredMixin, View): ...@@ -33,11 +36,11 @@ class UserdataView(LoginRequiredMixin, View):
@method_decorator(never_cache, name='dispatch') @method_decorator(never_cache, name='dispatch')
class LogoutView(LoginRequiredMixin, RedirectView): class LogoutView(LoginRequiredMixin, RedirectView):
'''Log out the current user. """Log out the current user.
This view logs out a locally authenticated user, This view logs out a locally authenticated user,
or sends a Logout request to the SAML2 Identity Provider. or sends a Logout request to the SAML2 Identity Provider.
''' """
url = reverse_lazy(get_config('LOGOUT_REDIRECT_URL')) url = reverse_lazy(get_config('LOGOUT_REDIRECT_URL'))
...@@ -55,11 +58,11 @@ class LogoutView(LoginRequiredMixin, RedirectView): ...@@ -55,11 +58,11 @@ class LogoutView(LoginRequiredMixin, RedirectView):
@method_decorator(never_cache, name='dispatch') @method_decorator(never_cache, name='dispatch')
class SlsView(View): class SlsView(View):
''' """
The Single Logout Service processes the Logout response from the Identity Provider. The Single Logout Service processes the Logout response from the Identity Provider.
The logout request may have been generated by this Service Provider, or other SP. The logout request may have been generated by this Service Provider, or other SP.
''' """
url = reverse_lazy(get_config('LOGOUT_REDIRECT_URL')) url = reverse_lazy(get_config('LOGOUT_REDIRECT_URL'))
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment