diff --git a/access_controller/settings.py b/access_controller/settings.py index eecfa19..152b5b0 100644 --- a/access_controller/settings.py +++ b/access_controller/settings.py @@ -35,6 +35,7 @@ INSTALLED_APPS = [ 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', + 'django_cleanup.apps.CleanupConfig', 'django_registration', 'main', ] @@ -51,6 +52,17 @@ 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 = 'dj-gr-2@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 +131,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 = '/' diff --git a/access_controller/urls.py b/access_controller/urls.py index b2603b2..edd173e 100644 --- a/access_controller/urls.py +++ b/access_controller/urls.py @@ -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///', + auth_views.PasswordResetConfirmView.as_view(), + name='password_reset_confirm' + ), + path( + 'reset/done/', + auth_views.PasswordResetCompleteView.as_view(), + name='password_reset_complete' + ), ] diff --git a/main/extra_func.py b/main/extra_func.py index 73c533b..b3d194a 100644 --- a/main/extra_func.py +++ b/main/extra_func.py @@ -34,6 +34,11 @@ class ZendeskAdmin: user = self.admin.users.search(email).values[0] return user.id + def get_user_org(self, email: str) -> str: + user = self.admin.users.search(email).values[0] + print(user) + return user.organization + def get_user_image(self, email: str) -> str: user = self.admin.users.search(email).values[0] return user.photo['content_url'] if user.photo else None @@ -81,6 +86,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: """ Функция проверяет, верны ли входные данные @@ -94,10 +111,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') diff --git a/main/forms.py b/main/forms.py index fcd8a7f..6a058bb 100644 --- a/main/forms.py +++ b/main/forms.py @@ -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') diff --git a/main/templates/django_registration/registration_form.html b/main/templates/django_registration/registration_form.html index c4bb388..61b69b0 100644 --- a/main/templates/django_registration/registration_form.html +++ b/main/templates/django_registration/registration_form.html @@ -11,14 +11,12 @@ {% block content %}
{% csrf_token %} - {% for field in form %} - {{ field.label_tag }} - {{ field }} + {{ form.email.label_tag }} + {{ form.email }}
- {% if field.errors %} - {{ field.errors }} + {% if form.email.errors %} + {{ form.email.errors }} {% endif %} - {% endfor %}
{% endblock %} diff --git a/main/templates/registration/password_reset_complete.html b/main/templates/registration/password_reset_complete.html new file mode 100644 index 0000000..8381ada --- /dev/null +++ b/main/templates/registration/password_reset_complete.html @@ -0,0 +1,13 @@ +{% extends "base/base.html" %} + +{% block title %} + {{ pagename }} +{% endblock %} + +{% block heading %} + Восстановление пароля +{% endblock %} + +{% block content %} +

Ваш новый пароль был установлен. Вы можете войти сейчас

+{% endblock %} diff --git a/main/templates/registration/password_reset_confirm.html b/main/templates/registration/password_reset_confirm.html new file mode 100644 index 0000000..df40ed2 --- /dev/null +++ b/main/templates/registration/password_reset_confirm.html @@ -0,0 +1,23 @@ +{% extends "base/base.html" %} + +{% block title %} + {{ pagename }} +{% endblock %} + +{% block heading %} + Восстановление пароля +{% endblock %} + +{% block content %} + {% if validlink %} +

Пожалуйста, введите пароль дважды:

+
+ {{ form.as_p }} + {% csrf_token %} +

+
+ {% else %} +

Неверная ссылка восстановления пароля, возможно она уже была использована. + Пожалуйста, запросите новый сброс пароля

+ {% endif %} +{% endblock %} diff --git a/main/templates/registration/password_reset_done.html b/main/templates/registration/password_reset_done.html new file mode 100644 index 0000000..0103509 --- /dev/null +++ b/main/templates/registration/password_reset_done.html @@ -0,0 +1,14 @@ +{% extends "base/base.html" %} + +{% block title %} + {{ pagename }} +{% endblock %} + +{% block heading %} + Восстановление пароля +{% endblock %} + +{% block content %} +

Мы отправили вам на почту инструкцию по восстановлению

+

Если вы не получили сообщение, убедитесь что верно ввели адрес электронной почты.

+{% endblock %} diff --git a/main/templates/registration/password_reset_email.html b/main/templates/registration/password_reset_email.html new file mode 100644 index 0000000..8c0a2d2 --- /dev/null +++ b/main/templates/registration/password_reset_email.html @@ -0,0 +1,3 @@ +Someone asked for password reset for email {{ email }}. Follow thelink below: +{{ protocol }}://{{ domain }}{% url "password_reset_confirm" uidb64=uid token=token %} +Your username, in case you've forgotten: {{ user.get_username }} diff --git a/main/templates/registration/password_reset_form.html b/main/templates/registration/password_reset_form.html new file mode 100644 index 0000000..39cf045 --- /dev/null +++ b/main/templates/registration/password_reset_form.html @@ -0,0 +1,18 @@ +{% extends "base/base.html" %} + +{% block title %} + {{ pagename }} +{% endblock %} + +{% block heading %} + Забыли пароль? +{% endblock %} + +{% block content %} +

Введте свой e-mail адрес для восстановления пароля.

+
+ {{ form.as_p }} +

+ {% csrf_token %} +
+{% endblock %} diff --git a/main/views.py b/main/views.py index 797ea8b..92bedb6 100644 --- a/main/views.py +++ b/main/views.py @@ -1,17 +1,15 @@ +from django.contrib.auth.views import PasswordResetView 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.extra_func import check_user_exist, check_user_auth, update_profile, get_user_organization from main.models import UserProfile from django.contrib.auth.models import User from main.forms import CustomRegistrationForm -from django_registration.views import RegistrationView - from django.contrib.auth.decorators import login_required -from zenpy import Zenpy - class CustomRegistrationView(RegistrationView): """ @@ -24,14 +22,16 @@ 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']): + if get_user_organization(form.data['email'])=='SYSTEM' and check_user_exist(form.data['email']) : user = User.objects.create_user( - username=form.data['username'], + username=form.data['email'], email=form.data['email'], - password=form.data['password1'] ) + PasswordResetView.as_view()(self.request) + user.is_active = False + user.save() profile = user.userprofile - update_profile(profile) + return user else: self.is_allowed = False @@ -41,7 +41,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')