Commit 32f854d4 authored by 张宇's avatar 张宇

[A]环信用户注册

parent 9580c074
# -*- coding: utf-8 -*-
from django.core.cache import caches
huanxin_cache = caches['huanxin']
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
import json
from typing import Optional
from django.conf import settings
import requests
from adapter.log import exception_logger
from hx.exceptions import HuanXinException
from hx.errors import HuanXinError
from common.caches import huanxin_cache
def handle_huanxin_response_error(response: requests.models.Response, client=None):
# http://docs-im.easemob.com/im/other/errorcode/restapi#%E7%B4%A2%E5%BC%95_%E9%94%99%E8%AF%AF%E7%8A%B6%E6%80%81%E7%A0%81
result = None
try:
result = json.loads(response.content.decode('utf-8', 'ignore'),
strict=False)
except Exception as e:
exception_logger.exception(str(e))
raise HuanXinException(
error=HuanXinError.HUAN_XIN_SERVER_ERROR.value,
error_description=HuanXinError.HUAN_XIN_SERVER_ERROR.value,
client=client,
request=reqe.request,
response=reqe.response
)
if 400 <= response.status_code <= 599:
raise HuanXinException(
error=result.get('error'),
error_description=result.get('error_description'),
client=client,
request=reqe.request,
response=reqe.response
)
return result
class HuanXinClient(object):
BASE_URL = getattr(settings, 'HX_BASE_URL', None)
ORG_NAME = getattr(settings, 'HX_ORG_NAME', None)
APP_NAME = getattr(settings, 'HX_APP_NAME', None)
CLIENT_ID = getattr(settings, 'HX_CLIENT_ID', None)
CLIENT_SECRECT = getattr(settings, 'HX_CLIENT_SECRECT', None)
TOKEN_CACHE_KEY = 'HX_TOEKN'
def __init__(self):
assert self.BASE_URL and self.ORG_NAME and \
self.APP_NAME and self.CLIENT_ID and self.CLIENT_SECRECT, \
'huanxin config error'
self.session = requests.Session()
def _get_auth_token(self):
GET_TOKEN_URL = '{base_url}/{org_name}/{app_name}/token'.format(
base_url=self.BASE_URL,
org_name=self.ORG_NAME,
app_name=self.APP_NAME)
data = {
'grant_type': 'client_credentials',
'client_id': self.CLIENT_ID,
'client_secret': self.CLIENT_SECRECT
}
response = self.session.post(GET_TOKEN_URL, json=data)
return handle_huanxin_response_error(response)
def check_then_set_token(self):
cached_hx_token = huanxin_cache.get(self.TOKEN_CACHE_KEY)
if not cached_hx_token:
token_dict = self._get_auth_token()
expires_in = token_res.get('expires_in', 5184000) - 5*60
huanxin_cache.set(self.TOKEN_CACHE_KEY, json.dumps(token_res), expires_in)
else:
token_dict = json.loads(cached_hx_token)
self.session.headers['Authorization'] = 'Bearer {}'.format(token_dict.get('access_token'))
def register_single_user(self, hx_username:str, hx_password:str, nickname: Optional[str]=None):
REGISTER_SINGLE_USER_URL = '{base_url}/{org_name}/{app_name}/users'.format(
base_url=self.BASE_URL,
org_name=self.ORG_NAME,
app_name=self.APP_NAME)
data = dict(
username=hx_username,
password=hx_password,
nickname=nickname
)
response = self.session.post(REGISTER_SINGLE_USER_URL, json=data)
return handle_huanxin_response_error(response)
\ No newline at end of file
# -*- coding: utf-8 -*-
from enum import Enum
class HuanXinError(str, Enum):
HUAN_XIN_SERVER_ERROR = 'huanxin server error' # 返回数据格式不是json
REQUEST_ENTITY_TOO_LARGE = 'Request Entity Too Large'
AUTH_BAD_ACCESS_TOKEN = 'auth_bad_access_token'
DUPLICATE_UNIQUE_PROPERTY_EXISTS = 'duplicate_unique_property_exists'
FORBIDDEN_OP = 'forbidden_op'
ILLEGAL_ARGUMENT = 'illegal_argument'
INVALID_GRANT = 'invalid_grant'
INVALID_PARAMETER = 'invalid_parameter'
JSON_PARSE = 'json_parse'
NO_FULL_TEXT_INDEX = 'no_full_text_index'
ORGANIZATION_APPLICATION_NOT_FOUND = 'organization_application_not_found'
REACH_LIMIT = 'reach_limit'
REQUIRED_PROPERTY_NOT_FOUND = 'required_property_not_found'
RESOURCE_LIMITED = 'resource_limited'
SERVICE_RESOURCE_NOT_FOUND = 'service_resource_not_found'
STORAGE_OBJECT_NOT_FOUND = 'storage_object_not_found'
UNAUTHORIZED = 'unauthorized'
UNSUPPORTED_SERVICE_OPERATION = 'unsupported_service_operation'
WEB_APPLICATION = 'web_application'
# -*- coding: utf-8 -*-
class HuanXinException(object):
def __init__(self, errcode, errmsg, client=None,
request=None, response=None):
self.errcode = errcode
self.errmsg = errmsg
self.client = client
self.request = request
self.response = response
class HuanXinGetTokenException():
pass
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment