Skip to content

Commit

Permalink
Fixed when user has not profile because lost OTP and not end the regi…
Browse files Browse the repository at this point in the history
…ster, now redirect register otp view.
  • Loading branch information
luisza committed Jan 10, 2024
1 parent 69a485a commit 48631ec
Show file tree
Hide file tree
Showing 8 changed files with 119 additions and 34 deletions.
8 changes: 7 additions & 1 deletion src/auth_and_perms/forms.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from django import forms
from django.conf import settings
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User, Group
from django.utils.translation import gettext_lazy as _
Expand Down Expand Up @@ -78,10 +79,15 @@ class AddProfileForm(OTPTokenForm, GTForm):
job_position = forms.CharField(label=_('Job Position'), max_length=100,
widget=genwidgets.TextInput)

language = forms.ChoiceField(choices=settings.LANGUAGES,
widget=genwidgets.Select,
initial=settings.LANGUAGE_CODE,
label=_("Language") )

field_order = [
'first_name', 'last_name', 'email', 'phone_number', 'id_card', 'job_position',
'otp_device',
'otp_challenge', 'otp_token'
'otp_challenge', 'otp_token', 'language'
]

def __init__(self, *args, **kwargs):
Expand Down
20 changes: 13 additions & 7 deletions src/auth_and_perms/middleware.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.db.models import Q
from django.contrib.auth import logout as auth_logout
from django.http import Http404

from auth_and_perms.models import ProfilePermission
from laboratory.models import OrganizationStructure
from laboratory.utils import get_laboratories_by_user_profile
from django.shortcuts import redirect
from django.urls import reverse
from django.utils import translation

from auth_and_perms.models import RegistrationUser


class ProfileLanguageMiddleware:
def __init__(self, get_response):
self.get_response = get_response
Expand All @@ -22,6 +21,13 @@ def process_view(self, request, view_func, view_args, view_kwargs):
if not user.is_authenticated or not user.is_active:
return
if not hasattr(user, 'profile'):
reguser = RegistrationUser.objects.filter(user=user).first()
if reguser:
auth_logout(request)
if reguser.registration_method == 1:
return redirect(reverse('auth_and_perms:user_org_creation_totp', args=[user.pk]))
if reguser.registration_method == 2:
return redirect(reverse('auth_and_perms:create_profile_by_digital_signature', args=[user.pk]))
raise Http404("User has not profile")

profile = user.profile
Expand Down
10 changes: 4 additions & 6 deletions src/auth_and_perms/views/organizationstructure.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.http import HttpResponseForbidden, Http404
from django.http import HttpResponseForbidden, Http404, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404, redirect
from django.urls import reverse
from django.utils.decorators import method_decorator
Expand Down Expand Up @@ -235,12 +235,10 @@ def get_success_url(self):
return reverse('auth_and_perms:organizationManager')

def form_valid(self, form):
response = super().form_valid(form)
response = HttpResponseRedirect(self.get_success_url())
password = User.objects.make_random_password()
form.save()
user = User.objects.filter(
username=form.cleaned_data['username']
).first()
user = form.save(commit=True)
user.username=form.cleaned_data['email']
user.password = password
user.save()
#self.organization.users.add(user)
Expand Down
13 changes: 8 additions & 5 deletions src/auth_and_perms/views/user_org_creation.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,23 +72,25 @@ def set_rol_administrator_on_org(profile, organization, type_in_organization=Use
def create_user_organization(user, organization, data, user_type=UserOrganization.LABORATORY_USER):
profile = Profile.objects.create(user=user, phone_number=data['phone_number'],
id_card=data['id_card'],
job_position=data['job_position'])
job_position=data['job_position'],
language=data['language'])
if isinstance(organization, str):
org = OrganizationStructure.objects.create(name=organization)
else:
org = organization
set_rol_administrator_on_org(profile, org, type_in_organization=user_type)
user.active = True
user.save()
# //UserOrganization.objects.create(user=user, organization=org, status=True, type_in_organization=user_type)
# UserOrganization.objects.create(user=user, organization=org, status=True, type_in_organization=user_type)

