diff --git a/access_controller/urls.py b/access_controller/urls.py index e174717..9550e6b 100644 --- a/access_controller/urls.py +++ b/access_controller/urls.py @@ -17,28 +17,27 @@ from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include -from main.views import main_page, profile_page, CustomRegistrationView, CustomLoginView +from main.views import main_page, profile_page, CustomRegistrationView, CustomLoginView, registration_error from main.views import work_page, work_hand_over, work_become_engineer, \ AdminPageView, statistic_page from main.urls import router - urlpatterns = [ path('admin/', admin.site.urls, name='admin'), path('', main_page, name='index'), path('accounts/profile/', profile_page, name='profile'), path('accounts/register/', CustomRegistrationView.as_view(), name='registration'), + path('accounts/register/error/', registration_error, name='registration_email_error'), path('accounts/login/', CustomLoginView.as_view(), name='login'), path('accounts/', include('django.contrib.auth.urls')), path('accounts/', include('django_registration.backends.one_step.urls')), path('work/', work_page, name="work"), path('work/hand_over/', work_hand_over, name="work_hand_over"), path('work/become_engineer/', work_become_engineer, name="work_become_engineer"), - path('accounts/', include('django_registration.backends.activation.urls')), path('accounts/login/', include('django.contrib.auth.urls')), path('control/', AdminPageView.as_view(), name='control'), path('statistic/', statistic_page, name='statistic') - ] +] urlpatterns += [ path( @@ -47,7 +46,7 @@ urlpatterns += [ name='password_reset' ), path( - 'password-reset/done/', + 'password_reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done' ), diff --git a/logs/.gitkeep b/logs/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/main/extra_func.py b/main/extra_func.py index 6358d7e..758875a 100644 --- a/main/extra_func.py +++ b/main/extra_func.py @@ -94,12 +94,12 @@ class ZendeskAdmin: def get_group(self, name: str) -> str: """ - Функция возвращает группы, к которым принадлежит пользователь. + Функция возвращает группу по названию :param name: Имя пользователя :return: Группы пользователя (в случае отсутствия None) """ - groups = self.admin.search(name) + groups = self.admin.search(name, type='group') for group in groups: return group return None diff --git a/main/templates/django_registration/registration_error.html b/main/templates/django_registration/registration_error.html new file mode 100644 index 0000000..603e103 --- /dev/null +++ b/main/templates/django_registration/registration_error.html @@ -0,0 +1,15 @@ +{% extends 'base/base.html' %} +{% load static %} + +{% block title %} + Регистрация завершена +{% endblock %} + +{% block heading %} + Регистрация +{% endblock %} + +{% block content %} +
+

Произошла ошибка при отправке электронного сообщения.

+{% endblock %} diff --git a/main/views.py b/main/views.py index 629fdf1..0e31a5d 100644 --- a/main/views.py +++ b/main/views.py @@ -2,6 +2,9 @@ import logging import os from datetime import datetime +from smtplib import SMTPException + +from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin from django.contrib.auth.models import User, Permission @@ -13,23 +16,19 @@ from django.contrib.messages.views import SuccessMessageMixin from django.core.exceptions import PermissionDenied from django.core.handlers.wsgi import WSGIRequest from django.http import HttpResponseRedirect, HttpResponse -from django.shortcuts import render, get_list_or_404, redirect +from django.shortcuts import render, redirect from django.urls import reverse_lazy, reverse from django.views.generic import FormView from django_registration.views import RegistrationView -from django.contrib import messages - # Django REST from rest_framework import viewsets from rest_framework.response import Response - from zenpy.lib.api_objects import User as ZenpyUser -from access_controller.settings import EMAIL_HOST_USER, ZENDESK_ROLES, ZENDESK_MAX_AGENTS -from main.extra_func import ZendeskAdmin +from access_controller.settings import EMAIL_HOST_USER, ZENDESK_ROLES, ZENDESK_MAX_AGENTS, ZENDESK_GROUPS from main.extra_func import check_user_exist, update_profile, get_user_organization, \ make_engineer, make_light_agent, get_users_list, update_users_in_model, count_users, \ - StatisticData, log + StatisticData, log, ZendeskAdmin from main.forms import AdminPageUsers, CustomRegistrationForm, CustomAuthenticationForm, StatisticForm from main.serializers import ProfileSerializer, ZendeskUserSerializer from .models import UserProfile @@ -50,8 +49,12 @@ class CustomRegistrationView(RegistrationView): """ form_class = CustomRegistrationForm template_name = 'django_registration/registration_form.html' - success_url = reverse_lazy('django_registration_complete') - is_allowed = True + urls = { + 'done': reverse_lazy('password_reset_done'), + 'invalid_zendesk_email': reverse_lazy('django_registration_disallowed'), + 'email_sending_error': reverse_lazy('registration_email_error'), + } + redirect_url = 'done' def register(self, form: CustomRegistrationForm) -> User: """ @@ -64,7 +67,7 @@ class CustomRegistrationView(RegistrationView): :param form: Email пользователя на Zendesk :return: user """ - self.is_allowed = True + self.redirect_url = 'done' if check_user_exist(form.data['email']) and get_user_organization(form.data['email']) == 'SYSTEM': forms = PasswordResetForm(self.request.POST) if forms.is_valid(): @@ -83,14 +86,17 @@ class CustomRegistrationView(RegistrationView): email=form.data['email'], password=User.objects.make_random_password(length=50) ) - forms.save(**opts) - update_profile(user.userprofile) - self.set_permission(user) - return user + try: + update_profile(user.userprofile) + self.set_permission(user) + forms.save(**opts) + return user + except SMTPException: + self.redirect_url = 'email_sending_error' else: raise ValueError('Непредвиденная ошибка') else: - self.is_allowed = False + self.redirect_url = 'invalid_zendesk_email' @staticmethod def set_permission(user: User) -> None: @@ -107,7 +113,7 @@ class CustomRegistrationView(RegistrationView): ) user.user_permissions.add(permission) - def get_success_url(self, user: User = None) -> success_url: + def get_success_url(self, user: User = None): """ Функция возвращает url-адрес страницы, куда нужно перейти после успешной/не успешной регистрации. Используется самой django-registration. @@ -115,10 +121,11 @@ class CustomRegistrationView(RegistrationView): :param user: пользователь, пытающийся зарегистрироваться :return: адресация на страницу успешной регистрации """ - if self.is_allowed: - return reverse_lazy('password_reset_done') - else: - return reverse_lazy('django_registration_disallowed') + return self.urls[self.redirect_url] + + +def registration_error(request): + return render(request, 'django_registration/registration_error.html') @login_required() @@ -352,7 +359,7 @@ def statistic_page(request: WSGIRequest) -> HttpResponse: :return: адресация на страницу статистики """ if not request.user.has_perm('main.has_control_access'): - return PermissionDenied + raise PermissionDenied context = { 'pagename': 'страница статистики', 'errors': list(),