access-controller/main/extra_func.py
2021-02-16 22:32:29 +03:00

107 lines
3.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
from zenpy import Zenpy
from zenpy.lib.exception import APIException
from main.models import 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):
"""
Функция обновляет профиль пользователя в соотвтетствии с текущим в Zendesk
: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_profile.save()
def check_user_exist(email: str) -> bool:
"""
Функция проверяет, существует ли пользователь
:param email: Электронная почта пользователя
:type email: :class:`str`
:return: True, если существует, иначе False
:rtype: :class:`bool`
"""
return ZendeskAdmin().check_user(email)
def check_user_auth(email: str, password: str) -> bool:
"""
Функция проверяет, верны ли входные данные
:param email: Электроная почта пользователя
:type email: :class:`str`
:param password: Пароль пользователя
:type password: :class:`str`
:return: True, если входные данные верны, иначе False
:raise :class:`APIException`: исключение, вызываемое если пользователь не аутентифицирован
:rtype: :class:`bool`
"""
creds = {
'email': email,
'password': password,
'subdomain': 'ngenix1612197338',
}
try:
user = Zenpy(**creds)
user.search(email, type='user')
except APIException:
return False
return True