async def run(self, user): """ retrives invoices (payment requests) for current user and returns them with payment state based on gRPC query. Side Effect: adds true lnd invoices as paid in redis Internal invoices are marked as paid on payment send """ statement = DB_Invoice.query.where( or_( and_(DB_Invoice.payee == user.username, self._payee), and_(DB_Invoice.payer == user.username, self._payer), )).order_by(DB_Invoice.timestamp.desc()) if self._limit > 0: statement = statement.limit(self._limit) statement = statement.offset(self._offset) invoices = [] async with GINO.db.transaction(): async for invoice in statement.gino.iterate(): if not invoice.paid: # if not paid check lnd to see if its paid in lnd db req = ln.PaymentHash( r_hash=decode64(invoice.payment_hash.encode("utf-8"))) lookup_info = await LND.stub.LookupInvoice(req) if lookup_info.state == 1: # invoice is paid update state in db await invoice.update( paid=True, paid_at=lookup_info.settle_date).apply() if self._filter(invoice): invoices.append(invoice) # TODO convert to asynchronous generator? return invoices
def decodex(x): from base64 import urlsafe_b64decode as decode64 #x_decoded = bytes.decode(decode64(x.decode())) x_ = x.replace("b'", "") x_byte = x_.encode() x__ = decode64(x_byte.decode()) x_decoded = bytes.decode(x__) return x_decoded
def _parse(self): match = _DATA_URI_RE.match(self) if not match: raise InvalidDataURI("Not a valid data URI: %r" % self) mimetype = match.group('mimetype') or None name = match.group('name') or None charset = match.group('charset') or None if match.group('base64'): if BYTES: _charset = charset or 'utf-8' _data = bytes(match.group('data'), _charset) data = decode64(_data) else: data = decode64(match.group('data')) else: data = unquote(match.group('data')) return mimetype, name, charset, bool(match.group('base64')), data
def decode_payload(payload): #sq.task("Fix possible incorrect padding in payload") payload += '=' * (-len(payload) % 4 ) # Fix incorrect padding of base64 string. debug_log.info("After padding fix :{}".format(payload)) #sq.task("Decode SLR payload and store it into object") debug_log.info(payload.encode()) content = decode64(payload.encode()) #sq.task("Load decoded payload as python dict") payload = loads(content.decode("utf-8")) debug_log.info("Decoded SLR payload:") debug_log.info(type(payload)) debug_log.info(dumps(payload, indent=2)) return payload
def recover_secret(self, *shares): xor_binary = self.binify_share(reduce(lambda a, e: a ^ e, shares)) if xor_binary == self.secret: base64.decode64(xor_binary)
def recover_secret(self, *shares): # NOTE: Whether the following XOR (^) needs to be bitwise or boolean is undetermined xor_binary = self.binify_share(reduce(lambda a, e: a ^ e, shares)) if xor_binary == self.secret: base64.decode64(xor_binary)
def post(self): args = self.parser.parse_args() def get_api_key(account_url=self.account_url + "account/api/v1.3/", user=None, password=None, endpoint="external/auth/user/"): debug_log.info( "\nFetching Account Key for account '{}' from endpoint: {}". format(user + ":" + password, account_url + endpoint)) api_json = get(account_url + endpoint, auth=(user, password)) #debug_log.info("Received following key:\n {}".format(api_json)) if api_json.ok: return loads(api_json.text) else: raise DetailedHTTPException( title="Authentication to Account failed.", status=403) # Check Account is valid account, this is dummy UI, this is dumm test. account_info = get_api_key(user=args["username"], password=args["pword"]) account_id = account_info["account_id"] account_api_key = account_info["Api-Key-User"] # Initialize all common variables surrogate_id = args["surrogate_id"] service_id = args["service_id"] return_url = args["return_url"] # Generate Code for session code = str(guid()) debug_log.info( "Session information contains: code {}, account id {} and service_id {}" .format(code, account_id, service_id)) debug_log.info("Store session_information to database") session_information = { code: { "account_id": account_id, "service_id": service_id, "user_key": account_api_key } } self.store_session(session_information) try: # Make request to register surrogate_id data = { "code": code, "operator_id": self.operator_id, "return_url": return_url, "surrogate_id": surrogate_id, } # Fetch service information: service_json = self.service_registry_handler.getService(service_id) service_domain = service_json["serviceInstance"][0][ "domain"] # Domain to Login of Service service_access_uri = service_json["serviceInstance"][0][ "serviceAccessEndPoint"]["serviceAccessURI"] service_linking_uri = "/slr/linking" service_url = service_domain + service_access_uri + service_linking_uri # Initiate Service Link Process debug_log.info("Sending linking request to Service at: {}".format( service_url)) linking_result = post(service_url, json=data) debug_log.debug("Service Linking resulted in:\n {}\n {}".format( linking_result.status_code, linking_result.text)) # If SLR was created success fully load it as a dictionary, on errors we delete session. if linking_result.ok: reply_json = loads(linking_result.text) else: self.helper.delete_session(code) raise DetailedHTTPException( title=linking_result.reason, status=linking_result.status_code, detail={"msg": linking_result.text}) debug_log.info( "Encoding json as reply to ui: \n{}".format(reply_json)) if isinstance(reply_json, dict): reply_json = dumps(reply_json) self.helper.delete_session(code) return redirect("{}?results={}".format( decode64(args["return_url"]), encode64(reply_json)), code=302) except DetailedHTTPException as e: self.helper.delete_session(code) raise e except Exception as e: self.helper.delete_session(code) raise DetailedHTTPException( status=500, exception=e, title="Something went wrong during service linking, try again." )
def post(self): def link_surrogate_id(json_response, user_id, operator_id): response_user_id = self.helpers.get_user_id_with_code(args["code"]) if response_user_id == user_id: pass else: raise DetailedHTTPException( status=403, detail={ "msg": "Response was for different user_id than expected." }, title="User ID mismatch.") debug_log.info("We got surrogate_id {} for user_id {}".format( json_response["surrogate_id"], user_id)) debug_log.info(dumps(json_response, indent=2)) self.helpers.storeSurrogateJSON(user_id, json_response["surrogate_id"], operator_id) return json_response["surrogate_id"] args = self.parser.parse_args() debug_log.info("Args contain:\n {}".format(dumps(args, indent=2))) debug_log.info(dumps(request.json, indent=2)) user_id = args["Email"] user_pw = args["Password"] if not valid_credentials(user_id, user_pw): raise DetailedHTTPException( status=401, detail={"msg": "Unauthorized, check your login credentials."}) code = args["code"] self.helpers.store_code_user({code: user_id}) debug_log.info("User logged in with id ({})".format(format(user_id))) endpoint = "/api/1.3/slr/surrogate_id" # TODO: This needs to be fetched from somewhere. data = {"user_id": user_id, "operator_id": args["operator_id"]} result = post("{}{}".format(current_app.config["SERVICE_MGMNT_URL"], endpoint), json=data) if not result.ok: raise DetailedHTTPException( status=result.status_code, detail={ "msg": "Something went wrong while posting to Service_Components Mgmnt to inform login was successful " "and its alright to generate Surrogate_ID ", "Error from Service_Components Mgmnt": loads(result.text) }, title=result.reason) debug_log.info(result.text) try: operator_id = args["operator_id"] surrogate_id = link_surrogate_id( loads(result.text), user_id, operator_id) # Returns surrogate_id for convenience endpoint = "/api/1.3/slr/linking" # TODO: This needs to be fetched from somewhere. data = { "code": code, "operator_id": args["operator_id"], "return_url": args["return_url"], "surrogate_id": surrogate_id, "user_id": user_id } linking_result = post("{}{}".format( current_app.config["SERVICE_MGMNT_URL"], endpoint), json=data) debug_log.debug("Service Linking resulted in:\n {}\n {}".format( linking_result.status_code, linking_result.text)) except Exception as e: raise e reply_json = loads(linking_result.text) debug_log.info("Encoding json as reply to ui: \n{}".format(reply_json)) if isinstance(reply_json, dict): reply_json = dumps(reply_json) return redirect("{}?results={}".format(decode64(args["return_url"]), encode64(reply_json)), code=302)