merge registration branch
This commit is contained in:
commit
b0932c94b6
@ -51,6 +51,15 @@ MIDDLEWARE = [
|
||||
|
||||
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 = [
|
||||
{
|
||||
'BACKEND': 'django.template.backends.django.DjangoTemplates',
|
||||
@ -119,11 +128,9 @@ STATIC_URL = '/static/'
|
||||
STATIC_ROOT = os.path.join(BASE_DIR, 'staticroot')
|
||||
STATICFILES_DIRS = [
|
||||
os.path.join(BASE_DIR, 'static'),
|
||||
os.path.join(BASE_DIR, 'media'),
|
||||
]
|
||||
|
||||
MEDIA_ROOT = BASE_DIR / 'media'
|
||||
MEDIA_URL = '/media/'
|
||||
ACCOUNT_ACTIVATION_DAYS = 7
|
||||
|
||||
LOGIN_REDIRECT_URL = '/'
|
||||
LOGOUT_REDIRECT_URL = '/'
|
||||
|
@ -13,13 +13,10 @@ Including another URLconf
|
||||
1. Import the include() function: from django.urls import include, path
|
||||
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.auth.views import LoginView
|
||||
from django.contrib.auth import views as auth_views
|
||||
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
|
||||
|
||||
urlpatterns = [
|
||||
@ -29,5 +26,28 @@ urlpatterns = [
|
||||
path('accounts/register/', CustomRegistrationView.as_view(), name='registration'),
|
||||
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_registration.backends.one_step.urls')),
|
||||
path('accounts/', include('django_registration.backends.activation.urls')),
|
||||
]
|
||||
|
||||
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'
|
||||
),
|
||||
]
|
||||
|
@ -81,6 +81,13 @@ class ZendeskAdmin:
|
||||
user = self.admin.users.search(email).values[0]
|
||||
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:
|
||||
"""
|
||||
Функция **Create_admin()** создает администратора, проверяя наличие вводимых данных в env.
|
||||
@ -114,9 +121,10 @@ def update_profile(user_profile: UserProfile):
|
||||
:param user_profile: Объект профиля пользователя
|
||||
:type user_profile: :class:`main.models.UserProfile`
|
||||
"""
|
||||
user_profile.name = ZendeskAdmin().get_user_name(user_profile.user.email)
|
||||
user_profile.role = ZendeskAdmin().get_user_role(user_profile.user.email)
|
||||
user_profile.image = ZendeskAdmin().get_user_image(user_profile.user.email)
|
||||
user = ZendeskAdmin().get_user(user_profile.user.email)
|
||||
user_profile.name = user.name
|
||||
user_profile.role = user.role
|
||||
user_profile.image = user.photo['content_url'] if user.photo else None
|
||||
user_profile.save()
|
||||
|
||||
|
||||
@ -132,6 +140,18 @@ def check_user_exist(email: str) -> bool:
|
||||
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:
|
||||
"""
|
||||
Функция проверяет, верны ли входные данные
|
||||
@ -145,10 +165,10 @@ def check_user_auth(email: str, password: str) -> bool:
|
||||
:rtype: :class:`bool`
|
||||
"""
|
||||
creds = {
|
||||
'email': email,
|
||||
'password': password,
|
||||
'subdomain': 'ngenix1612197338',
|
||||
}
|
||||
'email': email,
|
||||
'password': password,
|
||||
'subdomain': 'ngenix1612197338',
|
||||
}
|
||||
try:
|
||||
user = Zenpy(**creds)
|
||||
user.search(email, type='user')
|
||||
|
@ -5,30 +5,22 @@ from django_registration.forms import RegistrationFormUniqueEmail
|
||||
class CustomRegistrationForm(RegistrationFormUniqueEmail):
|
||||
"""
|
||||
Форма для регистрации :class:`django_registration.forms.RegistrationFormUniqueEmail`
|
||||
с полем для ввода пароля от Zendesk аккаунта и с добавлением bootstrap-класса 'form-control' для всех полей
|
||||
с добавлением bootstrap-класса 'form-control'
|
||||
|
||||
:param password_zen: Поле для ввода пароля от Zendesk
|
||||
: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):
|
||||
super().__init__(*args, **kwargs)
|
||||
for visible in self.visible_fields():
|
||||
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:
|
||||
visible.field.widget.attrs['class'] += 'form-control'
|
||||
else:
|
||||
visible.field.widget.attrs['class'] = 'form-control'
|
||||
if visible.html_name !='email':
|
||||
visible.field.required = False
|
||||
|
||||
class Meta(RegistrationFormUniqueEmail.Meta):
|
||||
fields = RegistrationFormUniqueEmail.Meta.fields
|
||||
fields.insert(2, 'password_zen')
|
||||
|
@ -11,5 +11,5 @@
|
||||
|
||||
{% block content %}
|
||||
<br>
|
||||
<h4> Нет пользователя с указаным адресом электронной почты, либо был введён неверный пароль</h4>
|
||||
<h4> Нет пользователя с указаным адресом электронной почты.</h4>
|
||||
{% endblock %}
|
||||
|
@ -11,14 +11,12 @@
|
||||
{% block content %}
|
||||
<form method="post" action="">
|
||||
{% csrf_token %}
|
||||
{% for field in form %}
|
||||
{{ field.label_tag }}
|
||||
{{ field }}
|
||||
{{ form.email.label_tag }}
|
||||
{{ form.email }}
|
||||
<br>
|
||||
{% if field.errors %}
|
||||
<span>{{ field.errors }}</span>
|
||||
{% if form.email.errors %}
|
||||
<span>{{ form.email.errors }}</span>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
<input type="submit" value="Зарегистрироваться" class="clearfix">
|
||||
</form>
|
||||
{% endblock %}
|
||||
|
@ -31,7 +31,7 @@
|
||||
{% endif %}
|
||||
<div class="text-center">
|
||||
<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>
|
||||
</form>
|
||||
</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,18 +1,20 @@
|
||||
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
|
||||
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 main.models import UserProfile
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
from access_controller.settings import EMAIL_HOST_USER
|
||||
from main.extra_func import check_user_exist, update_profile, get_user_organization
|
||||
from main.forms import CustomRegistrationForm
|
||||
from django_registration.views import RegistrationView
|
||||
|
||||
from django.contrib.auth.decorators import login_required
|
||||
|
||||
import logging
|
||||
|
||||
|
||||
|
||||
class CustomRegistrationView(RegistrationView):
|
||||
"""
|
||||
Отображение и логика работы страницы регистрации пользователя
|
||||
@ -24,14 +26,29 @@ class CustomRegistrationView(RegistrationView):
|
||||
|
||||
def register(self, form):
|
||||
self.is_allowed = True
|
||||
if check_user_exist(form.data['email']) and check_user_auth(form.data['email'], form.data['password_zen']):
|
||||
user = User.objects.create_user(
|
||||
username=form.data['username'],
|
||||
email=form.data['email'],
|
||||
password=form.data['password1']
|
||||
)
|
||||
profile = user.userprofile
|
||||
update_profile(profile)
|
||||
if check_user_exist(form.data['email']) and get_user_organization(form.data['email']) == 'SYSTEM':
|
||||
forms = PasswordResetForm(self.request.POST)
|
||||
if forms.is_valid():
|
||||
opts = {
|
||||
'use_https': self.request.is_secure(),
|
||||
'token_generator': default_token_generator,
|
||||
'from_email': EMAIL_HOST_USER,
|
||||
'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:
|
||||
self.is_allowed = False
|
||||
|
||||
@ -41,7 +58,7 @@ class CustomRegistrationView(RegistrationView):
|
||||
Используется самой django-registration
|
||||
"""
|
||||
if self.is_allowed:
|
||||
return reverse_lazy('django_registration_complete')
|
||||
return reverse_lazy('password_reset_done')
|
||||
else:
|
||||
return reverse_lazy('django_registration_disallowed')
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user