Merge branch 'feature/registration' into 'develop'
Feature/registration See merge request 2020-2021/online/s101/group-02/access_controller!26
This commit is contained in:
commit
b84824f888
19
access_controller/auth.py
Normal file
19
access_controller/auth.py
Normal file
@ -0,0 +1,19 @@
|
||||
from django.contrib.auth.backends import ModelBackend
|
||||
from django.contrib.auth.models import User
|
||||
|
||||
|
||||
class EmailAuthBackend(ModelBackend):
|
||||
def authenticate(self, request, username=None, password=None, **kwargs):
|
||||
try:
|
||||
user = User.objects.get(email=username)
|
||||
if user.check_password(password):
|
||||
return user
|
||||
return None
|
||||
except User.DoesNotExist:
|
||||
return None
|
||||
|
||||
def get_user(self, user_id):
|
||||
try:
|
||||
return User.objects.get(pk=user_id)
|
||||
except User.DoesNotExist:
|
||||
return None
|
@ -135,6 +135,12 @@ ACCOUNT_ACTIVATION_DAYS = 7
|
||||
LOGIN_REDIRECT_URL = '/'
|
||||
LOGOUT_REDIRECT_URL = '/'
|
||||
|
||||
|
||||
# Название_приложения.Название_файла.Название_класса_обработчика
|
||||
AUTHENTICATION_BACKENDS = [
|
||||
'access_controller.auth.EmailAuthBackend',
|
||||
]
|
||||
|
||||
# Logging system
|
||||
# https://docs.djangoproject.com/en/3.1/topics/logging/
|
||||
LOGGING = {
|
||||
|
@ -14,6 +14,7 @@ Including another URLconf
|
||||
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
|
||||
"""
|
||||
from django.contrib import admin
|
||||
from django.contrib.auth.forms import AuthenticationForm
|
||||
from django.contrib.auth.views import LoginView
|
||||
from django.contrib.auth import views as auth_views
|
||||
from django.urls import path, include
|
||||
@ -21,13 +22,14 @@ from access_controller import settings
|
||||
from access_controller.settings import DEBUG
|
||||
from main.views import main_page, profile_page, CustomRegistrationView, work_page, work_hand_over, work_become_engineer, AdminPageView
|
||||
|
||||
from main.views import main_page, profile_page, CustomRegistrationView, CustomLoginView
|
||||
|
||||
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/login/', LoginView.as_view(extra_context={}), name='login'), # TODO add extra context
|
||||
path('accounts/login/', CustomLoginView.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('work/<int:id>', work_page, name="work"),
|
||||
@ -59,5 +61,4 @@ urlpatterns += [
|
||||
auth_views.PasswordResetCompleteView.as_view(),
|
||||
name='password_reset_complete'
|
||||
),
|
||||
|
||||
]
|
||||
|
@ -20,7 +20,6 @@ class ZendeskAdmin:
|
||||
:type token: :class:`str`
|
||||
:param password: Пароль администратора, указанный в env
|
||||
:type password: :class:`str`
|
||||
|
||||
"""
|
||||
|
||||
credentials: dict = {
|
||||
@ -29,6 +28,12 @@ class ZendeskAdmin:
|
||||
email: str = os.getenv('ACCESS_CONTROLLER_API_EMAIL')
|
||||
token: str = os.getenv('ACCESS_CONTROLLER_API_TOKEN')
|
||||
password: str = os.getenv('ACCESS_CONTROLLER_API_PASSWORD')
|
||||
_instance=None
|
||||
|
||||
def __new__(cls, *args, **kwargs):
|
||||
if cls._instance is None:
|
||||
cls._instance = super().__new__(cls)
|
||||
return cls._instance
|
||||
|
||||
def __init__(self):
|
||||
self.create_admin()
|
||||
@ -62,7 +67,7 @@ class ZendeskAdmin:
|
||||
|
||||
def get_user_image(self, email: str) -> str:
|
||||
"""
|
||||
Функция **get_user_image** возвращает аватар пользователя по его email
|
||||
Функция **get_user_image** возвращает url-ссылку на аватар пользователя по его email
|
||||
"""
|
||||
user = self.admin.users.search(email).values[0]
|
||||
return user.photo['content_url'] if user.photo else None
|
||||
@ -78,7 +83,7 @@ class ZendeskAdmin:
|
||||
Функция **get_user_org** возвращает организацию, к которой относится пользователь по его email
|
||||
"""
|
||||
user = self.admin.users.search(email).values[0]
|
||||
return user.organization
|
||||
return user.organization.name
|
||||
|
||||
def create_admin(self) -> Zenpy:
|
||||
"""
|
||||
|
@ -1,4 +1,5 @@
|
||||
from django import forms
|
||||
from django.contrib.auth.forms import AuthenticationForm
|
||||
from django_registration.forms import RegistrationFormUniqueEmail
|
||||
|
||||
from main.models import UserProfile
|
||||
@ -6,13 +7,9 @@ from main.models import UserProfile
|
||||
|
||||
class CustomRegistrationForm(RegistrationFormUniqueEmail):
|
||||
"""
|
||||
Форма для регистрации :class:`django_registration.forms.RegistrationFormUniqueEmail`
|
||||
с добавлением bootstrap-класса 'form-control'
|
||||
|
||||
:param password_zen: Поле для ввода пароля от Zendesk
|
||||
:type password_zen: :class:`django.forms.CharField`
|
||||
Форма для регистрации :class:`django_registration.forms.RegistrationFormUniqueEmail`
|
||||
с добавлением bootstrap-класса 'form-control'
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
for visible in self.visible_fields():
|
||||
@ -31,9 +28,6 @@ class CustomRegistrationForm(RegistrationFormUniqueEmail):
|
||||
class AdminPageUsers(forms.Form):
|
||||
"""
|
||||
Форма для установки статуса
|
||||
|
||||
:param password_zen: Поле для ввода пароля от Zendesk
|
||||
:type password_zen: :class:`django.forms.CharField`
|
||||
"""
|
||||
|
||||
users = forms.ModelMultipleChoiceField(
|
||||
@ -45,3 +39,21 @@ class AdminPageUsers(forms.Form):
|
||||
),
|
||||
label=''
|
||||
)
|
||||
|
||||
|
||||
class CustomAuthenticationForm(AuthenticationForm):
|
||||
"""
|
||||
Форма для авторизации :class:`django.contrib.auth.forms.AuthenticationForm`
|
||||
с изменением поля username на email
|
||||
"""
|
||||
username = forms.CharField(
|
||||
label="Электронная почта",
|
||||
widget=forms.EmailInput(),
|
||||
)
|
||||
error_messages = {
|
||||
'invalid_login':
|
||||
"Пожалуйста, введите правильные электронную почту и пароль. Оба поля "
|
||||
"могут быть чувствительны к регистру."
|
||||
,
|
||||
'inactive': "Аккаунт не активен.",
|
||||
}
|
||||
|
@ -1,36 +1,27 @@
|
||||
from django.shortcuts import render, redirect, reverse
|
||||
from django.http import HttpResponseRedirect
|
||||
import logging
|
||||
import os
|
||||
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.contrib.auth.forms import PasswordResetForm
|
||||
from django.contrib.auth.mixins import LoginRequiredMixin
|
||||
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.contrib.auth.views import LoginView
|
||||
from django.core.exceptions import PermissionDenied
|
||||
from django.http import HttpResponseRedirect
|
||||
from django.shortcuts import get_list_or_404, redirect, reverse, render
|
||||
from django.urls import reverse_lazy
|
||||
from django.views.generic import FormView
|
||||
from django_registration.backends.one_step.views import RegistrationView
|
||||
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
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
from main.models import UserProfile
|
||||
from main.forms import CustomRegistrationForm, AdminPageUsers
|
||||
from django_registration.views import RegistrationView
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.contrib.auth.mixins import LoginRequiredMixin
|
||||
from django.core.exceptions import PermissionDenied
|
||||
|
||||
import logging
|
||||
|
||||
from zenpy import Zenpy
|
||||
from zenpy.lib.api_objects import User as ZenpyUser
|
||||
|
||||
from access_controller.settings import EMAIL_HOST_USER, ZENDESK_ROLES
|
||||
from main.extra_func import check_user_exist, update_profile, get_user_organization, make_engineer, make_light_agent, \
|
||||
get_users_list
|
||||
from main.forms import AdminPageUsers, CustomRegistrationForm, CustomAuthenticationForm
|
||||
from .models import UserProfile
|
||||
|
||||
import os
|
||||
from access_controller.settings import ZENDESK_ROLES
|
||||
|
||||
|
||||
class CustomRegistrationView(RegistrationView):
|
||||
"""
|
||||
@ -192,3 +183,10 @@ class AdminPageView(FormView, LoginRequiredMixin):
|
||||
UserProfile, role='agent')
|
||||
context['engineers'], context['light_agents'] = self.count_users(get_users_list())
|
||||
return context # TODO: need to get profile page url
|
||||
|
||||
|
||||
class CustomLoginView(LoginView):
|
||||
"""
|
||||
Отображение страницы авторизации пользователя
|
||||
"""
|
||||
form_class = CustomAuthenticationForm
|
||||
|
Loading…
x
Reference in New Issue
Block a user