def put(self, model, overwrite=True): storage_model = StorageModel(model_type=type(model)) serialized_item = storage_model.serialize(model) serialized_item.pop(storage_model.key_field) if len(serialized_item) == 1 and storage_model.expiry_field in serialized_item: # Don't store a value if the only key that is not the key_field is the expiry_field value = "" else: value = json.dumps(serialized_item) key_value = getattr(model, storage_model.key_field) expires_in = None if storage_model.expiry_field: expiry_at = getattr(model, storage_model.expiry_field) expires_in = expiry_at - datetime.now(tz=tzutc()) try: record_created = self.client.set( name=key_value, value=value, ex=expires_in, nx=not overwrite ) except RedisConnectionError: self.log_retry("set") record_created = self.client.set( name=key_value, value=value, ex=expires_in, nx=not overwrite ) if not record_created: raise ItemAlreadyExistsError()
def put_jti(self, jti): record_created = self.redis.set( name=jti.jti_claim, value=int(jti.used_at.timestamp()), ex=int((jti.expires - jti.used_at).total_seconds()), nx=True, ) if not record_created: raise ItemAlreadyExistsError()
def test_should_raise_jti_token_used_when_token_already_exists(self): # Given jti_token = str(uuid4()) expires = datetime.now(tz=tzutc()) + timedelta(seconds=60) # When with self.assertRaises(JtiTokenUsed) as err: with patch('app.storage.data_access.put', side_effect=[ItemAlreadyExistsError()]): use_jti_claim(jti_token, expires) # Then self.assertEqual(err.exception.jti_claim, jti_token) self.assertEqual(str(err.exception), "jti claim '{}' has already been used".format(jti_token))
def put(model, overwrite): config = TABLE_CONFIG[type(model)] sql_model = config['sql_model'].from_app_model(model) try: # pylint: disable=maybe-no-member if overwrite: models.db.session.merge(sql_model) else: models.db.session.add(sql_model) models.db.session.commit() except (IntegrityError, FlushError) as e: raise ItemAlreadyExistsError() from e
def test_should_raise_jti_token_used_when_token_already_exists( app, mock_redis_put): with app.app_context(): # Given jti_token = str(uuid4()) expires_at = datetime.now(tz=timezone.utc) + timedelta(seconds=60) # When with pytest.raises(JtiTokenUsed) as excinfo: mock_redis_put.side_effect = [ItemAlreadyExistsError()] use_jti_claim(jti_token, expires_at) # Then assert str( excinfo.value) == f"jti claim '{jti_token}' has already been used"
def put(self, model, overwrite=True): storage_model = StorageModel(model_type=type(model)) table = self.client.Table(storage_model.table_name) put_kwargs = {"Item": storage_model.serialize(model)} if not overwrite: put_kwargs[ "ConditionExpression"] = f"attribute_not_exists({storage_model.key_field})" try: response = table.put_item( **put_kwargs)["ResponseMetadata"]["HTTPStatusCode"] return response == 200 except ClientError as e: if e.response["Error"][ "Code"] == "ConditionalCheckFailedException": raise ItemAlreadyExistsError() from e raise # pragma: no cover
def put(model, overwrite): config = TABLE_CONFIG[type(model)] schema = config['schema'](strict=True) table = get_table(config) key_field = config['key_field'] item, _ = schema.dump(model) put_kwargs = {'Item': item} if not overwrite: put_kwargs[ 'ConditionExpression'] = 'attribute_not_exists({key_field})'.format( key_field=key_field) try: response = table.put_item( **put_kwargs)['ResponseMetadata']['HTTPStatusCode'] return response == 200 except ClientError as e: if e.response['Error']['Code'] == 'ConditionalCheckFailedException': raise ItemAlreadyExistsError() from e raise # pragma: no cover
def put(self, model, overwrite=True): config = TABLE_CONFIG[type(model)] schema = config["schema"]() table = self.get_table(config) key_field = config["key_field"] item = schema.dump(model) put_kwargs = {"Item": item} if not overwrite: put_kwargs[ "ConditionExpression"] = "attribute_not_exists({key_field})".format( key_field=key_field) try: response = table.put_item( **put_kwargs)["ResponseMetadata"]["HTTPStatusCode"] return response == 200 except ClientError as e: if e.response["Error"][ "Code"] == "ConditionalCheckFailedException": raise ItemAlreadyExistsError() from e raise # pragma: no cover