Ejemplo n.º 1
0
 def test_get_app_token_cache(self):
     app_token_key = get_hash_key(key_type="app")
     cache.set(app_token_key, {'app_token': MOCK_RESPONSE},
               timeout=MOCK_RESPONSE["expires_in"] - 120)
     app_token = get_app_token()
     cache.delete(app_token_key)
     self.assertEqual(app_token, MOCK_RESPONSE["token"])
Ejemplo n.º 2
0
def get_acl_token(service_name):
    """get service acl token"""
    acl_middleware = getattr(settings, 'ACL_MIDDLEWARE', None)
    if acl_middleware is None:
        return None
    acl_token_key = get_hash_key()
    settings_acl_token = getattr(settings, acl_token_key, None)
    if settings_acl_token and (int(time.time()) - int(settings_acl_token['time'])) <= int(60*10):
        logging.info('sparrow_cloud: get acl_token from settings, within ten minutes')
        return settings_acl_token['acl_token']
    cache_acl_token = cache.get(acl_token_key)
    if cache_acl_token and (int(time.time()) - int(cache_acl_token['time'])) <= int(60*10):
        logging.info('sparrow_cloud: get acl_token from cache, within ten minutes')
        return cache_acl_token['acl_token']
    try:
        response = requests_get(acl_middleware['ACL_SERVICE'], service_name, acl_middleware['API_PATH'])
        acl_token = response.json()['acl_token']
        setattr(settings, acl_token_key, {'acl_token': acl_token, 'time': time.time()})
        cache.set(acl_token_key, {'acl_token': acl_token, 'time': time.time()})
        logging.info('sparrow_cloud: get acl_token from acl_service')
        return acl_token
    except Exception as ex:
        if cache_acl_token and (int(time.time()) - int(cache_acl_token['time'])) < int(24*60*60):
            logging.info('sparrow_cloud: get acl_token from cache, within 24 hours')
            return cache_acl_token['acl_token']
        if settings_acl_token and (int(time.time()) - int(settings_acl_token['time'])) < int(24*60*60):
            logging.info('sparrow_cloud: get acl_token from settings, within 24 hours')
            return settings_acl_token['acl_token']
        logger.error('sparrow_cloud error: ACL_SERVICE Exception, no token available in cache, message:{}'
                     .format(ex.__str__()))
        raise Exception('sparrow_cloud error: ACL_SERVICE Exception, no token available in cache, message:{}'
                        .format(ex.__str__()))
Ejemplo n.º 3
0
def get_app_token():
    """
    get app token
    REGISTRY_APP_CONF = {
        "SERVICE_ADDRESS": "sparrow-service-svc:8000",
        "PATH": "/api/get_app_token/",
        "ENABLE_TOKEN_CACHE": os.environ.get("ENABLE_TOKEN_CACHE", False)
    }
    :return:
    """
    app_token_key = get_hash_key(key_type="app")
    service_conf = get_settings_value("SERVICE_CONF")
    registry_app_conf = get_settings_value("REGISTRY_APP_CONF")
    enable_get_token_cache = registry_app_conf["ENABLE_TOKEN_CACHE"]
    if enable_get_token_cache:
        cache_app_token = cache.get(app_token_key)
        if cache_app_token:
            return cache_app_token["app_token"]
    try:
        data = {"name": service_conf["NAME"], "secret": service_conf["SECRET"]}
        data_to_send = json.dumps(data).encode("utf-8")
        app_token = rest_client.post(
            service_address=registry_app_conf["SERVICE_ADDRESS"],
            api_path=registry_app_conf["PATH"],
            timeout=0.5,
            data=data_to_send)
        cache.set(app_token_key, {'app_token': app_token},
                  timeout=app_token["expires_in"] - 120)
        return app_token["token"]
    except Exception as ex:
        raise Exception(
            'get_app_token error, no token available in cache and registry_app_error, '
            'message:{}'.format(ex.__str__()))
Ejemplo n.º 4
0
def get_app_token():
    """
    get app token
    configmap:
        SC_MANAGE_SVC
        SC_MANAGE_API
    """
    app_token_key = get_hash_key(key_type="app")
    service_conf = get_settings_value("SERVICE_CONF")
    sc_manage_svc = get_cm_value("SC_MANAGE_SVC")
    sc_manage_api = get_cm_value("SC_MANAGE_API")
    try:
        cache_app_token = cache.get(app_token_key)
        if cache_app_token:
            return cache_app_token["app_token"]["token"]
        else:
            data = {
                "name": service_conf["NAME"],
                "secret": service_conf["SECRET"]
            }
            app_token = rest_client.post(service_address=sc_manage_svc,
                                         api_path=sc_manage_api,
                                         json=data)
            cache.set(app_token_key, {'app_token': app_token},
                      timeout=app_token["expires_in"] - 120)
            logger.info("sparrowcloud get app token: {}".format(
                app_token["token"]))
            return app_token["token"]
    except Exception as ex:
        raise Exception(
            'sparrowcloud/get_app_token error, no token available in cache and app_manage_error, '
            'message:{}'.format(ex.__str__()))
