def do_POST(self): try: request = json.loads(self._read_request()) if 'type' not in request.keys(): request['type'] = 'GET' if 'url' not in request.keys() or \ (request['type'] == 'POST' and 'content' not in request.keys()): return self._return_error('invalid json') except: return self._return_error('invalid json') new_request = urllib.request.Request( url=request['url'], data=bytes(request.get('content'), 'UTF-8') if 'content' in request else None, headers=request.get('headers', {}), method=request['type']) self.open_follow(new_request, timeout=request.get('timeout', 1))
def __generate_url(self, request): baseUrl = "http://" + self.vnfmAddress + "/client/api?" requestUrl = '&'.join([ '='.join([k, urllib.parse.quote_plus(request[k])]) for k in request.keys() ]) signatureStr = '&'.join([ '='.join([ k.lower(), urllib.parse.quote_plus(request[k].lower().replace('+', '%20')) ]) for k in sorted(request.keys()) ]) signatureUrl = urllib.parse.quote_plus( base64.encodestring( hmac.new(self.secretKey.encode("utf-8"), signatureStr.encode("utf-8"), hashlib.sha1).digest()).strip()) return baseUrl + requestUrl + '&signature=' + signatureUrl
def __init__(self, id, tunnel, remote_addr, start, duration, request, response): self.id = id self.remote_addr = remote_addr self.start = datetime.datetime.strptime(start, "%Y-%m-%dT%H:%M:%SZ") self.duration = duration self.request = namedtuple("Request", request.keys())(**request) self.response = namedtuple("Response", response.keys())(**response) try: data = api("tunnels/%s" % tunnel) self.tunnel = Tunnel(data["config"], data["name"], data["uri"], data["public_url"], data["proto"], data["metrics"]) except Exception: self.tunnel = None
''' daily '10:03'(3:10) weekly '10:03:1'(Sunday 3:10) monthly '10:03:15'(15th 3:10) ''' #request['schedule'] = '0:03' #daily request['schedule'] = '40:03:1' #weekly request['schedule'] = '30:03:1' #monthly request['timezone'] = 'JST' #request['']='' request['apikey'] = sys.argv[1] secretkey = sys.argv[2] request_str = '&'.join([ '='.join([k, urllib.parse.quote_plus(request[k])]) for k in request.keys() ]) sig_str = '&'.join([ '='.join([ k.lower(), urllib.parse.quote_plus(request[k].lower().replace('+', '%20')) ]) for k in sorted(request.keys()) ]) digest = hmac.new(secretkey.encode('utf-8'), sig_str.lower().encode('utf-8'), hashlib.sha1).digest() sig = urllib.parse.quote_plus(base64.b64encode(digest).decode('utf-8').strip()) req = baseurl + request_str + '&signature=' + sig
def l_registration_endpoint(self, request, authn=None, **kwargs): _log_debug = logger.debug _log_info = logger.info _log_debug("@registration_endpoint") request = RegistrationRequest().deserialize(request, "json") _log_info("registration_request:%s" % request.to_dict()) resp_keys = list(request.keys()) try: request.verify() except MessageException as err: if "type" not in request: return self._error(error="invalid_type", descr="%s" % err) else: return self._error(error="invalid_configuration_parameter", descr="%s" % err) _keyjar = self.server.keyjar # create new id och secret client_id = rndstr(12) while client_id in self.cdb: client_id = rndstr(12) client_secret = secret(self.seed, client_id) _rat = rndstr(32) reg_enp = "" for endp in self.endpoints: if isinstance(endp, DynamicClientEndpoint): reg_enp = "%s%s" % (self.baseurl, endp.etype) self.cdb[client_id] = { "client_id": client_id, "client_secret": client_secret, "registration_access_token": _rat, "registration_client_uri": "%s?client_id=%s" % (reg_enp, client_id), "client_secret_expires_at": utc_time_sans_frac() + 86400, "client_id_issued_at": utc_time_sans_frac()} self.cdb[_rat] = client_id _cinfo = self.do_client_registration(request, client_id, ignore=["redirect_uris", "policy_url", "logo_url"]) if isinstance(_cinfo, Response): return _cinfo args = dict([(k, v) for k, v in list(_cinfo.items()) if k in RegistrationResponse.c_param]) self.comb_redirect_uris(args) response = RegistrationResponse(**args) self.keyjar.load_keys(request, client_id) # Add the key to the keyjar if client_secret: _kc = KeyBundle([{"kty": "oct", "key": client_secret, "use": "ver"}, {"kty": "oct", "key": client_secret, "use": "sig"}]) try: _keyjar[client_id].append(_kc) except KeyError: _keyjar[client_id] = [_kc] self.cdb[client_id] = _cinfo _log_info("Client info: %s" % _cinfo) logger.debug("registration_response: %s" % response.to_dict()) return Response(response.to_json(), content="application/json", headers=[("Cache-Control", "no-store")])
import urllib.request import urllib.parse import hashlib import hmac import base64 baseurl='https://tky001b.pf.gmocloud.com/client/api?' request={} request['command']='listUsers' request['response']='json' request['apikey']='' secretkey='' request_str='&'.join(['='.join([k,urllib.parse.quote_plus(request[k])]) for k in request.keys()]) sig_str='&'.join(['='.join([k.lower(),urllib.parse.quote_plus(request[k].lower().replace('+','%20'))])for k in sorted(request.keys())]) digest=hmac.new(secretkey.encode('utf-8'),sig_str.lower().encode('utf-8'),hashlib.sha1).digest() sig=urllib.parse.quote_plus(base64.b64encode(digest).decode('utf-8').strip()) req=baseurl+request_str+'&signature='+sig res=urllib.request.urlopen(req) result=res.read() print(result)
def DebugWeb(environ, start_response): request = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ) templateDict = {} templateDict["importChemDB"] = "" templateDict["importOEChem"] = "" templateDict["importPsycoPg"] = "" if "importChemDB" in request: templateDict["importChemDB"] = "checked" if "importOEChem" in request: templateDict["importOEChem"] = "checked" if "importPsycoPg" in request: templateDict["importPsycoPg"] = "checked" html =\ """ <html> <body> <form action="DebugWeb.py" method=get name="debugForm"> <input type=text name="smiles"> <A HREF="Draw structure" onClick="popup = window.open('../JMEPopupWeb.py?parentForm=debugForm&smilesField=smiles&smiles='+ document.forms[0].smiles.value +'&JMEPopupWeb=True','jmePopup','resizable=yes,width=400,height=400'); popup.focus(); return false;"><IMG SRC="../../resource/edit.gif" STYLE="width: 19; height: 17; border: 0" alt="Draw structure"></A> <br> <textarea name="testArea"></textarea> <A HREF="Draw structure" onClick="popup = window.open('../JMEPopupWeb.py?parentForm=debugForm&smilesField=testArea','jmePopup','resizable=yes,width=400,height=400'); popup.focus(); return false;"><IMG SRC="../../resource/edit.gif" STYLE="width: 19; height: 17; border: 0" alt="Draw structure"></A> <br> <select multiple name="testMulti" size=4> <option>A <option>B <option>C <option>D <option>E <option>F <option>G </select><br> <input type=text name="repeater" value="joe"><br> <input type=text name="repeater" disabled value="blah"><br> <input type=text name="repeater" value="mama"><br> Import: <ul> <li><input type=checkbox name="importChemDB" value="checked" %(importChemDB)s> Misc ChemDB Module (requires web server PYTHONPATH to be set to CHEM's parent directory) <li><input type=checkbox name="importOEChem" value="checked" %(importOEChem)s> OEChem (requires OEChem installation and web server OE_LICENSE to be set to license file name and location) <li><input type=checkbox name="importPsycoPg" value="checked" %(importPsycoPg)s> PsycoPg </ul> <input type=file name="testFile"><br> <input type=submit name="JMEPopupWeb"><br> </form> """ % templateDict # Test if external imports work: if "importChemDB" in request: import CHEM.Common.Env html += "<i>Successfully imported a CHEM module</i><br>" if "importOEChem" in request: from openeye.oechem import OEGraphMol mol = OEGraphMol() html += "<i>Successfully imported a OEChem module</i><br>" if "importPsycoPg" in request: import psycopg2 html += "<i>Successfully imported psycopg2 module</i><br>" html += "Request Parameters" html += "<table border=1>" html += "<tr><th>Key</th><th>Value</th><th>Filename and Type</th></tr>" for key in list(request.keys()): field = request[key] if not isinstance(field, list): field = [field] # Convert to list of size 1 for item in field: html += "<tr><td>%s</td><td><pre>%s</pre></td><td>%s<br><br>%s</td></tr>" % ( key, item.value, item.filename, item.type) html += "</table>" html += "Paths (PYTHONPATH)" html += "<ul>" for path in sys.path: html += "<li>" + path + "</li>" html += "</ul>\n" #cgi.test() html += "<b>Request</b><br>" html += str(request) html += "<br><b>Environment Variables</b>" html += "<table border=1>" html += "<tr><th>Key</th><th>Value</th></tr>" keyList = list(os.environ.keys()) keyList.sort() for key in keyList: html += "<tr><td>%s</td><td>%s</td></tr>" % (key, os.environ[key]) html += "</table>" html += "</body>" html += "</html>" status = '200 OK' response_headers = [('Content-type', 'text/html'), ('Content-Length', str(len(html)))] start_response(status, response_headers) return html
def l_registration_endpoint(self, request, authn=None, **kwargs): _log_debug = logger.debug _log_info = logger.info _log_debug("@registration_endpoint") request = RegistrationRequest().deserialize(request, "json") _log_info("registration_request:%s" % request.to_dict()) resp_keys = list(request.keys()) try: request.verify() except MessageException as err: if "type" not in request: return self._error(error="invalid_type", descr="%s" % err) else: return self._error(error="invalid_configuration_parameter", descr="%s" % err) _keyjar = self.server.keyjar # create new id och secret client_id = rndstr(12) while client_id in self.cdb: client_id = rndstr(12) client_secret = secret(self.seed, client_id) _rat = rndstr(32) reg_enp = "" for endp in self.endpoints: if isinstance(endp, DynamicClientEndpoint): reg_enp = "%s%s" % (self.baseurl, endp.etype) self.cdb[client_id] = { "client_id": client_id, "client_secret": client_secret, "registration_access_token": _rat, "registration_client_uri": "%s?client_id=%s" % (reg_enp, client_id), "client_secret_expires_at": utc_time_sans_frac() + 86400, "client_id_issued_at": utc_time_sans_frac() } self.cdb[_rat] = client_id _cinfo = self.do_client_registration( request, client_id, ignore=["redirect_uris", "policy_url", "logo_url"]) if isinstance(_cinfo, Response): return _cinfo args = dict([(k, v) for k, v in list(_cinfo.items()) if k in RegistrationResponse.c_param]) self.comb_redirect_uris(args) response = RegistrationResponse(**args) self.keyjar.load_keys(request, client_id) # Add the key to the keyjar if client_secret: _kc = KeyBundle([{ "kty": "oct", "key": client_secret, "use": "ver" }, { "kty": "oct", "key": client_secret, "use": "sig" }]) try: _keyjar[client_id].append(_kc) except KeyError: _keyjar[client_id] = [_kc] self.cdb[client_id] = _cinfo _log_info("Client info: %s" % _cinfo) logger.debug("registration_response: %s" % response.to_dict()) return Response(response.to_json(), content="application/json", headers=[("Cache-Control", "no-store")])