def fund_PAC(total_usd: float, nonce: int) -> Tuple[str, str, str]: wallet = generate_wallet() signer = wallet['address'] secret = wallet['private'] config = generate_config(secret=secret, ) # todo: pass on gas and app-store overhead? usd_per_oxt = get_usd_per_oxt() oxt_per_usd = 1.0 / usd_per_oxt escrow_oxt = get_min_escrow() # todo: better alg to determine this? value_usd = total_usd * 0.7 - 0.5 # 30% store fee, 0.5 setup charge value_oxt = value_usd * oxt_per_usd num_tickets = int(value_oxt / (0.5 * escrow_oxt)) escrow_oxt = 2.0 * float(value_oxt) / float(num_tickets) total_oxt = value_oxt + escrow_oxt logging.debug( f"Funding PAC signer: {signer}, total: ${total_usd}{total_oxt} OXT, escrow: {escrow_oxt} OXT" ) funder_pubkey = get_secret(key=os.environ['PAC_FUNDER_PUBKEY_SECRET']) funder_privkey = get_secret(key=os.environ['PAC_FUNDER_PRIVKEY_SECRET']) txn_hash = fund_PAC_( signer=signer, total=w3.toWei(total_oxt, 'ether'), escrow=w3.toWei(escrow_oxt, 'ether'), funder_pubkey=funder_pubkey, funder_privkey=funder_privkey, nonce=nonce, ) return txn_hash, config, signer
def fund_PAC(total_usd: float, nonce: int) -> Tuple[str, str, str]: wallet = generate_wallet() signer = wallet['address'] secret = wallet['private'] config = generate_config(secret=secret, ) usd_per_oxt = get_usd_per_oxt() oxt_per_usd = 1.0 / usd_per_oxt total_oxt = total_usd * oxt_per_usd escrow_oxt = 3.0 if (escrow_oxt >= 0.9 * total_oxt): escrow_oxt = 0.5 * total_oxt logging.debug(f"Funding PAC signer: {signer}, \ total: ${total_usd}{total_oxt} OXT, \ escrow: {escrow_oxt} OXT ") funder_pubkey = get_secret(key=os.environ['PAC_FUNDER_PUBKEY_SECRET']) funder_privkey = get_secret(key=os.environ['PAC_FUNDER_PRIVKEY_SECRET']) txn_hash = fund_PAC_( signer=signer, total=w3.toWei(total_oxt, 'ether'), escrow=w3.toWei(escrow_oxt, 'ether'), funder_pubkey=funder_pubkey, funder_privkey=funder_privkey, nonce=nonce, ) return txn_hash, config, signer
def fund_PAC(total_usd: float, nonce: int) -> Tuple[str, str, str, float, float]: wallet = generate_wallet() signer = wallet['address'] secret = wallet['private'] config = generate_config(secret=secret) total_wei, escrow_wei = get_PAC_pot_config(total_usd) eth_to_wei = 1000000000000000000 escrow_oxt = float(escrow_wei) / float(eth_to_wei) total_oxt = float(total_wei) / float(eth_to_wei) balance_oxt = total_oxt - escrow_oxt logging.debug( f'Funding PAC signer: {signer}, total: ${total_usd}{total_oxt} OXT, escrow: {escrow_oxt} OXT balance_oxt: {balance_oxt} OXT ' ) funder_pubkey = get_secret(key=os.environ['PAC_FUNDER_PUBKEY_SECRET']) funder_privkey = get_secret(key=os.environ['PAC_FUNDER_PRIVKEY_SECRET']) txn_hash = fund_PAC_( signer=signer, total=toWei(total_wei, 'wei'), escrow=toWei(escrow_wei, 'wei'), funder_pubkey=funder_pubkey, funder_privkey=funder_privkey, nonce=nonce, ) return txn_hash, config, signer, balance_oxt, escrow_oxt
def __init__(self, destination: str = "s3"): """ Possible destinations: - s3 (AWS) - blob (Azure) """ self.destination = destination if destination == "blob": # Run Azure blob storage upload # self.block_blob_service = BlockBlobService( # account_name=config['blob']['account'], account_key=config['blob']['key']) pass elif destination == "s3": # AWS access ACCESS_KEY = utils.get_secret("ACCESS_KEY_ID", "aws") SECRET_KEY = utils.get_secret("SECRET_ACCESS_KEY", "aws") AWS_REGION = utils.get_secret("REGION", "aws") self.S3_BUCKET = utils.get_secret("S3_BUCKET", "aws") # Run AWS S3 upload self.client = b3.client('s3', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY, region_name=AWS_REGION) else: log.error( "Cloud storage provider %s is not supported. Use 's3' or 'blob' instead." % destination)
def get_database_engine(): if "db_ip" in config.database: SACN = "mysql+mysqlconnector://{}:{}@{}:3306/{}?charset=utf8&ssl_ca={}&ssl_cert={}&ssl_key={}".format( config.database["db_user"], utils.get_secret(config.database["project_id"], config.database["secret_name"]), config.database["db_ip"], config.database["db_name"], config.database["server_ca"], config.database["client_ca"], config.database["client_key"], ) else: SACN = ( "mysql+pymysql://{}:{}@/{}?unix_socket=/cloudsql/{}:europe-west1:{}" .format( config.database["db_user"], utils.get_secret(config.database["project_id"], config.database["secret_name"]), config.database["db_name"], config.database["project_id"], config.database["instance_id"], )) return create_engine(SACN, pool_recycle=3600)
def get_api(): """Get krakenx API object""" log.debug("Getting kraken API object") kx_api = krakenex.API(get_secret("KRAKEN_KEY"), get_secret("KRAKEN_SECRET")) return KrakenAPI(kx_api)
def __init__(self): """General object initializer.""" self.OIDC_DOMAIN = get_secret('sso-dashboard.oidc_domain', {'app': 'sso-dashboard'}) self.OIDC_CLIENT_ID = get_secret('sso-dashboard.oidc_client_id', {'app': 'sso-dashboard'}) self.OIDC_CLIENT_SECRET = get_secret( 'sso-dashboard.oidc_client_secret', {'app': 'sso-dashboard'}) self.LOGIN_URL = "https://{DOMAIN}/login?client={CLIENT_ID}".format( DOMAIN=self.OIDC_DOMAIN, CLIENT_ID=self.OIDC_CLIENT_ID)
def lambda_handler(*_): github_project = os.environ.get("GITHUB_PROJECT") if not github_project: raise ValueError("Missing GITHUB_PROJECT environment") g = synchronizer.GitHubCredentials( github_project, **utils.get_secret(os.environ.get("GITHUB_CREDENTIALS_VAULT")) ) j = synchronizer.JiraCredentials( **utils.get_secret(os.environ.get("JIRA_CREDENTIALS_VAULT")) ) s = synchronizer.Synchronizer(g, j) s.synchronize()
def get_oxt_balance(address=get_secret(key=os.environ['PAC_FUNDER_PUBKEY_SECRET'])) -> float: token_addr = w3.toChecksumAddress(os.environ['TOKEN']) token_contract = w3.eth.contract( abi=token_abi, address=token_addr, ) token_name = get_token_name(token_addr) token_symbol = get_token_symbol(token_addr) token_decimals = get_token_decimals(token_addr) DECIMALS = 10 ** token_decimals raw_balance = token_contract.functions.balanceOf(address).call() balance = raw_balance / DECIMALS logging.info( f"Balance of {address}: {balance} {token_name} ({token_symbol})") if is_true(os.environ.get('ENABLE_MONITORING', '')): lambda_metric( f"orchid.pac.balance.{token_symbol.lower()}", balance, tags=[ f'account:{address}', f'token_name:{token_name}', f'token_symbol:{token_symbol}', f'token_decimals:{token_decimals}', ] ) return balance
def bind( signer: str, verifier: str, nonce: int, shared: str = '0x', gas_price: float = float(os.environ['DEFAULT_GAS']) ): logging.debug( f'bind() signer: {signer} verifier: {verifier} shared: {shared} ' f'nonce: {nonce} gas_price: {gas_price}' ) w3 = refresh_w3() funder_pubkey = get_secret(key=os.environ['PAC_FUNDER_PUBKEY_SECRET']) funder_privkey = get_secret(key=os.environ['PAC_FUNDER_PRIVKEY_SECRET']) lottery_addr = w3.toChecksumAddress(os.environ['LOTTERY']) lottery_contract = w3.eth.contract( abi=lottery_abi, address=lottery_addr, ) bind_txn = lottery_contract.functions.bind( signer, verifier, shared, ).buildTransaction( { 'chainId': 1, 'from': funder_pubkey, 'gas': 200000, 'gasPrice': w3.toWei(gas_price, 'gwei'), 'nonce': nonce, } ) logging.debug(f'bind_txn: {bind_txn}') bind_txn_signed = w3.eth.account.sign_transaction( bind_txn, private_key=funder_privkey, ) logging.debug(f'bind_txn_signed: {bind_txn_signed}') bind_txn_hash = w3.eth.sendRawTransaction(bind_txn_signed.rawTransaction) logging.debug(f'Submitted bind transaction with hash: {bind_txn_hash.hex()}') return bind_txn_hash.hex()
def main(event, context): stage = os.environ['STAGE'] body = json.loads(event.get('body', {})) if is_true(body.get('debug', '')): configure_logging(level="DEBUG") logging.debug(f'entry_payment_google stage:{stage}') logging.debug(f'os.environ: {os.environ}') logging.debug(f'event: {event}') logging.debug(f'context: {context}') logging.debug(f'body: {body}') #receipt = body.get('receipt', '') #bundle_id = body.get('bundle_id', '') account_id = body.get('account_id', '') verify_receipt = True # todo: add optional existing account if os.environ['STAGE'] == 'dev': verify_receipt = is_true(body.get('verify_receipt', 'True')) if os.environ['STAGE'] != 'dev': if body.get('verify_receipt', None) is not None: return response(402, {'msg': 'invalid_dev_param'}) GOOGLE_SERVICE_ACCOUNT_KEY_FILE = get_secret( 'ORCHID_GOOGLE_SERVICE_ACCOUNT2') logging.debug(f'{GOOGLE_SERVICE_ACCOUNT_KEY_FILE}') GOOGLE_SERVICE_ACCOUNT_KEY = json.loads(GOOGLE_SERVICE_ACCOUNT_KEY_FILE) purchase_token = body.get('receipt', '') product_id = body.get('product_id', '') bundle_id = body.get('bundle_id', 'net.orchid.Orchid') msg, receipt_hash, total_usd = verify_(GOOGLE_SERVICE_ACCOUNT_KEY, purchase_token, product_id, bundle_id) if ((account_id is None) or (account_id == '')): account_id = receipt_hash if (msg == "success"): logging.debug(f'conditional writing receipt with hash: {receipt_hash}') try: w3_generic.dynamodb_cwrite1(os.environ['RECEIPT_TABLE_NAME'], 'receipt', receipt_hash) except Exception as e: logging.info(f'writing receipt exception: {str(e)} ') return response(403, {'msg': 'Receipt already redeemed'}) w3_generic.credit_account_balance(account_id, total_usd) return response(200, { 'msg': msg, 'account_id': account_id, 'total_usd': total_usd }) else: return response(402, {'msg': msg})
def fund_PAC(total_usd: float, nonce: int) -> Tuple[str, str, str, float, float]: wallet = generate_wallet() signer = wallet['address'] secret = wallet['private'] config = generate_config(secret=secret) target_NFV = get_target_NFV(total_usd) tot_units = max(int(target_NFV + 0.5), 3) subsidy_usd = 0.0 usd_per_oxt = get_usd_per_oxt() oxt_per_usd = 1.0 / usd_per_oxt # escrow_oxt = get_min_escrow() value_usd = total_usd * 0.7 - 0.5 + subsidy_usd # 30% store fee, 0.5 setup charge value_oxt = value_usd * oxt_per_usd # tot_units = max(int(value_oxt / (0.5*escrow_oxt)), 3); FV_oxt = value_oxt / float(tot_units) eth_to_wei = 1000000000000000000 FV_wei = int(eth_to_wei * FV_oxt) total_wei = tot_units * FV_wei escrow_wei = 2 * FV_wei escrow_oxt = float(escrow_wei) / float(eth_to_wei) total_oxt = float(total_wei) / float(eth_to_wei) balance_oxt = total_oxt - escrow_oxt logging.debug( f'Funding PAC signer: {signer}, total: ${total_usd}{total_oxt} OXT, ' f'escrow: {escrow_oxt} OXT tot_units: {tot_units} FV_oxt: {FV_oxt} ' f'target_NFV: {target_NFV}') funder_pubkey = get_secret(key=os.environ['PAC_FUNDER_PUBKEY_SECRET']) funder_privkey = get_secret(key=os.environ['PAC_FUNDER_PRIVKEY_SECRET']) txn_hash = fund_PAC_( signer=signer, total=toWei(total_wei, 'wei'), escrow=toWei(escrow_wei, 'wei'), funder_pubkey=funder_pubkey, funder_privkey=funder_privkey, nonce=nonce, ) return txn_hash, config, signer, balance_oxt, escrow_oxt
def get_nonce() -> int: logging.debug('get_nonce()') w3 = refresh_w3() funder_pubkey = get_secret(key=os.environ['PAC_FUNDER_PUBKEY_SECRET']) nonce = w3.eth.getTransactionCount(account=funder_pubkey) logging.debug(f'nonce: {nonce}') return nonce
def main(event, context): logging.debug('Beginning Account Reclaiming Process') pac_funder = get_secret(key=os.environ['PAC_FUNDER_PUBKEY_SECRET']) logging.debug(f'Funder: {pac_funder}') signers = keys(funder=pac_funder) context = None body = { 'debug': 'True', 'funder': pac_funder, 'password': get_secret(key=os.environ['RECYCLE_KEY']) } for signer in signers: logging.debug(f'Processing Signer: {signer}') body['signer'] = signer event = { 'body': json.dumps(body), } recycle(event, context)
def maintain_pool_wrapper(event=None, context=None): configure_logging(level="DEBUG") mapping = get_product_id_mapping() funder_pubkey = get_secret(key=os.environ['PAC_FUNDER_PUBKEY_SECRET']) nonce = w3.eth.getTransactionCount(account=funder_pubkey) logging.debug(f"maintain_pool_wrapper Funder nonce: {nonce}") for product_id in mapping: price = mapping[product_id] nonce = maintain_pool(price=price, nonce=nonce)
def signMessage(message_text: str): logging.debug(f'signMessage() message_text: {message_text}') w3 = refresh_w3() funder_privkey = get_secret(key=os.environ['PAC_FUNDER_PRIVKEY_SECRET']) message = encode_defunct(text=message_text) signed_message = w3.eth.account.sign_message(message, private_key=funder_privkey) logging.debug(f'Signed Message: {signed_message}') return signed_message.signature
def push(signer: str, total: float, escrow: float, nonce: int, gas_price: float = float(os.environ['DEFAULT_GAS'])): logging.debug( f'push() signer: {signer} total: {total} escrow: {escrow} nonce: {nonce} gas_price: {gas_price}' ) w3 = refresh_w3() funder_pubkey = get_secret(key=os.environ['PAC_FUNDER_PUBKEY_SECRET']) funder_privkey = get_secret(key=os.environ['PAC_FUNDER_PRIVKEY_SECRET']) lottery_addr = w3.toChecksumAddress(os.environ['LOTTERY']) lottery_contract = w3.eth.contract( abi=lottery_abi, address=lottery_addr, ) push_txn = lottery_contract.functions.push( signer, total, escrow, ).buildTransaction({ 'chainId': 1, 'from': funder_pubkey, 'gas': 200000, 'gasPrice': w3.toWei(gas_price, 'gwei'), 'nonce': nonce, }) logging.debug(f'push_txn: {push_txn}') push_txn_signed = w3.eth.account.sign_transaction( push_txn, private_key=funder_privkey, ) logging.debug(f'push_txn_signed: {push_txn_signed}') push_txn_hash = w3.eth.sendRawTransaction(push_txn_signed.rawTransaction) logging.debug( f'Submitted push transaction with hash: {push_txn_hash.hex()}') return push_txn_hash.hex()
def pull(signer: str, target: str, autolock: bool, amount: float, escrow: float, nonce: int): logging.debug( f'pull() signer: {signer} target: {target} autolock: {autolock} amount: {amount} ' f'escrow: {escrow} nonce: {nonce}' ) w3 = refresh_w3() lottery_addr = w3.toChecksumAddress(os.environ['LOTTERY']) gas_price = int(os.environ['DEFAULT_GAS']) funder_pubkey = get_secret(key=os.environ['PAC_FUNDER_PUBKEY_SECRET']) funder_privkey = get_secret(key=os.environ['PAC_FUNDER_PRIVKEY_SECRET']) lottery_contract = w3.eth.contract( abi=lottery_abi, address=lottery_addr, ) pull_txn = lottery_contract.functions.pull( signer, target, autolock, amount, escrow, ).buildTransaction( { 'chainId': 1, 'from': funder_pubkey, 'gas': 150000, 'gasPrice': w3.toWei(gas_price, 'gwei'), 'nonce': nonce, } ) logging.debug(pull_txn) pull_txn_signed = w3.eth.account.sign_transaction( pull_txn, private_key=funder_privkey, ) logging.debug(pull_txn_signed) logging.debug('Submitting pull transaction') pull_txn_hash = w3.eth.sendRawTransaction( pull_txn_signed.rawTransaction, ) logging.debug(f'Submitted pull transaction with hash: {pull_txn_hash.hex()}') return pull_txn_hash.hex()
def handler(request): storage_service = None if BUCKET_NAME: storage_service = EmailAttachmentStorageService(BUCKET_NAME) publish_service = MailPublishService(TOPIC_NAME, request) identifier = request.args.get("identifier", None) if identifier is None: raise ValueError("No email address specified.") credentials = EMAIL_ADDRESSES.get(identifier, None) if credentials is None: raise ValueError("No credentials found for given email address.") email_address = credentials["email"] password = get_secret(PROJECT_ID, credentials["secret_id"]) email_service = EWSEmailService( email_address=email_address, password=password, folder=credentials.get("folder", None), alias=credentials.get("alias", None), ) emails = email_service.retrieve_unread_emails() for email in emails: logging.info("Processing email {} from sender {}".format( email.subject, email.sender)) try: publish_and_mark(storage_service, publish_service, email, identifier) except Exception as e: if ERROR_EMAIL_ADDRESS: logging.info( "Error processing email '{}' in mailbox {}. Forwarding to {}" .format( email.subject, credentials.get("alias", email_address), ERROR_EMAIL_ADDRESS, ), exc_info=True, ) email.forward(ERROR_EMAIL_ADDRESS, None, ERROR_EMAIL_MESSAGE) email.mark_as_read() else: logging.error( "Error processing email '{}' in mailbox {} because of {}". format(email.subject, credentials.get("alias", email_address), e), exc_info=True, )
def approve(spender: str, amount: float, nonce: int, gas_price: float = float(os.environ['DEFAULT_GAS'])): logging.debug( f'approve() spender: {spender} amount: {amount} gas_price: {gas_price} nonce: {nonce}' ) w3 = refresh_w3() funder_pubkey = get_secret(key=os.environ['PAC_FUNDER_PUBKEY_SECRET']) funder_privkey = get_secret(key=os.environ['PAC_FUNDER_PRIVKEY_SECRET']) token_addr = w3.toChecksumAddress(os.environ['TOKEN']) token_contract = w3.eth.contract( abi=token_abi, address=token_addr, ) approve_txn = token_contract.functions.approve( spender, amount, ).buildTransaction({ 'chainId': 1, 'from': funder_pubkey, 'gas': 50000, 'gasPrice': w3.toWei(gas_price, 'gwei'), 'nonce': nonce, }) logging.debug(f'approve_txn: {approve_txn}') approve_txn_signed = w3.eth.account.sign_transaction( approve_txn, private_key=funder_privkey, ) logging.debug(f'approve_txn_signed: {approve_txn_signed}') approve_txn_hash = w3.eth.sendRawTransaction( approve_txn_signed.rawTransaction) logging.debug( f'Submitted approve transaction with hash: {approve_txn_hash.hex()}') return approve_txn_hash.hex()
def generate_config( secret: str = None, curator: str = 'partners.orch1d.eth', protocol: str = 'orchid', funder: str = get_secret(key=os.environ['PAC_FUNDER_PUBKEY_SECRET']), ) -> str: if secret is not None: return f'account = {{curator:"{curator}", protocol: "{protocol}", \ funder: "{funder}", secret: "{secret}"}};' else: return f'account = {{curator:"{curator}", protocol: "{protocol}", \
def __init__(self): """Authenticate email server and prepare configuration""" # AWS access ACCESS_KEY = utils.get_secret("ACCESS_KEY_ID", "aws") SECRET_KEY = utils.get_secret("SECRET_ACCESS_KEY", "aws") AWS_REGION = utils.get_secret("REGION", "aws") # Create a new SES resource and specify a region. self.client = b3.client('ses', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY, region_name = AWS_REGION) # Sender, receiver self.SENDER = utils.get_secret("sender", "email") recipients = utils.get_secret("receiver", "email") self.RECEIVERS = recipients.split(",") # Config self.CHARSET = "UTF-8"
class DefaultConfig(object): """Defaults for the configuration objects.""" DEBUG = True TESTING = False CSRF_ENABLED = True PERMANENT_SESSION = True PERMANENT_SESSION_LIFETIME = 86400 SESSION_COOKIE_HTTPONLY = True LOGGER_NAME = "sso-dashboard" SECRET_KEY = get_secret('sso-dashboard.secret_key', {'app': 'sso-dashboard'}) SERVER_NAME = get_secret('sso-dashboard.server_name', {'app': 'sso-dashboard'}) S3_BUCKET = get_secret('sso-dashboard.s3_bucket', {'app': 'sso-dashboard'}) CDN = 'https://cdn.{SERVER_NAME}'.format(SERVER_NAME=SERVER_NAME) FORBIDDEN_PAGE_PUBLIC_KEY = base64.b64decode( get_secret('sso-dashboard.forbidden_page_public_key', {'app': 'sso-dashboard'}) )
def query_indexa(endpoint): """Raw function for querying indexa""" url = f"{BASE_URL}/{endpoint}" log.info(f"Querying '{url}'") token = u.get_secret(TOKEN_NAME) res = requests.get(url, headers={"X-AUTH-TOKEN": token}) res.raise_for_status() return res.json()
def main(event, context): stage = os.environ['STAGE'] body = json.loads(event.get('body', {})) if is_true(body.get('debug', '')): configure_logging(level="DEBUG") logging.debug(f'recycle() stage:{stage}') logging.debug(f'event: {event}') logging.debug(f'context: {context}') logging.debug(f'body: {body}') funder = toChecksumAddress(address=body.get('funder', '')) signer = toChecksumAddress(address=body.get('signer', '')) password = body.get('password', '') if password != get_secret(key=os.environ['RECYCLE_KEY']): return incorrect_password() pac_funder = get_secret(key=os.environ['PAC_FUNDER_PUBKEY_SECRET']) if funder != pac_funder: return invalid_funder(funder, pac_funder) funder_keys = keys(funder) if signer == '' or signer not in funder_keys: return invalid_signer(signer) amount, escrow, unlock = look(funder, signer) amount_threshold = float("inf") escrow_threshold = float("inf") if amount > amount_threshold: return amount_too_high(amount, amount_threshold) if escrow > escrow_threshold: return escrow_too_high(escrow, escrow_threshold) store_account(funder, signer, unlock) return account_queued_response()
def get_account_( price: float) -> Tuple[Optional[str], Optional[str], Optional[str]]: logging.debug(f'get_account_ price:{price}') dynamodb = boto3.resource('dynamodb') table = dynamodb.Table(os.environ['TABLE_NAME']) response = random_scan(table, price) ret = None signer_pubkey = '0xTODO' epoch_time = int(time.time()) for item in response['Items']: if float(price) == float(item['price']): signer_pubkey = item['signer'] config = item['config'] push_txn_hash = item['push_txn_hash'] creation_etime = item.get('creation_etime', 0) age = epoch_time - creation_etime # check status - make sure pot is ready #status = item['status'] status = get_transaction_status(push_txn_hash) if ((status != 'confirmed') and (age < 3600)): logging.debug( f'Skipping account ({push_txn_hash}) with status: {status} age: {age}' ) continue logging.debug( f'Found potential account ({push_txn_hash}) status: {status} age:{age} config: {config}' ) key = { 'price': item['price'], 'signer': signer_pubkey, } delete_response = table.delete_item(Key=key, ReturnValues='ALL_OLD') if (delete_response['Attributes'] is not None and len(delete_response['Attributes']) > 0): balance, escrow = look(funder=get_secret( key=os.environ['PAC_FUNDER_PUBKEY_SECRET']), signer=signer_pubkey) # update succeeded if ((status == 'confirmed') and (escrow > get_min_escrow())): ret = push_txn_hash, config, signer_pubkey break else: logging.debug( f'broken account: {push_txn_hash} status: {status} age: {age} balance: {balance} deleted and skipped' ) else: logging.debug('Account was already deleted!') if ret: return ret return None, None, None
class DefaultConfig(object): """Defaults for the configuration objects.""" DEBUG = True LOG_LEVEL = logging.DEBUG PERMANENT_SESSION = True PERMANENT_SESSION_LIFETIME = 86400 SECRET_KEY = get_secret('accessproxy.flask_secret', {'app': 'accessproxy'}) SESSION_COOKIE_HTTPONLY = True SESSION_COOKIE_SECURE = True SESSION_TYPE = 'filesystem' SESSION_FILE_THRESHOLD = 5000 SESSION_FILE_DIR = '/tmp/accessproxy/sessions/' SESSION_FILE_MODE = 0o600 REVERSE_PROXY_COOKIE_NAME = 'session' CA_USER_SECRET_KEY = get_secret('accessproxy.ca_user_key', {'app': 'accessproxy'}) CA_USER_PUBLIC_KEY = get_secret('accessproxy.ca_user_key_pub', {'app': 'accessproxy'})
def add_user(user, company, password): retval = False try: users = pymongo.Connection().sds.users except: print 'Couldn\'t connect to SDS db' return retval secret = utils.get_secret('keyfile') enc_password = utils.encrypt(password, secret) o = {'password': enc_password, 'u_and_c': user+'__'+company} users.insert(o) encoded = base64.b64encode('%s__%s:%s' % (user, company, password)) return encoded
def add_user(user, company, password): retval = False try: users = pymongo.Connection().sds.users except: print 'Couldn\'t connect to SDS db' return retval secret = utils.get_secret('keyfile') enc_password = utils.encrypt(password, secret) o = {'password': enc_password, 'u_and_c': user + '__' + company} users.insert(o) encoded = base64.b64encode('%s__%s:%s' % (user, company, password)) return encoded
def handle(event=None, context={}): os.environ["CIS_OAUTH2_CLIENT_ID"] = get_secret( 'cis_ldap_publisher.client_id', dict(app='cis_ldap_publisher')) os.environ["CIS_OAUTH2_CLIENT_SECRET"] = get_secret( 'cis_ldap_publisher.client_secret', dict(app='cis_ldap_publisher')) people = ldapfroms3.People() people.connect() people_json = people.all boto_session = boto3.session.Session(region_name='us-west-2') cis_publisher_session = assume_role_session() person_api = Person( person_api_config={ 'audience': os.getenv('CIS_PERSON_API_AUDIENCE'), 'client_id': os.getenv('CIS_OAUTH2_CLIENT_ID'), 'client_secret': os.getenv('CIS_OAUTH2_CLIENT_SECRET'), 'oauth2_domain': os.getenv('CIS_OAUTH2_DOMAIN'), 'person_api_url': os.getenv('CIS_PERSON_API_URL'), 'person_api_version': os.getenv('CIS_PERSON_API_VERSION') }) threads = [] for email, data_fields in people_json.items(): ldap_json = data_fields t = threading.Thread(target=publish, args=[ email, boto_session, cis_publisher_session, ldap_json, person_api ]) threads.append(t) t.start() for thread in threads: thread.join()
def handle(event=None, context={}): boto_session = boto3.session.Session(region_name='us-west-2') hris_json = hris.HrisJSON(boto_session) hr_data = hris_json.load() boto_session = boto3.session.Session(region_name='us-west-2') cis_publisher_session = assume_role_session() hris_json = hris.HrisJSON(boto_session) # Load the file of HRIS Data. os.environ["CIS_OAUTH2_CLIENT_ID"] = get_secret( 'cis_hris_publisher.client_id', dict(app='cis_hris_publisher')) os.environ["CIS_OAUTH2_CLIENT_SECRET"] = get_secret( 'cis_hris_publisher.client_secret', dict(app='cis_hris_publisher')) person_api = Person( person_api_config={ 'audience': os.getenv('CIS_PERSON_API_AUDIENCE'), 'client_id': os.getenv('CIS_OAUTH2_CLIENT_ID'), 'client_secret': os.getenv('CIS_OAUTH2_CLIENT_SECRET'), 'oauth2_domain': os.getenv('CIS_OAUTH2_DOMAIN'), 'person_api_url': os.getenv('CIS_PERSON_API_URL'), 'person_api_version': os.getenv('CIS_PERSON_API_VERSION') }) threads = [] for record in hr_data.get('Report_Entry'): t = threading.Thread(target=publish, args=[ record, boto_session, cis_publisher_session, hris_json, person_api ]) threads.append(t) t.start() for thread in threads: thread.join()