access-controller/main/apiauth.py

50 lines
1.7 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.api_objects import User as ZenpyUser
from access_controller.settings import ACTRL_ZENDESK_SUBDOMAIN, ACTRL_API_EMAIL, ACTRL_API_TOKEN, ACTRL_API_PASSWORD
def api_auth() -> dict:
"""
Функция создания пользователя с использованием Zendesk API.
Получает из env Zendesk - email, token, password пользователя.
Если данные валидны и пользователь Zendesk с указанным email и токеном или паролем существует,
создается словарь данных пользователя, полученных через API c Zendesk.
:return: данные пользователя
"""
credentials = {
'subdomain': ACTRL_ZENDESK_SUBDOMAIN
}
email = ACTRL_API_EMAIL
token = ACTRL_API_TOKEN
password = ACTRL_API_PASSWORD
if email is None:
raise ValueError('access_controller email not in env')
credentials['email'] = email
# prefer token, use password if token not provided
if token:
credentials['token'] = token
elif password:
credentials['password'] = password
else:
raise ValueError('access_controller token or password not in env')
zenpy_client = Zenpy(**credentials)
zenpy_user: ZenpyUser = zenpy_client.users.search(email).values[0]
user = {
'id': zenpy_user.id,
'name': zenpy_user.name, # Zendesk doesn't have separate first and last name fields
'email': zenpy_user.email,
'role': zenpy_user.role, # str like 'admin' or 'agent', not id
'photo': zenpy_user.photo['content_url'] if zenpy_user.photo is not None else None,
}
return user