This commit is contained in:
Artyom Kravchenko 2021-04-14 09:23:29 +03:00
commit 22f1d1394a
5 changed files with 49 additions and 28 deletions

View File

@ -17,28 +17,27 @@ from django.contrib import admin
from django.contrib.auth import views as auth_views from django.contrib.auth import views as auth_views
from django.urls import path, include 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, \ from main.views import work_page, work_hand_over, work_become_engineer, \
AdminPageView, statistic_page AdminPageView, statistic_page
from main.urls import router from main.urls import router
urlpatterns = [ urlpatterns = [
path('admin/', admin.site.urls, name='admin'), path('admin/', admin.site.urls, name='admin'),
path('', main_page, name='index'), path('', main_page, name='index'),
path('accounts/profile/', profile_page, name='profile'), path('accounts/profile/', profile_page, name='profile'),
path('accounts/register/', CustomRegistrationView.as_view(), name='registration'), 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/login/', CustomLoginView.as_view(), name='login'),
path('accounts/', include('django.contrib.auth.urls')), path('accounts/', include('django.contrib.auth.urls')),
path('accounts/', include('django_registration.backends.one_step.urls')), path('accounts/', include('django_registration.backends.one_step.urls')),
path('work/<int:id>', work_page, name="work"), path('work/<int:id>', work_page, name="work"),
path('work/hand_over/', work_hand_over, name="work_hand_over"), path('work/hand_over/', work_hand_over, name="work_hand_over"),
path('work/become_engineer/', work_become_engineer, name="work_become_engineer"), 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('accounts/login/', include('django.contrib.auth.urls')),
path('control/', AdminPageView.as_view(), name='control'), path('control/', AdminPageView.as_view(), name='control'),
path('statistic/', statistic_page, name='statistic') path('statistic/', statistic_page, name='statistic')
] ]
urlpatterns += [ urlpatterns += [
path( path(
@ -47,7 +46,7 @@ urlpatterns += [
name='password_reset' name='password_reset'
), ),
path( path(
'password-reset/done/', 'password_reset/done/',
auth_views.PasswordResetDoneView.as_view(), auth_views.PasswordResetDoneView.as_view(),
name='password_reset_done' name='password_reset_done'
), ),

0
logs/.gitkeep Normal file
View File

View File

@ -94,12 +94,12 @@ class ZendeskAdmin:
def get_group(self, name: str) -> str: def get_group(self, name: str) -> str:
""" """
Функция возвращает группы, к которым принадлежит пользователь. Функция возвращает группу по названию
:param name: Имя пользователя :param name: Имя пользователя
:return: Группы пользователя (в случае отсутствия None) :return: Группы пользователя (в случае отсутствия None)
""" """
groups = self.admin.search(name) groups = self.admin.search(name, type='group')
for group in groups: for group in groups:
return group return group
return None return None

View File

@ -0,0 +1,15 @@
{% extends 'base/base.html' %}
{% load static %}
{% block title %}
Регистрация завершена
{% endblock %}
{% block heading %}
Регистрация
{% endblock %}
{% block content %}
<br>
<h4> Произошла ошибка при отправке электронного сообщения.</h4>
{% endblock %}

View File

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