diff --git a/main/extra_func.py b/main/extra_func.py index 305e897..73c533b 100644 --- a/main/extra_func.py +++ b/main/extra_func.py @@ -7,55 +7,66 @@ from main.models import UserProfile # Дополнительные функции -def set_and_get_name(user_profile: UserProfile): +class ZendeskAdmin: + # Класс существует, чтобы в каждой фунциии отдельно не проверять аккаунт администратора + credentials = { + 'subdomain': 'ngenix1612197338' + } + email = os.getenv('ACCESS_CONTROLLER_API_EMAIL') + token = os.getenv('ACCESS_CONTROLLER_API_TOKEN') + password = os.getenv('ACCESS_CONTROLLER_API_PASSWORD') + + def __init__(self): + self.create_admin() + + def check_user(self, email: str) -> bool: + return True if self.admin.search(email, type='user') else False + + def get_user_name(self, email: str) -> str: + user = self.admin.users.search(email).values[0] + return user.name + + def get_user_role(self, email: str) -> str: + user = self.admin.users.search(email).values[0] + return user.role + + def get_user_id(self, email: str) -> str: + user = self.admin.users.search(email).values[0] + return user.id + + 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 + + def create_admin(self) -> None: + if self.email is None: + raise ValueError('access_controller email not in env') + self.credentials['email'] = os.getenv('ACCESS_CONTROLLER_API_EMAIL') + + if self.token: + self.credentials['token'] = self.token + elif self.password: + self.credentials['password'] = self.password + else: + raise ValueError('access_controller token or password not in env') + self.admin = Zenpy(**self.credentials) + try: + self.admin.search(self.email, type='user') + except APIException: + raise ValueError('invalid access_controller`s login data') + + +def update_profile(user_profile: UserProfile): """ - Функция устанавливает поле :class:`username` текущим именем в Zendesk + Функция обновляет профиль пользователя в соотвтетствии с текущим в Zendesk - .. TODO:: - Переделать с получением данных через API - - :param UP: Объект профиля пользователя - :type UP: :class:`main.models.UserProfile` - :return: Имя пользователя - :rtype: :class:`str` + :param user_profile: Объект профиля пользователя + :type user_profile: :class:`main.models.UserProfile` """ - return user_profile.user.username - - -def set_and_get_email(user_profile: UserProfile): # TODO: Переделать с получением данных через API - """ - Функция устанавливает поле :class:`user.email` текущей почтой в Zendesk - - :param UP: Объект профиля пользователя - :type UP: :class:`main.models.UserProfile` - :return: Почта пользователя - :rtype: :class:`str` - """ - return user_profile.user.email - - -def set_and_get_role(user_profile: UserProfile): # TODO: Переделать с получением данных через API - """ - Функция устанавливает поле :class:`role` текущей ролью в Zendesk - - :param UP: Объект профиля пользователя - :type UP: :class:`main.models.UserProfile` - :return: Роль пользователя - :rtype: :class:`str` - """ - return user_profile.role - - -def load_and_get_image(user_profile: UserProfile): # TODO: Переделать с получением изображения через API - """ - Функция загружает и устанавливает изображение в поле :class:`image` - - :param UP: Объект профиля пользователя - :type UP: :class:`main.models.UserProfile` - :return: Название изображения - :rtype: :class:`str` - """ - return user_profile.image.name + 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_profile.save() def check_user_exist(email: str) -> bool: @@ -67,16 +78,7 @@ def check_user_exist(email: str) -> bool: :return: True, если существует, иначе False :rtype: :class:`bool` """ - admin_creds = { - 'email': os.environ.get('Admin_email'), - 'subdomain': 'ngenix1612197338', - 'token': os.environ.get('Oauth_token'), - } - admin = Zenpy(**admin_creds) - zenpy_user = admin.search(email, type='user') - if zenpy_user: - return True - return False + return ZendeskAdmin().check_user(email) def check_user_auth(email: str, password: str) -> bool: @@ -91,12 +93,12 @@ def check_user_auth(email: str, password: str) -> bool: :raise :class:`APIException`: исключение, вызываемое если пользователь не аутентифицирован :rtype: :class:`bool` """ - try: - creds = { + creds = { 'email': email, - 'subdomain': 'ngenix1612197338', 'password': password, + 'subdomain': 'ngenix1612197338', } + try: user = Zenpy(**creds) user.search(email, type='user') except APIException: diff --git a/main/models.py b/main/models.py index 96d04db..58ae492 100644 --- a/main/models.py +++ b/main/models.py @@ -1,11 +1,22 @@ -import os - from django.contrib.auth.models import User from django.db import models +from django.db.models.signals import post_save +from django.dispatch import receiver class UserProfile(models.Model): user = models.OneToOneField(to=User, on_delete=models.CASCADE) - role = models.IntegerField() - image = models.ImageField(upload_to='user_avatars') + role = models.CharField(default='None', max_length=100) + image = models.URLField(null=True, blank=True) name = models.CharField(default='None', max_length=100) + + +@receiver(post_save, sender=User) +def create_user_profile(sender, instance, created, **kwargs): + if created: + UserProfile.objects.create(user=instance) + + +@receiver(post_save, sender=User) +def save_user_profile(sender, instance, **kwargs): + instance.userprofile.save() diff --git a/main/templates/pages/profile.html b/main/templates/pages/profile.html index 2b917eb..bfd8cd7 100644 --- a/main/templates/pages/profile.html +++ b/main/templates/pages/profile.html @@ -14,8 +14,8 @@ .img{ width:auto; height:auto; - max-width:300px!important; - max-height:500px!important; + max-width:100px!important; + max-height:100px!important; } @@ -28,8 +28,8 @@