def validate_pairing_code(pairing_code): cache_key = 'pairing.code:' + pairing_code cache = SeleneCache() pairing_cache = cache.get(cache_key) if pairing_cache is None: raise ValidationError('pairing code not found')
class UpdateDeviceLastContact(SeleneScript): def __init__(self): super(UpdateDeviceLastContact, self).__init__(__file__) self.cache = SeleneCache() def _run(self): device_repo = DeviceRepository(self.db) devices_updated = 0 for device in device_repo.get_all_device_ids(): last_contact_ts = self._get_ts_from_cache(device.id) if last_contact_ts is not None: devices_updated += 1 device_repo.update_last_contact_ts(device.id, last_contact_ts) self.log.info(str(devices_updated) + ' devices were active today') def _get_ts_from_cache(self, device_id): last_contact_ts = None cache_key = DEVICE_LAST_CONTACT_KEY.format(device_id=device_id) value = self.cache.get(cache_key) if value is not None: last_contact_ts = datetime.strptime(value.decode(), '%Y-%m-%d %H:%M:%S.%f') self.cache.delete(cache_key) return last_contact_ts
def validate_pairing_code_removal(context): """Ensure that the endpoint removed the pairing code entry from the cache.""" cache = SeleneCache() pairing_data = cache.get( DEVICE_PAIRING_CODE_KEY.format(pairing_code=context.pairing_code) ) assert_that(pairing_data, none())
def validate_pairing_code(pairing_code): """Ensure the pairing code exists in the cache of valid pairing codes.""" cache_key = DEVICE_PAIRING_CODE_KEY.format(pairing_code=pairing_code) cache = SeleneCache() pairing_cache = cache.get(cache_key) if pairing_cache is None: raise ValidationError("pairing code not found")
def validate_pairing_code(pairing_code): """Ensure the pairing code exists in the cache of valid pairing codes.""" cache_key = "pairing.code:" + pairing_code cache = SeleneCache() pairing_cache = cache.get(cache_key) if pairing_cache is None: raise ValidationError("pairing code not found")
def validate_pairing_token(context): device_id = context.response.data.decode() cache = SeleneCache() pairing_data = cache.get('pairing.token:this is a token') pairing_data = json.loads(pairing_data) assert_that(pairing_data['uuid'], equal_to(device_id)) assert_that(pairing_data['state'], equal_to(context.pairing_data['state'])) assert_that(pairing_data['token'], equal_to(context.pairing_data['token']))
def validate_pairing_token(context): device_id = context.response.data.decode() cache = SeleneCache() pairing_data = cache.get("pairing.token:this is a token") pairing_data = json.loads(pairing_data) assert_that(pairing_data["uuid"], equal_to(device_id)) assert_that(pairing_data["state"], equal_to(context.pairing_data["state"])) assert_that(pairing_data["token"], equal_to(context.pairing_data["token"]))
def validate_pairing_token(context): """Validate the pairing token data was added to the cache as expected.""" device_id = context.response.data.decode() cache = SeleneCache() pairing_data = cache.get( DEVICE_PAIRING_TOKEN_KEY.format(pairing_token="this is a token")) pairing_data = json.loads(pairing_data) assert_that(pairing_data["uuid"], equal_to(device_id)) assert_that(pairing_data["state"], equal_to(context.pairing_data["state"])) assert_that(pairing_data["token"], equal_to(context.pairing_data["token"]))
def set_device_pairing_code(context): pairing_data = dict(code='ABC123', state='this is a state', token='this is a token', expiration=84600) cache = SeleneCache() cache.set_with_expiration('pairing.code:ABC123', json.dumps(pairing_data), expiration=86400) context.pairing_data = pairing_data context.pairing_code = 'ABC123'
def set_device_pairing_code(context): pairing_data = dict( code="ABC123", state="this is a state", token="this is a token", expiration=84600, ) cache = SeleneCache() cache.set_with_expiration("pairing.code:ABC123", json.dumps(pairing_data), expiration=86400) context.pairing_data = pairing_data context.pairing_code = "ABC123"
def set_device_pairing_code(context): """Add dummy data to the Redis cache for the test.""" pairing_data = dict( code="ABC123", packaging_type="pantacor", state="this is a state", token="this is a token", expiration=84600, ) cache = SeleneCache() cache.set_with_expiration("pairing.code:ABC123", json.dumps(pairing_data), expiration=86400) context.pairing_data = pairing_data context.pairing_code = "ABC123"
def before_all(context): use_fixture(public_api_client, context) context.cache = SeleneCache() context.db = connect_to_db(context.client_config['DB_CONNECTION_CONFIG']) agreements = add_agreements(context.db) context.terms_of_use = agreements[0] context.privacy_policy = agreements[1] context.open_dataset = agreements[2]
def before_all(context): """Setup static test data before any tests run. This is data that does not change from test to test so it only needs to be setup and torn down once. """ use_fixture(public_api_client, context) context.cache = SeleneCache() context.db = connect_to_db(context.client_config["DB_CONNECTION_CONFIG"]) add_agreements(context)
def delete_device_login(device_id: str, cache: SeleneCache): session = cache.get("device.session:{uuid}".format(uuid=device_id)) if session is not None: session = json.loads(session) access_token = session["accessToken"] cache.delete( "device.token.access:{access}".format(access=access_token)) refresh_token = session["refreshToken"] cache.delete( "device.refresh.token:{refresh}".format(refresh=refresh_token)) cache.delete("device.session:{uuid}".format(uuid=device_id))
def before_all(context): """Setup static test data before any tests run. This is data that does not change from test to test so it only needs to be setup and torn down once. """ _log.info("setting up test suite...") use_fixture(public_api_client, context) context.cache = SeleneCache() context.db = connect_to_db(context.client_config["DB_CONNECTION_CONFIG"]) add_agreements(context) context.wake_words = {"hey selene": add_wake_word(context.db)} data_dir = mkdtemp() context.wake_word_dir = Path(data_dir).joinpath("wake-word") os.environ["SELENE_DATA_DIR"] = data_dir
def generate_device_login(device_id: str, cache: SeleneCache) -> dict: """Generates a login session for a given device id""" sha512 = hashlib.sha512() sha512.update(bytes(str(uuid.uuid4()), "utf-8")) access = sha512.hexdigest() sha512.update(bytes(str(uuid.uuid4()), "utf-8")) refresh = sha512.hexdigest() login = dict(uuid=device_id, accessToken=access, refreshToken=refresh, expiration=ONE_DAY) login_json = json.dumps(login) # Storing device access token for one: cache.set_with_expiration( "device.token.access:{access}".format(access=access), login_json, ONE_DAY) # Storing device refresh token for ever: cache.set("device.token.refresh:{refresh}".format(refresh=refresh), login_json) # Storing the login session by uuid (that allows us to delete session using the uuid) cache.set("device.session:{uuid}".format(uuid=device_id), login_json) return login
from .endpoints.oauth_callback import OauthCallbackEndpoint from .endpoints.open_weather_map import OpenWeatherMapEndpoint from .endpoints.premium_voice import PremiumVoiceEndpoint from .endpoints.stripe_webhook import StripeWebHookEndpoint from .endpoints.wake_word_file import WakeWordFileUpload from .endpoints.wolfram_alpha import WolframAlphaEndpoint from .endpoints.wolfram_alpha_simple import WolframAlphaSimpleEndpoint from .endpoints.wolfram_alpha_spoken import WolframAlphaSpokenEndpoint from .endpoints.wolfram_alpha_v2 import WolframAlphaV2Endpoint _log = configure_logger("public_api") public = Flask(__name__) public.config.from_object(get_base_config()) public.config["GOOGLE_STT_KEY"] = os.environ["GOOGLE_STT_KEY"] public.config["SELENE_CACHE"] = SeleneCache() public.response_class = SeleneResponse public.register_blueprint(selene_api) public.add_url_rule( "/v1/device/<string:device_id>/skill/<string:skill_gid>", view_func=DeviceSkillSettingsEndpoint.as_view("device_skill_delete_api"), methods=["DELETE"], ) public.add_url_rule( "/v1/device/<string:device_id>/skill", view_func=DeviceSkillSettingsEndpoint.as_view("device_skill_api"), methods=["GET", "PUT"], ) public.add_url_rule( "/v1/device/<string:device_id>/skill/settings", view_func=DeviceSkillSettingsEndpointV2.as_view("skill_settings_api"),
def validate_pairing_code_removal(context): cache = SeleneCache() pairing_data = cache.get("pairing.code:ABC123") assert_that(pairing_data, none())
def __init__(self): super(UpdateDeviceLastContact, self).__init__(__file__) self.cache = SeleneCache()
SkillOauthEndpoint, SkillSettingsEndpoint, SoftwareUpdateEndpoint, TimezoneEndpoint, VoiceEndpoint, WakeWordEndpoint, ) _log = configure_logger("account_api") # Define the Flask application acct = Flask(__name__) acct.config.from_object(get_base_config()) acct.response_class = SeleneResponse acct.register_blueprint(selene_api) acct.config["SELENE_CACHE"] = SeleneCache() account_endpoint = AccountEndpoint.as_view("account_endpoint") acct.add_url_rule("/api/account", view_func=account_endpoint, methods=["GET", "PATCH", "DELETE"]) agreements_endpoint = AgreementsEndpoint.as_view("agreements_endpoint") acct.add_url_rule( "/api/agreement/<string:agreement_type>", view_func=agreements_endpoint, methods=["GET"], ) city_endpoint = CityEndpoint.as_view("city_endpoint") acct.add_url_rule("/api/cities", view_func=city_endpoint, methods=["GET"])
from .endpoints import (PreferencesEndpoint, CityEndpoint, CountryEndpoint, AccountDefaultsEndpoint, DeviceEndpoint, DeviceCountEndpoint, GeographyEndpoint, MembershipEndpoint, RegionEndpoint, PairingCodeEndpoint, SkillsEndpoint, SkillOauthEndpoint, SkillSettingsEndpoint, TimezoneEndpoint, VoiceEndpoint, WakeWordEndpoint) _log = configure_logger('account_api') # Define the Flask application acct = Flask(__name__) acct.config.from_object(get_base_config()) acct.response_class = SeleneResponse acct.register_blueprint(selene_api) acct.config['SELENE_CACHE'] = SeleneCache() account_endpoint = AccountEndpoint.as_view('account_endpoint') acct.add_url_rule('/api/account', view_func=account_endpoint, methods=['GET', 'POST', 'PATCH', 'DELETE']) agreements_endpoint = AgreementsEndpoint.as_view('agreements_endpoint') acct.add_url_rule('/api/agreement/<string:agreement_type>', view_func=agreements_endpoint, methods=['GET']) city_endpoint = CityEndpoint.as_view('city_endpoint') acct.add_url_rule('/api/cities', view_func=city_endpoint, methods=['GET']) country_endpoint = CountryEndpoint.as_view('country_endpoint')
from .endpoints.device_subscription import DeviceSubscriptionEndpoint from .endpoints.geolocation import GeolocationEndpoint from .endpoints.google_stt import GoogleSTTEndpoint from .endpoints.oauth_callback import OauthCallbackEndpoint from .endpoints.open_weather_map import OpenWeatherMapEndpoint from .endpoints.premium_voice import PremiumVoiceEndpoint from .endpoints.stripe_webhook import StripeWebHookEndpoint from .endpoints.wolfram_alpha import WolframAlphaEndpoint from .endpoints.wolfram_alpha_spoken import WolframAlphaSpokenEndpoint _log = configure_logger('public_api') public = Flask(__name__) public.config.from_object(get_base_config()) public.config['GOOGLE_STT_KEY'] = os.environ['GOOGLE_STT_KEY'] public.config['SELENE_CACHE'] = SeleneCache() public.response_class = SeleneResponse public.register_blueprint(selene_api) public.add_url_rule( '/v1/device/<string:device_id>/skill/<string:skill_gid>', view_func=DeviceSkillSettingsEndpoint.as_view('device_skill_delete_api'), methods=['DELETE'] ) public.add_url_rule( '/v1/device/<string:device_id>/skill', view_func=DeviceSkillSettingsEndpoint.as_view('device_skill_api'), methods=['GET', 'PUT'] ) public.add_url_rule( '/v1/device/<string:device_id>/skill/settings', view_func=DeviceSkillSettingsEndpointV2.as_view('skill_settings_api'),
def _clean_cache(): """Remove testing data from the Redis database.""" cache = SeleneCache() cache.delete("pairing.token:this is a token")
def _expire_device_setting_cache(self): cache = SeleneCache() etag_manager = ETagManager(cache, self.config) etag_manager.expire_device_setting_etag_by_account_id(self.account.id)
def _clean_cache(): cache = SeleneCache() cache.delete('pairing.token:this is a token')