88 lines
2.7 KiB
Python
88 lines
2.7 KiB
Python
import logging
|
|
|
|
import requests
|
|
import time
|
|
from django.conf import settings
|
|
from django.core.cache import cache
|
|
from django.db import models
|
|
from httpx import Request
|
|
|
|
from utils.clients.gooyal_promotions_client import AuthenticatedClient
|
|
from utils.clients.gooyal_promotions_client.api.api import (
|
|
api_v2_promotions_application_plan_promote_create
|
|
)
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
def login_as_client_credentials():
|
|
access_token_cache_key = 'accounts_access_token'
|
|
access_token = cache.get(access_token_cache_key)
|
|
# expires_in = self.auth_data.get('expires_in')
|
|
# created_at = self.auth_data.get('created_at')
|
|
#
|
|
# if access_token and expires_in > time.time() - created_at:
|
|
# return self.auth_data
|
|
if access_token:
|
|
logger.debug('token available in cache')
|
|
return access_token
|
|
|
|
logger.debug('no token available in cache')
|
|
|
|
data = {
|
|
"grant_type": 'client_credentials',
|
|
"scope": settings.OAUTH2_PROVIDER_SCOPES,
|
|
}
|
|
auth = (settings.OAUTH2_PROVIDER_CLIENT_ID, settings.OAUTH2_PROVIDER_CLIENT_SECRET)
|
|
|
|
response = requests.post(f'{settings.OAUTH2_PROVIDER_BASE_PUBLIC_URL}/token/',
|
|
data=data,
|
|
auth=auth)
|
|
logger.debug(response.content)
|
|
|
|
auth_data = response.json()
|
|
if 'access_token' in auth_data:
|
|
auth_data['created_at'] = time.time()
|
|
cache.set(access_token_cache_key, auth_data, timeout=auth_data.get('expires_in') - 5)
|
|
|
|
return auth_data
|
|
|
|
|
|
def log_request(request: Request):
|
|
logger.debug(f'authorization: {request.headers["authorization"]}')
|
|
logger.debug(
|
|
f"Request event hook: {request.method} {request.url} {request.method} {request.headers} - Waiting for response")
|
|
|
|
|
|
def log_response(response):
|
|
request = response.request
|
|
logger.debug(f"Response event hook: {request.method} {request.url} - Status {response.status_code}")
|
|
# logger.debug(f"Response event hook: {response.read()}")
|
|
|
|
|
|
def get_promotions_client():
|
|
access_token = login_as_client_credentials()['access_token']
|
|
client = AuthenticatedClient(base_url=settings.PROMOTIONS_BASE_PUBLIC_URL, token=access_token,
|
|
httpx_args={"event_hooks": {"request": [log_request], "response": [log_response]}},
|
|
)
|
|
return client
|
|
|
|
|
|
def promote_user(user, plan, label, data):
|
|
class Tmp():
|
|
def to_dict(self):
|
|
return {
|
|
"data": data,
|
|
"label": label
|
|
}
|
|
|
|
data = Tmp()
|
|
client = get_promotions_client()
|
|
response = api_v2_promotions_application_plan_promote_create.sync(
|
|
user_uuid=user,
|
|
id=plan,
|
|
client=client,
|
|
body=data
|
|
)
|
|
|
|
return response
|