Merge branch 'develop' into feature/adm_ruleset/backend
# Conflicts: # access_controller/settings.py # access_controller/urls.py # main/forms.py # main/views.py
This commit is contained in:
commit
918306aa48
@ -51,6 +51,15 @@ MIDDLEWARE = [
|
|||||||
|
|
||||||
ROOT_URLCONF = 'access_controller.urls'
|
ROOT_URLCONF = 'access_controller.urls'
|
||||||
|
|
||||||
|
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
|
||||||
|
EMAIL_HOST = 'smtp.mail.ru'
|
||||||
|
EMAIL_PORT = 2525
|
||||||
|
EMAIL_USE_TLS = True
|
||||||
|
EMAIL_HOST_USER = 'djgr.02@mail.ru'
|
||||||
|
EMAIL_HOST_PASSWORD = 'djangogroup02'
|
||||||
|
SERVER_EMAIL = EMAIL_HOST_USER
|
||||||
|
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
|
||||||
|
|
||||||
TEMPLATES = [
|
TEMPLATES = [
|
||||||
{
|
{
|
||||||
'BACKEND': 'django.template.backends.django.DjangoTemplates',
|
'BACKEND': 'django.template.backends.django.DjangoTemplates',
|
||||||
@ -119,15 +128,51 @@ STATIC_URL = '/static/'
|
|||||||
STATIC_ROOT = os.path.join(BASE_DIR, 'staticroot')
|
STATIC_ROOT = os.path.join(BASE_DIR, 'staticroot')
|
||||||
STATICFILES_DIRS = [
|
STATICFILES_DIRS = [
|
||||||
os.path.join(BASE_DIR, 'static'),
|
os.path.join(BASE_DIR, 'static'),
|
||||||
os.path.join(BASE_DIR, 'media'),
|
|
||||||
]
|
]
|
||||||
|
|
||||||
MEDIA_ROOT = BASE_DIR / 'media'
|
ACCOUNT_ACTIVATION_DAYS = 7
|
||||||
MEDIA_URL = '/media/'
|
|
||||||
|
|
||||||
LOGIN_REDIRECT_URL = '/'
|
LOGIN_REDIRECT_URL = '/'
|
||||||
LOGOUT_REDIRECT_URL = '/'
|
LOGOUT_REDIRECT_URL = '/'
|
||||||
|
|
||||||
|
# Logging system
|
||||||
|
# https://docs.djangoproject.com/en/3.1/topics/logging/
|
||||||
|
LOGGING = {
|
||||||
|
'version': 1,
|
||||||
|
'disable_existing_loggers': False,
|
||||||
|
'formatters': {
|
||||||
|
'verbose': {
|
||||||
|
'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}',
|
||||||
|
'style': '{',
|
||||||
|
},
|
||||||
|
'simple': {
|
||||||
|
'format': '{levelname} {message}',
|
||||||
|
'style': '{',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
'handlers': {
|
||||||
|
'console': {
|
||||||
|
'level': 'INFO',
|
||||||
|
'class': 'logging.StreamHandler',
|
||||||
|
'formatter': 'simple'
|
||||||
|
},
|
||||||
|
'mail_admins': {
|
||||||
|
'level': 'ERROR',
|
||||||
|
'class': 'django.utils.log.AdminEmailHandler',
|
||||||
|
}
|
||||||
|
},
|
||||||
|
'loggers': {
|
||||||
|
'django': {
|
||||||
|
'handlers': ['console'],
|
||||||
|
'propagate': True,
|
||||||
|
},
|
||||||
|
'main.index': {
|
||||||
|
'handlers': ['console'],
|
||||||
|
'level': 'INFO',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
ZENDESK_ROLES = {
|
ZENDESK_ROLES = {
|
||||||
'engineer': 360005209000,
|
'engineer': 360005209000,
|
||||||
'light_agent': 360005208980,
|
'light_agent': 360005208980,
|
||||||
|
@ -13,13 +13,10 @@ Including another URLconf
|
|||||||
1. Import the include() function: from django.urls import include, path
|
1. Import the include() function: from django.urls import include, path
|
||||||
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
|
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
|
||||||
"""
|
"""
|
||||||
from django.conf.urls.static import static
|
|
||||||
from django.contrib import admin
|
from django.contrib import admin
|
||||||
from django.contrib.auth.views import LoginView
|
from django.contrib.auth.views import LoginView
|
||||||
|
from django.contrib.auth import views as auth_views
|
||||||
from django.urls import path, include
|
from django.urls import path, include
|
||||||
|
|
||||||
from access_controller import settings
|
|
||||||
from access_controller.settings import DEBUG
|
|
||||||
from main.views import main_page, profile_page, CustomRegistrationView, AdminPageView
|
from main.views import main_page, profile_page, CustomRegistrationView, AdminPageView
|
||||||
|
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
@ -29,6 +26,30 @@ urlpatterns = [
|
|||||||
path('accounts/register/', CustomRegistrationView.as_view(), name='registration'),
|
path('accounts/register/', CustomRegistrationView.as_view(), name='registration'),
|
||||||
path('accounts/login/', LoginView.as_view(extra_context={}), name='login'), # TODO add extra context
|
path('accounts/login/', LoginView.as_view(extra_context={}), name='login'), # TODO add extra context
|
||||||
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.activation.urls')),
|
||||||
|
path('accounts/login/', include('django.contrib.auth.urls')),
|
||||||
path('control/', AdminPageView.as_view(), name='control')
|
path('control/', AdminPageView.as_view(), name='control')
|
||||||
|
]
|
||||||
|
|
||||||
|
urlpatterns += [
|
||||||
|
path(
|
||||||
|
'password_reset/',
|
||||||
|
auth_views.PasswordResetView.as_view(),
|
||||||
|
name='password_reset'
|
||||||
|
),
|
||||||
|
path(
|
||||||
|
'password-reset/done/',
|
||||||
|
auth_views.PasswordResetDoneView.as_view(),
|
||||||
|
name='password_reset_done'
|
||||||
|
),
|
||||||
|
path(
|
||||||
|
'reset/<uidb64>/<token>/',
|
||||||
|
auth_views.PasswordResetConfirmView.as_view(),
|
||||||
|
name='password_reset_confirm'
|
||||||
|
),
|
||||||
|
path(
|
||||||
|
'reset/done/',
|
||||||
|
auth_views.PasswordResetCompleteView.as_view(),
|
||||||
|
name='password_reset_complete'
|
||||||
|
),
|
||||||
]
|
]
|
||||||
|
@ -83,6 +83,13 @@ class ZendeskAdmin:
|
|||||||
user = self.admin.users.search(email).values[0]
|
user = self.admin.users.search(email).values[0]
|
||||||
return user.photo['content_url'] if user.photo else None
|
return user.photo['content_url'] if user.photo else None
|
||||||
|
|
||||||
|
def get_user(self, email: str) -> str:
|
||||||
|
return self.admin.users.search(email).values[0]
|
||||||
|
|
||||||
|
def get_user_org(self, email: str) -> str:
|
||||||
|
user = self.admin.users.search(email).values[0]
|
||||||
|
return user.organization.name
|
||||||
|
|
||||||
def create_admin(self) -> None:
|
def create_admin(self) -> None:
|
||||||
"""
|
"""
|
||||||
Функция **Create_admin()** создает администратора, проверяя наличие вводимых данных в env.
|
Функция **Create_admin()** создает администратора, проверяя наличие вводимых данных в env.
|
||||||
@ -141,9 +148,10 @@ def update_profile(user_profile: UserProfile):
|
|||||||
:param user_profile: Объект профиля пользователя
|
:param user_profile: Объект профиля пользователя
|
||||||
:type user_profile: :class:`main.models.UserProfile`
|
:type user_profile: :class:`main.models.UserProfile`
|
||||||
"""
|
"""
|
||||||
user_profile.name = ZendeskAdmin().get_user_name(user_profile.user.email)
|
user = ZendeskAdmin().get_user(user_profile.user.email)
|
||||||
user_profile.role = ZendeskAdmin().get_user_role(user_profile.user.email)
|
user_profile.name = user.name
|
||||||
user_profile.image = ZendeskAdmin().get_user_image(user_profile.user.email)
|
user_profile.role = user.role
|
||||||
|
user_profile.image = user.photo['content_url'] if user.photo else None
|
||||||
user_profile.save()
|
user_profile.save()
|
||||||
|
|
||||||
|
|
||||||
@ -159,6 +167,18 @@ def check_user_exist(email: str) -> bool:
|
|||||||
return ZendeskAdmin().check_user(email)
|
return ZendeskAdmin().check_user(email)
|
||||||
|
|
||||||
|
|
||||||
|
def get_user_organization(email: str) -> bool:
|
||||||
|
"""
|
||||||
|
Функция возвращает организацию пользователя
|
||||||
|
|
||||||
|
:param email: Электронная почта пользователя
|
||||||
|
:type email: :class:`str`
|
||||||
|
:return: Название организации
|
||||||
|
:rtype: :class:`str`
|
||||||
|
"""
|
||||||
|
return ZendeskAdmin().get_user_org(email)
|
||||||
|
|
||||||
|
|
||||||
def check_user_auth(email: str, password: str) -> bool:
|
def check_user_auth(email: str, password: str) -> bool:
|
||||||
"""
|
"""
|
||||||
Функция проверяет, верны ли входные данные
|
Функция проверяет, верны ли входные данные
|
||||||
|
@ -7,33 +7,25 @@ from main.models import UserProfile
|
|||||||
class CustomRegistrationForm(RegistrationFormUniqueEmail):
|
class CustomRegistrationForm(RegistrationFormUniqueEmail):
|
||||||
"""
|
"""
|
||||||
Форма для регистрации :class:`django_registration.forms.RegistrationFormUniqueEmail`
|
Форма для регистрации :class:`django_registration.forms.RegistrationFormUniqueEmail`
|
||||||
с полем для ввода пароля от Zendesk аккаунта и с добавлением bootstrap-класса 'form-control' для всех полей
|
с добавлением bootstrap-класса 'form-control'
|
||||||
|
|
||||||
:param password_zen: Поле для ввода пароля от Zendesk
|
:param password_zen: Поле для ввода пароля от Zendesk
|
||||||
:type password_zen: :class:`django.forms.CharField`
|
:type password_zen: :class:`django.forms.CharField`
|
||||||
"""
|
"""
|
||||||
password_zen = forms.CharField(
|
|
||||||
required=True,
|
|
||||||
label="Пароль от Zendesk аккаунта",
|
|
||||||
strip=False,
|
|
||||||
widget=forms.PasswordInput(attrs={
|
|
||||||
'class': 'form-control'
|
|
||||||
})
|
|
||||||
)
|
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
super().__init__(*args, **kwargs)
|
super().__init__(*args, **kwargs)
|
||||||
for visible in self.visible_fields():
|
for visible in self.visible_fields():
|
||||||
if visible.field.widget.attrs.get('class', False):
|
if visible.field.widget.attrs.get('class', False):
|
||||||
print(visible.field.widget.attrs['class'].find('form-control'))
|
|
||||||
if visible.field.widget.attrs['class'].find('form-control') < 0:
|
if visible.field.widget.attrs['class'].find('form-control') < 0:
|
||||||
visible.field.widget.attrs['class'] += 'form-control'
|
visible.field.widget.attrs['class'] += 'form-control'
|
||||||
else:
|
else:
|
||||||
visible.field.widget.attrs['class'] = 'form-control'
|
visible.field.widget.attrs['class'] = 'form-control'
|
||||||
|
if visible.html_name !='email':
|
||||||
|
visible.field.required = False
|
||||||
|
|
||||||
class Meta(RegistrationFormUniqueEmail.Meta):
|
class Meta(RegistrationFormUniqueEmail.Meta):
|
||||||
fields = RegistrationFormUniqueEmail.Meta.fields
|
fields = RegistrationFormUniqueEmail.Meta.fields
|
||||||
fields.insert(2, 'password_zen')
|
|
||||||
|
|
||||||
|
|
||||||
class AdminPageUsers(forms.Form):
|
class AdminPageUsers(forms.Form):
|
||||||
|
@ -11,5 +11,5 @@
|
|||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<br>
|
<br>
|
||||||
<h4> Нет пользователя с указаным адресом электронной почты, либо был введён неверный пароль</h4>
|
<h4> Нет пользователя с указаным адресом электронной почты.</h4>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
@ -11,14 +11,12 @@
|
|||||||
{% block content %}
|
{% block content %}
|
||||||
<form method="post" action="">
|
<form method="post" action="">
|
||||||
{% csrf_token %}
|
{% csrf_token %}
|
||||||
{% for field in form %}
|
{{ form.email.label_tag }}
|
||||||
{{ field.label_tag }}
|
{{ form.email }}
|
||||||
{{ field }}
|
|
||||||
<br>
|
<br>
|
||||||
{% if field.errors %}
|
{% if form.email.errors %}
|
||||||
<span>{{ field.errors }}</span>
|
<span>{{ form.email.errors }}</span>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{% endfor %}
|
|
||||||
<input type="submit" value="Зарегистрироваться" class="clearfix">
|
<input type="submit" value="Зарегистрироваться" class="clearfix">
|
||||||
</form>
|
</form>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
@ -31,7 +31,7 @@
|
|||||||
{% endif %}
|
{% endif %}
|
||||||
<div class="text-center">
|
<div class="text-center">
|
||||||
<button type="submit" class="btn btn-primary">Войти</button>
|
<button type="submit" class="btn btn-primary">Войти</button>
|
||||||
<a href="" class="btn btn-link" style="display: block;">Забыли пароль?</a>
|
<a href="password_reset" class="btn btn-link" style="display: block;">Забыли пароль?</a>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
13
main/templates/registration/password_reset_complete.html
Normal file
13
main/templates/registration/password_reset_complete.html
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
{% extends "base/base.html" %}
|
||||||
|
|
||||||
|
{% block title %}
|
||||||
|
{{ pagename }}
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block heading %}
|
||||||
|
Восстановление пароля
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<p>Ваш новый пароль был установлен. Вы можете <a href="{% url 'login' %}">войти</a> сейчас</p>
|
||||||
|
{% endblock %}
|
23
main/templates/registration/password_reset_confirm.html
Normal file
23
main/templates/registration/password_reset_confirm.html
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
{% extends "base/base.html" %}
|
||||||
|
|
||||||
|
{% block title %}
|
||||||
|
{{ pagename }}
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block heading %}
|
||||||
|
Восстановление пароля
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
{% if validlink %}
|
||||||
|
<p>Пожалуйста, введите пароль дважды:</p>
|
||||||
|
<form action="." method="post">
|
||||||
|
{{ form.as_p }}
|
||||||
|
{% csrf_token %}
|
||||||
|
<p><input class="btn btn-success" type="submit" value="Сменить пароль"/></p>
|
||||||
|
</form>
|
||||||
|
{% else %}
|
||||||
|
<p>Неверная ссылка восстановления пароля, возможно она уже была использована.
|
||||||
|
Пожалуйста, запросите новый сброс пароля</p>
|
||||||
|
{% endif %}
|
||||||
|
{% endblock %}
|
14
main/templates/registration/password_reset_done.html
Normal file
14
main/templates/registration/password_reset_done.html
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
{% extends "base/base.html" %}
|
||||||
|
|
||||||
|
{% block title %}
|
||||||
|
{{ pagename }}
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block heading %}
|
||||||
|
Восстановление пароля
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<p>Мы отправили вам на почту инструкцию по восстановлению</p>
|
||||||
|
<p>Если вы не получили сообщение, убедитесь что верно ввели адрес электронной почты.</p>
|
||||||
|
{% endblock %}
|
18
main/templates/registration/password_reset_form.html
Normal file
18
main/templates/registration/password_reset_form.html
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
{% extends "base/base.html" %}
|
||||||
|
|
||||||
|
{% block title %}
|
||||||
|
{{ pagename }}
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block heading %}
|
||||||
|
Забыли пароль?
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<p>Введте свой e-mail адрес для восстановления пароля.</p>
|
||||||
|
<form action="." method="post">
|
||||||
|
{{ form.as_p }}
|
||||||
|
<p><input class="btn btn-success" type="submit" value="Отпрваить e-mail"></p>
|
||||||
|
{% csrf_token %}
|
||||||
|
</form>
|
||||||
|
{% endblock %}
|
@ -1,19 +1,25 @@
|
|||||||
from django.core.exceptions import PermissionDenied
|
from django.contrib.auth.decorators import login_required
|
||||||
|
from django.contrib.auth.forms import PasswordResetForm
|
||||||
|
from django.contrib.auth.models import User
|
||||||
|
from django.contrib.auth.tokens import default_token_generator
|
||||||
from django.shortcuts import render, get_list_or_404
|
from django.shortcuts import render, get_list_or_404
|
||||||
from django.urls import reverse_lazy
|
from django.urls import reverse_lazy
|
||||||
|
from django_registration.backends.one_step.views import RegistrationView
|
||||||
|
|
||||||
from main.extra_func import check_user_exist, check_user_auth, update_profile, \
|
from access_controller.settings import EMAIL_HOST_USER
|
||||||
|
from main.extra_func import check_user_exist, update_profile, get_user_organization, \
|
||||||
make_engineer, make_light_agent, get_users_list
|
make_engineer, make_light_agent, get_users_list
|
||||||
from main.models import UserProfile
|
|
||||||
|
|
||||||
from django.contrib.auth.models import User
|
from django.contrib.auth.models import User
|
||||||
|
from main.models import UserProfile
|
||||||
from main.forms import CustomRegistrationForm, AdminPageUsers
|
from main.forms import CustomRegistrationForm, AdminPageUsers
|
||||||
from django_registration.views import RegistrationView, FormView
|
from django_registration.views import RegistrationView
|
||||||
|
|
||||||
from django.contrib.auth.decorators import login_required
|
from django.contrib.auth.decorators import login_required
|
||||||
from django.contrib.auth.mixins import LoginRequiredMixin
|
from django.contrib.auth.mixins import LoginRequiredMixin
|
||||||
|
from django.core.exceptions import PermissionDenied
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
from zenpy import Zenpy
|
|
||||||
from access_controller.settings import ZENDESK_ROLES
|
from access_controller.settings import ZENDESK_ROLES
|
||||||
|
|
||||||
|
|
||||||
@ -28,14 +34,29 @@ class CustomRegistrationView(RegistrationView):
|
|||||||
|
|
||||||
def register(self, form):
|
def register(self, form):
|
||||||
self.is_allowed = True
|
self.is_allowed = True
|
||||||
if check_user_exist(form.data['email']) and check_user_auth(form.data['email'], form.data['password_zen']):
|
if check_user_exist(form.data['email']) and get_user_organization(form.data['email']) == 'SYSTEM':
|
||||||
user = User.objects.create_user(
|
forms = PasswordResetForm(self.request.POST)
|
||||||
username=form.data['username'],
|
if forms.is_valid():
|
||||||
email=form.data['email'],
|
opts = {
|
||||||
password=form.data['password1']
|
'use_https': self.request.is_secure(),
|
||||||
)
|
'token_generator': default_token_generator,
|
||||||
profile = user.userprofile
|
'from_email': EMAIL_HOST_USER,
|
||||||
update_profile(profile)
|
'email_template_name': 'registration/password_reset_email.html',
|
||||||
|
'subject_template_name': 'registration/password_reset_subject.txt',
|
||||||
|
'request': self.request,
|
||||||
|
'html_email_template_name': None,
|
||||||
|
'extra_email_context': None,
|
||||||
|
}
|
||||||
|
user = User.objects.create_user(
|
||||||
|
username=form.data['email'],
|
||||||
|
email=form.data['email'],
|
||||||
|
password=User.objects.make_random_password(length=50)
|
||||||
|
)
|
||||||
|
forms.save(**opts)
|
||||||
|
update_profile(user.userprofile)
|
||||||
|
return user
|
||||||
|
else:
|
||||||
|
raise ValueError('Непредвиденная ошибка')
|
||||||
else:
|
else:
|
||||||
self.is_allowed = False
|
self.is_allowed = False
|
||||||
|
|
||||||
@ -45,7 +66,7 @@ class CustomRegistrationView(RegistrationView):
|
|||||||
Используется самой django-registration
|
Используется самой django-registration
|
||||||
"""
|
"""
|
||||||
if self.is_allowed:
|
if self.is_allowed:
|
||||||
return reverse_lazy('django_registration_complete')
|
return reverse_lazy('password_reset_done')
|
||||||
else:
|
else:
|
||||||
return reverse_lazy('django_registration_disallowed')
|
return reverse_lazy('django_registration_disallowed')
|
||||||
|
|
||||||
@ -73,6 +94,8 @@ def profile_page(request):
|
|||||||
|
|
||||||
|
|
||||||
def main_page(request):
|
def main_page(request):
|
||||||
|
logger = logging.getLogger('main.index')
|
||||||
|
logger.info('Index page opened')
|
||||||
return render(request, 'pages/index.html')
|
return render(request, 'pages/index.html')
|
||||||
|
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user