@transaction.atomic
def create_profile_otp(request, pk):
user = get_object_or_404(User, pk=pk)
device = TOTPDevice.objects.get(user__pk=pk)
form = partial(AddProfileForm, user)
if request.method == 'POST':
form = form(data=request.POST, initial={'otp_device': 'otp_totp.totpdevice/%d'%device.pk})
form = form(data=request.POST, initial={
'otp_device': 'otp_totp.totpdevice/%d'%device.pk})
if form.is_valid():
reguser = RegistrationUser.objects.filter(
user=user,
Expand All @@ -103,7 +105,8 @@ def create_profile_otp(request, pk):
messages.error(request, _("You have no creation process, maybe it was expired, please try to register again"))
return redirect(reverse('auth_and_perms:register_user_to_platform'))
else:
form = form(initial={'otp_device': 'otp_totp.totpdevice/%d'%device.pk, 'email': user.email})
form = form(initial={'otp_device': 'otp_totp.totpdevice/%d'%device.pk,
'email': user.username})
context={
'form': form,
'user': user.pk
Expand Down Expand Up @@ -146,4 +149,4 @@ def show_QR_img(request, pk):
img = qrcode.make(device.config_url, image_factory=qrcode.image.svg.SvgImage)
response = HttpResponse(content_type='image/svg+xml')
img.save(response)
return response
return response
9 changes: 7 additions & 2 deletions src/authentication/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,16 @@ class CreateUserForm(forms.ModelForm, GTForm):
id_card = forms.CharField(label=_('ID Card'), max_length=100, widget=djgenwidgets.TextInput)
job_position = forms.CharField(label=_('Job Position'), max_length=100, widget=djgenwidgets.TextInput)

def clean_email(self):
value = self.cleaned_data['email']
if User.objects.using(settings.READONLY_DATABASE).filter(username=value):
raise ValidationError(_("User email exist, please try to add user on organization modal"))
return value

class Meta:
model = User
fields = ['username', 'first_name', 'last_name', 'email']
fields = ['first_name', 'last_name', 'email']
widgets = {
'username': djgenwidgets.TextInput,
'first_name': djgenwidgets.TextInput,
'last_name': djgenwidgets.TextInput,
'email': djgenwidgets.EmailMaskInput
Expand Down
20 changes: 16 additions & 4 deletions src/authentication/templates/auth/user_form.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,27 @@
<div class="container">
<div class="row">
<div class='col-md-6 col-md-offset-1 '><form action="" method="POST">
<h2 class="text-center">{% trans 'New User' %}</h2>
<h2 class="text-center">{% trans 'New User' %} </h2>
{{ form.as_horizontal }}
{% csrf_token %}
<div class="form-group">
<input type="submit" class="btn btn-success text-center" value="{% trans 'Create' %}" name="btnsubmit" />
</div> </form>
</div>
<div class='col-md-4 col-md-offset-2 '>
<div class="card border-primary mb-3" >
<div class="card-header">{% trans "Help" %}</div>
<div class="card-body">
<h5 class="card-title">{% trans "What happen with the user you will create" %}</h5>
<p class="card-text">{% trans "To the created user, an email will be sent with instructions on how to change their password. Please contact them to check their email. Some emails might go to the SPAM folder, so please also check the SPAM mailbox." %}</p>
<p class="card-text">{% trans "The email is used as username." %}</p>
<p class="card-text">{% blocktranslate %}The user is created with the default role of Student, so they will be ready to be added to the desired laboratory. You can add an administrative role by adding the user to the organization in the organization tab. In both cases, the user should be assigned roles in each laboratory.
Remember, you can use the user creation functionality via QR code provided in the laboratory administration to simplify the role assignment for a large number of users.{% endblocktranslate %}</p>
</div>
</div>
</div>
</div>

</div>
</div>
</div>

{% endblock %}
{% endblock %}
22 changes: 17 additions & 5 deletions src/laboratory/views/laboratory.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,13 +125,25 @@ def form_valid(self, form):
relobj=self.object)

user = self.request.user
admins = User.objects.filter(is_superuser=True)
contenttypeobj=self.object
ppp = user.profile.profilepermission_set.first()

rol = ppp.rol.first() if ppp else None
pp, created =ProfilePermission.objects.get_or_create(
profile=user.profile,
content_type=ContentType.objects.filter(app_label=contenttypeobj._meta.app_label,
model=contenttypeobj._meta.model_name).first(),
object_id=contenttypeobj.pk
)
if created and rol:
pp.rol.add(rol)
# admins = User.objects.filter(is_superuser=True)
# TODO: This is necesary ? all user has to be profile
user.profile.laboratories.add(self.object)
for admin in admins:
if not hasattr(admin, 'profile'):
admin.profile = Profile.objects.create(user=admin)
admin.profile.laboratories.add(self.object)
# for admin in admins:
# if not hasattr(admin, 'profile'):
# admin.profile = Profile.objects.create(user=admin)
# admin.profile.laboratories.add(self.object)
response = super(CreateLaboratoryFormView, self).form_valid(form)

return response
Expand Down
51 changes: 47 additions & 4 deletions src/locale/es/LC_MESSAGES/django.po
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2024-01-08 12:44-0600\n"
"POT-Creation-Date: 2024-01-09 21:36-0600\n"
"PO-Revision-Date: \n"
"Last-Translator: \n"
"Language-Team: \n"
Expand Down Expand Up @@ -330,6 +330,9 @@ msgstr "Identificación"
msgid "Job Position"
msgstr "Puesto de Trabajo"

msgid "Language"
msgstr "Idioma"

msgid "It will used to login when you want to login with digital signature"
msgstr "Este campo será usado cuando se autentique con firma digital"

Expand All @@ -354,9 +357,6 @@ msgstr "Organización no existe"
msgid "ID Card"
msgstr "Tarjeta de identificación"

msgid "Language"
msgstr "Idioma"

msgid "Can add external user to organization"
msgstr "Puede agregar usuarios externos a la organización"

Expand Down Expand Up @@ -665,6 +665,11 @@ msgstr ""
"No tiene un proceso de creación activo, o está expirado, por favor vuelva a "
"inscribirse"

msgid "User email exist, please try to add user on organization modal"
msgstr ""
"Usuario no existe, Lo lamentamos, intente agregar el usuario en modal de "
"organización"

msgid "Password"
msgstr "Contraseña"

Expand Down Expand Up @@ -701,6 +706,44 @@ msgstr "Nuevo Usuario"
msgid "Create"
msgstr "Crear"

msgid "Help"
msgstr "Ayuda"

msgid "What happen with the user you will create"
msgstr "Qué pasa cuando se crea un usuario"

msgid ""
"To the created user, an email will be sent with instructions on how to "
"change their password. Please contact them to check their email. Some emails "
"might go to the SPAM folder, so please also check the SPAM mailbox."
msgstr ""
"Al usuario creado le llegará un correo electrónico donde se le facilita el "
"cambio de contraseña del usuario, comuníquese con él para que revise su "
"correo.\n"
"Algunos correos podrían llegar al SPAM, por favor revisar también la bandeja "
"de correos SPAM"

msgid "The email is used as username."
msgstr "El correo será usado como nombre de usuario"

msgid ""
"The user is created with the default role of Student, so they will be ready "
"to be added to the desired laboratory. You can add an administrative role by "
"adding the user to the organization in the organization tab. In both cases, "
"the user should be assigned roles in each laboratory.\n"
"Remember, you can use the user creation functionality via QR code provided "
"in the laboratory administration to simplify the role assignment for a large "
"number of users."
msgstr ""
"El usuario se crea con el rol Estudiante por defecto, por lo que quedará "
"listo para agregar al laboratorio deseado, puede agregar un rol "
"administrativo agregando el usuario a la organización en la pestaña de "
"organización, en ambos caso al usuario se le deberán asignar los roles en "
"cada laboratorio.\n"
"Recuerde puede usar la funcionalidad de creación de usuarios mediante QR "
"provista en la administración del laboratorio para simplificar la asignación "
"de roles a un gran número de usuarios"

msgid "Feedback"
msgstr "Retroalimentación"

Expand Down

0 comments on commit 48631ec

Please sign in to comment.