def to_datauri(mimetype, data, charset: str = 'utf-8', base64: bool = False, binary: bool = True): """ Convert data to data URI. :param mimetype: MIME types (e.g. 'text/plain','image/png' etc.) :param data: Data representations. :param charset: Charset may be any character set registered with IANA :param base64: Used to encode arbitrary octet sequences into a form that satisfies the rules of 7bit. Designed to be efficient for non-text 8 bit and binary data. Sometimes used for text data that frequently uses non-US-ASCII characters. :param binary: :return: """ parts = ['data:', mimetype] if charset is not None: parts.extend([';charset=', charset]) if base64: parts.append(';base64') from base64 import encodebytes as encode64 if binary: encoded_data = encode64(data).decode(charset).replace('\n', '').strip() else: encoded_data = encode64(data).strip() else: from urllib.parse import quote_from_bytes, quote if binary: encoded_data = quote_from_bytes(data) else: encoded_data = quote(data) parts.extend([',', encoded_data]) return ''.join(parts)
def make(cls, mimetype, charset, base64, data): parts = ['data:'] if mimetype is not None: if not _MIMETYPE_RE.match(mimetype): raise InvalidMimeType("Invalid mimetype: %r" % mimetype) parts.append(mimetype) if charset is not None: if not _CHARSET_RE.match(charset): raise InvalidCharset("Invalid charset: %r" % charset) parts.extend([';charset=', charset]) if base64: parts.append(';base64') if BYTES: _charset = charset or 'utf-8' if isinstance(data, bytes): _data = data else: _data = bytes(data, _charset) encoded_data = encode64(_data).decode(_charset).strip() else: encoded_data = encode64(data).strip() else: encoded_data = quote(data) parts.extend([',', encoded_data]) return cls(''.join(parts))
def md5_64(self): hash = encode64(hashlib.md5(self.password).digest()) self.out['md5_64'] = { 'header': '{md5_64}', 'salt': None, 'hash': hash } return hash
def sha1_64(self): hash = encode64(hashlib.sha1(self.password).digest()) self.out['sha1_64'] = { 'header': '{sha1_64}', 'salt': None, 'hash': hash } return hash
def base64(self): hash = encode64(self.password) self.out['b64'] = { 'header': '{b64}', 'salt': None, 'hash': hash } return hash
def to_datauri(mimetype, data, charset: str = 'utf-8', base64: bool = False, binary: bool = True): parts = ['data:', mimetype] if charset is not None: parts.extend([';charset=', charset]) if base64: parts.append(';base64') from base64 import encodebytes as encode64 if binary: encoded_data = encode64(data).decode(charset).replace('\n', '').strip() else: encoded_data = encode64(data).strip() else: from urllib.parse import quote_from_bytes, quote if binary: encoded_data = quote_from_bytes(data) else: encoded_data = quote(data) parts.extend([',', encoded_data]) return ''.join(parts)
def ssha(self): s = self.salt or self._gen_random() h = hashlib.sha1(self.password) h.update(s) hash = encode64(h.digest() + s) self.out['ssha'] = { 'header': '{ssha}', 'salt': s, 'hash': hash } return hash
def make_datauri(self, mimetype, data, binary=True): parts = ['data:', mimetype] if self.charset is not None: parts.extend([';charset=', self.charset]) if self.base64: parts.append(';base64') from base64 import encodebytes as encode64 if binary: encoded_data = encode64(data).decode(self.charset).replace('\n', '').strip() else: encoded_data = encode64(data).strip() else: from urllib.parse import quote_from_bytes, quote if binary: encoded_data = quote_from_bytes(data) else: encoded_data = quote(data) parts.extend([',', encoded_data]) return ''.join(parts)
def post(self): args = self.parser.parse_args() operator_id = args["operator_id"] 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."} ) # Send Management the Operator id and get Surrogate_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) surrogate_id = loads(result.text)["surrogate_id"] # Link surrogate_id to the user def link_surrogate_id(surrogate_id, user_id, operator_id): debug_log.info("We got surrogate_id {} for user_id {} on operator {}".format(surrogate_id, user_id, operator_id)) self.helpers.storeSurrogateJSON(user_id, surrogate_id, operator_id) link_surrogate_id(surrogate_id, user_id, operator_id) # Redirect user to Operator UI service_id = settings.SERVICE_ID return_url = "http://"+request.headers["HOST"]+"/" #TODO: less hardcoded stuff operator_login_url = self.helpers.get_operator_login_url(operator_id) operator_endpoint = "{}".format(operator_login_url) operator_query = "?surrogate_id={}&service_id={}&return_url={}&linkingFrom={}".format( # TODO: Get return url from somewhere surrogate_id, service_id, encode64(return_url), "Service") debug_log.info("Redirect url with parameters:\n{}{}\nSurrogate_id is: {}".format(operator_endpoint, operator_query, surrogate_id)) response = make_response(redirect(operator_endpoint + operator_query)) return response
def encodex(x): from base64 import urlsafe_b64encode as encode64 x_url = encode64(x.encode()) return x_url
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)