Ejemplo n.º 5
0
 def test_get_app_token_cache(self, mock_post):
     app_token = get_app_token()
     data = json.loads(app_token)
     self.assertIn("uid", data)
     # 测试一次请求之后,检查缓存中是否已经缓存该token,并且缓存中与函数返回的数据相同
     app_token_key = get_hash_key(key_type="app")
     cache_app_token = cache.get(app_token_key)
     self.assertEqual(app_token, cache_app_token)
Ejemplo n.º 6
0
 def test_get_user_token_cache(self):
     user_token_key = get_hash_key(key_type="user",
                                   user_id="21424kvjbcdjslafds")
     cache.set(user_token_key, {'user_token': MOCK_RESPONSE},
               timeout=MOCK_RESPONSE["expires_in"] - 120)
     token = get_user_token(user_id="21424kvjbcdjslafds")
     cache.delete(user_token_key)
     self.assertEqual(token, MOCK_RESPONSE["token"])
Ejemplo n.º 7
0
 def test_get_user_token_cache(self, mock_post):
     uid = "test_cache_user_id"
     token = get_user_token(user_id=uid)
     data = json.loads(token)
     self.assertIn("uid", data)
     # 测试一次请求之后,检查缓存中是否已经缓存该token,并且缓存中与函数返回的数据相同
     user_token_key = get_hash_key(key_type="user", user_id=uid)
     cache_user_token = cache.get(user_token_key)
     self.assertEqual(token, cache_user_token)
Ejemplo n.º 8
0
def get_user_token(user_id):
    """
    get user token
    :param user_id:
    
    configmap:
        SC_MANAGE_SVC
        SC_MANAGE_API
    """
    user_token_key = get_hash_key(key_type="user", user_id=user_id)
    service_conf = get_settings_value("SERVICE_CONF")
    sc_manage_svc = get_cm_value("SC_MANAGE_SVC")
    sc_manage_api = get_cm_value("SC_MANAGE_API")
    try:
        if os.environ.get("SC_SKIP_TOKEN_CACHE", "").title() != "True":
            cache_user_token = cache.get(user_token_key)
            if cache_user_token:
                return cache_user_token
        # 跳过缓存或者缓存数据空
        data = {
            "name": service_conf["NAME"],
            "secret": service_conf["SECRET"],
            "uid": user_id
        }
        res = requests_client.post(service_address=sc_manage_svc,
                                   api_path=sc_manage_api,
                                   json=data)
        if res.status_code < 200 or res.status_code >= 300:
            raise Exception(
                f"请求app_manage服务出错,状态码:{res.status_code},数据:{res.text}")
        cache.set(user_token_key,
                  res.text,
                  timeout=res.json().get("expires_in", 7200))
        return res.text
    except Exception as ex:
        logger.error(
            f"sparrowcloud/get_user_token error, no token available in cache and app_manage_error,\
                        'message:{ex.__str__()}, return static token")
        return json.dumps({
            "iss": "sparrow_cloud",
            "uid": user_id,
            "type": "user"
        })
Ejemplo n.º 9
0
 def tearDown(self):
     app_token_key = get_hash_key(key_type="app")
     cache.delete(app_token_key)
Ejemplo n.º 10
0
 def test_user_hash_key(self):
     user_token = get_hash_key(key_type="user",
                               user_id="21424kvjbcdjslafds")
     self.assertEqual(user_token, "USER_TOKEN_4238378")
Ejemplo n.º 11
0
 def test_app_hash_key(self):
     app_token = get_hash_key(key_type="app")
     self.assertEqual(app_token, "APP_TOKEN_B9B9023")
Ejemplo n.º 12
0
 def test_get_acl_token_from_cache(self):
     from django.core.cache import cache
     acl_token_key = get_hash_key()
     cache.set(acl_token_key, {'acl_token': 'ACL_TOKEN1010101010', 'time': time.time()})
     self.assertEqual(get_acl_token('acl_test'), 'ACL_TOKEN1010101010')
Ejemplo n.º 13
0
 def test_get_acl_token_from_settings(self):
     acl_token_key = get_hash_key()
     setattr(settings, acl_token_key, {'acl_token': 'ACL_TOKEN88888888888', 'time': time.time()})
     self.assertEqual(get_acl_token('acl_test'), 'ACL_TOKEN88888888888')