def signature_validation_with_ids(params, api_secret): """ проверка подписи входящих get параметров c ids параметрами :param params: FLASK request.args.items(multi=True) для выборки одинаковых ключей :param api_secret: API secret key (app info) вашего public app с акаунта partner :return: bool """ # достаем ids ids = [] temp_params = [] for param in params: if param[0] == 'ids[]': ids.append(param[1]) else: temp_params.append(param) if ids: params = temp_params ids = ['"{}"'.format(str(row)) for row in ids] ids = ', '.join(ids) ids = '[' + ids + ']' params.append(('ids', ids)) sorted_params = OrderedDict(sorted(params, key=lambda t: t[0])) hmac_param = sorted_params.pop('hmac') sorted_params = ['{}={}'.format(k, sorted_params[k]) for k in sorted_params] sorted_params = '&'.join(sorted_params) h = hmac.new(api_secret.encode('utf-8'), msg=sorted_params.encode('utf-8'), digestmod=hashlib.sha256).hexdigest() return hmac.compare_digest(hmac_param, h)
def write_plugin(plugin): """Write a plugin""" data = OrderedDict(zip(DEFAULT_ORDER, [None] * len(DEFAULT_ORDER))) with open(plugin['plugin'], "rb") as inp: data.update(json.loads(inp.read().decode('utf-8'))) # remove unset values for key, value in list(data.items()): if value is None: del data[key] # import scripts for fun in ('process', 'resolve'): if fun not in plugin: continue try: with open(plugin[fun]) as src: data[fun] = src.read() except IOError as ex: print("Could not open {0} file {1}: {2}". format(fun, plugin[fun], ex), file=sys.stderr) # generate JSON data = json.dumps(data, indent=4, separators=(',', ': ')) count = 1 while count > 0: data, count = RE_INDENT.subn('\\1\t', data) # write plugin file with open(plugin['plugin'], 'wb') as outp: outp.write(data.encode('utf-8'))
def create_signed_url(file, expires=60, secure=False, private_cloudfront=False, expires_at=None): if not private_cloudfront: generator = QueryStringAuthGenerator( settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY, calling_format=getattr(settings, 'AWS_CALLING_FORMAT', CallingFormat.SUBDOMAIN), is_secure=secure) generator.set_expires_in(expires) return generator.generate_url( 'GET', settings.AWS_STORAGE_BUCKET_NAME, file ) url = settings.MEDIA_URL if not isinstance(settings.MEDIA_URL, CloudFrontURLs): url = CloudFrontURLs(settings.MEDIA_URL) url = url.get_url(file, force_https=True if secure else False) if expires_at is None: expires = int(time.time() + expires) else: expires = expires_at # Use OrderedDict to keep things predictable and testable policy = OrderedDict() policy['Resource'] = url policy['Condition'] = { 'DateLessThan': { 'AWS:EpochTime': expires } } policy = { 'Statement': [ policy ] } policy = json.dumps(policy, separators=(',',':')) key = settings.CUDDLYBUDDLY_STORAGE_S3_KEY_PAIR dig = SHA.new() dig.update(policy.encode('utf-8')) sig = PKCS1_v1_5.new(RSA.importKey(key[1])) sig = sig.sign(dig) sig = base64.b64encode(sig).decode('utf-8') sig = sig.replace('+', '-').replace('=', '_').replace('/', '~') return '%s%sExpires=%s&Signature=%s&Key-Pair-Id=%s' % ( url, '&' if '?' in url else '?', expires, sig, key[0] )
def makeTable(environ, start_response): r = requests.get(url) stateAll = r.json() state = OrderedDict() state['SOC'] = str(stateAll['USOC']) + '%' state['Production'] = str(stateAll['Production_W']) + 'W' state['Consumption'] = str(stateAll['Consumption_W']) + 'W' state['Battery'] = str(stateAll['Pac_total_W']) + 'W' state['GridFeedIn'] = str(stateAll['GridFeedIn_W']) + 'W' state['Timestamp'] = stateAll['Timestamp'] build_direction = "LEFT_TO_RIGHT" state = json2table.convert(state, build_direction=build_direction) start_response('200 OK', [('Content-Type', 'text/html')]) if stateAll['GridFeedIn_W'] < -200: color = b'Red' elif stateAll['Pac_total_W'] > 50: color = b'Orange' elif stateAll['Pac_total_W'] < -50: color = b'green' elif stateAll['GridFeedIn_W'] > 200: color = b'DarkGreen' else: color = b'SkyBlue' return [ b""" <html> <head> <style> table { border-collapse: collapse; } th, td { text-align: left; padding: 8px; } tr:nth-child(even) {background-color: #f2f2f2;} </style> </head> <body bgcolor="%(bgcolor)s"> %(table)s </body> </html>""" % { b"table": state.encode('utf-8'), b"bgcolor": color } ]
def _ascii_encoder(obj): """Convert UNICODE strings to ASCII recursively.""" if isinstance(obj, dict): obj = OrderedDict(sorted([(k.encode('ascii'), _ascii_encoder(v)) for (k, v) in obj.iteritems()])) elif isinstance(obj, list): obj = [_ascii_encoder(i) for i in obj] elif isinstance(obj, unicode): obj = obj.encode('ascii') else: assert isinstance(obj, str) return obj
def signature_validation(params, api_secret): """ проверка подписи входящих get параметров :param params: request.args.items() :param api_secret: API secret key (app info) вашего public app с акаунта partner :return: bool """ sorder_params = OrderedDict(sorted(params, key=lambda t: t[0])) hmac_param = sorder_params.pop('hmac') sorder_params = ['{}={}'.format(k, sorder_params[k]) for k in sorder_params] sorder_params = '&'.join(sorder_params) h = hmac.new(api_secret.encode('utf-8'), msg=sorder_params.encode('utf-8'), digestmod=hashlib.sha256).hexdigest() return hmac.compare_digest(hmac_param, h)