def blessings_get_post(): data_type = constants.blessings if request.method == 'GET': # check Accept header if not helpers.has_acceptable_mimetype(request.accept_mimetypes): return make_response( json.dumps({"Error": "The service does not support the specified response media type(s)"}), status.NOT_ACCEPTABLE, constants.json_header) # return results q_limit = int(request.args.get('limit', '5')) q_offset = int(request.args.get('offset', '0')) return make_response(helpers.get_all_from_store_json(data_type, request.url_root, q_limit, q_offset), status.OK, constants.json_header) elif request.method == 'POST': # check valid JWT for existing user user = helpers.verify(request.headers.get('Authorization')) if not user: return make_response(constants.invalid_jwt) # check valid request body is_valid, content, code = helpers.is_valid_request_body(request, constants.blessings_attr, True) if is_valid: content.update({'founder': {'id': str(user.key.id)}, 'unicorns': []}) blessing = helpers.add_to_store(data_type, content) return make_response(json.dumps(helpers.from_datastore(blessing, data_type, request.url_root)), status.CREATED, constants.json_header) else: return make_response(json.dumps(content), code, constants.json_header) else: return make_response(json.dumps({"Error": "Method not allowed"}), status.METHOD_NOT_ALLOWED, constants.json_header)
def register(): if request.method == 'POST': u = escape(request.form['username']) p = escape(request.form['password']) rp = escape(request.form['re_enter']) q = queries.find(u) p_match = helpers.verify(p, rp) hashed_p = generate_password_hash(p, "sha256") found = db.execute(q).fetchone() if found != None: flash(helpers.msgs(u)['logged_in']) return redirect(url_for("register")) if p_match == False: flash(helpers.msgs(u)['p_match']) return redirect(url_for("register")) # set session data to logged in session['username'] = u q = queries.register(u, hashed_p, p_match) db.execute(q[0], q[1]) db.commit() flash(helpers.msgs(u)['logged_in']) return redirect(url_for("index")) else: return render_template("register.html")
def boats_post(): owner = verify() if not owner: return json_response(401, error_msg='Invalid JWT') if 'application/json' in request.content_type: content = request.get_json() try: validate(instance=content, schema=constants.boats_schema) except: return resource_not_found_400( "The request object is missing at least one of the required attributes" ) if 'application/json' not in request.accept_mimetypes: return json_response( 406, error_msg='Content must be returned in JSON format') error_msg = name_validator(client, content, constants.boats) if not error_msg: new_boat = datastore.entity.Entity(key=client.key(constants.boats)) content['owner'] = owner payload = Boat(content) new_boat.update(payload.update_data()) client.put(new_boat) return jsonify(payload.api_return(new_boat.id)), 201 elif 'unique' in error_msg: return json_response(403, error_msg=f'{error_msg}') else: return json_response(400, error_msg=f'{error_msg}') return json_response(400, error_msg='Body must be in JSON format')
def loads_unload(load_id): owner = verify() if not owner: return json_response(401, error_msg='Invalid JWT') load = id_validator(client, load_id, constants.loads) if load: unload_load(client, load_id) return '', 204 return resource_not_found_404("No load with this load_id exists")
def boats_delete(boat_id): owner = verify() if not owner: return json_response(401, error_msg='Invalid JWT') boat = id_validator(client, boat_id, constants.boats) if boat: key = client.key(constants.boats, int(boat_id)) client.delete(key) return '', 204 return resource_not_found_404("No boat with this boat_id exists")
def blessings_get_put_patch_delete(id): if request.method in {'GET', 'PUT', 'PATCH', 'DELETE'}: # check valid JWT for existing user user = helpers.verify(request.headers.get('Authorization')) if request.method != 'GET' and not user: return make_response(constants.invalid_jwt) # check valid blessing id blessing = helpers.get_from_store(constants.blessings, id) if not blessing: return make_response(json.dumps({"Error": "No blessing with this blessing_id exists"}), status.NOT_FOUND, constants.json_header) # check if the JWT user is the same as the blessing's creator/founder if request.method != 'GET' and str(user.key.id) != blessing['founder']['id']: return make_response(json.dumps({"Error": "The provided credentials do not have permission to perform that action"}), status.FORBIDDEN, constants.json_header) # route-specific application behavior if request.method == 'GET': if not helpers.has_acceptable_mimetype(request.accept_mimetypes): return make_response(json.dumps({"Error": "The service does not support the specified response media type(s)"}), status.NOT_ACCEPTABLE, constants.json_header) else: return make_response(json.dumps(helpers.from_datastore(blessing, constants.blessings, request.url_root)), status.OK, constants.json_header) elif request.method == 'PUT': is_valid, content, code = helpers.is_valid_request_body(request, constants.blessings_attr, True) if is_valid: blessing.update({"name": content["name"], "habitat": content["habitat"], "description": content["description"]}) client.put(blessing) return make_response(json.dumps(helpers.from_datastore(blessing, constants.blessings, request.url_root)), status.OK, constants.json_header) else: return make_response(json.dumps(content), code, constants.json_header) elif request.method == 'PATCH': is_valid, content, code = helpers.is_valid_request_body(request, constants.blessings_attr, False) if is_valid: for attribute in constants.blessings_attr: if attribute in content: blessing.update({attribute: content[attribute]}) client.put(blessing) return make_response(json.dumps(helpers.from_datastore(blessing, constants.blessings, request.url_root)), status.OK, constants.json_header) else: return make_response(json.dumps(content), code, constants.json_header) elif request.method == 'DELETE': for u in blessing['unicorns']: unicorn = helpers.get_from_store(constants.unicorns, u['id']) unicorn['blessing'] = None client.put(unicorn) client.delete(blessing.key) return make_response("", status.NO_CONTENT, constants.json_header) else: return make_response(json.dumps({"Error": "Method not allowed"}), status.METHOD_NOT_ALLOWED, constants.json_header)
def unicorns_get_put_patch_delete(id): if request.method in {'GET', 'PUT', 'PATCH', 'DELETE'}: # check valid JWT for existing user user = helpers.verify(request.headers.get('Authorization')) if request.method != 'GET' and not user: return make_response(constants.invalid_jwt) # check valid unicorn id unicorn = helpers.get_from_store(constants.unicorns, id) if not unicorn: return make_response(json.dumps({"Error": "No unicorn with this unicorn_id exists"}), status.NOT_FOUND, constants.json_header) # check if the JWT user is the same as the unicorn's creator/friend if request.method != 'GET' and str(user.key.id) != unicorn['friend']['id']: return make_response(json.dumps({"Error": "The provided credentials do not have permission to perform that action"}), status.FORBIDDEN, constants.json_header) # route-specific application behavior if request.method == 'GET': if not helpers.has_acceptable_mimetype(request.accept_mimetypes): return make_response(json.dumps({"Error": "The service does not support the specified response media type(s)"}), status.NOT_ACCEPTABLE, constants.json_header) else: return make_response(json.dumps(helpers.from_datastore(unicorn, constants.unicorns, request.url_root)), status.OK, constants.json_header) elif request.method == 'PUT': is_valid, content, code = helpers.is_valid_request_body(request, constants.unicorns_attr, True) if is_valid: unicorn.update({"name": content["name"], "color": content["color"], "magic": content["magic"]}) client.put(unicorn) return make_response(json.dumps(helpers.from_datastore(unicorn, constants.unicorns, request.url_root)), status.OK, constants.json_header) else: return make_response(json.dumps(content), code, constants.json_header) elif request.method == 'PATCH': is_valid, content, code = helpers.is_valid_request_body(request, constants.unicorns_attr, False) if is_valid: for attribute in constants.unicorns_attr: if attribute in content: unicorn.update({attribute: content[attribute]}) client.put(unicorn) return make_response(json.dumps(helpers.from_datastore(unicorn, constants.unicorns, request.url_root)), status.OK, constants.json_header) else: return make_response(json.dumps(content), code, constants.json_header) elif request.method == 'DELETE': if unicorn['blessing']: blessing_id = unicorn["blessing"]["id"] helpers.remove_unicorn(blessing_id, id) client.delete(unicorn.key) return make_response("", status.NO_CONTENT, constants.json_header) else: return make_response(json.dumps({"Error": "Method not allowed"}), status.METHOD_NOT_ALLOWED, constants.json_header)
def ajax_validate(): data = None client_ip = request.remote_addr captcha_response = request.form['g-recaptcha-response'] if helpers.verify(config_dic["captcha_private_key"], captcha_response, client_ip): data = { "status": True, "msg": "Here's the email you were looking for", "email": config_dic["hidden_address"] } else: data = {"status": False, "msg": "reCAPTCHA test failed."} return jsonify(data)
def unicorns_put_delete(uid, bid): if request.method in {'PUT', 'DELETE'}: # check valid JWT for existing user user = helpers.verify(request.headers.get('Authorization')) if not user: return make_response(constants.invalid_jwt) # check valid unicorn and blessing id unicorn = helpers.get_from_store(constants.unicorns, uid) blessing = helpers.get_from_store(constants.blessings, bid) if not unicorn or not blessing: return make_response(json.dumps({"Error": "The specified unicorn and/or blessing do not exist"}), status.NOT_FOUND, constants.json_header) # check if the JWT user is the same as the unicorn's creator/friend if str(user.key.id) != unicorn['friend']['id']: return make_response( json.dumps({"Error": "The provided credentials do not have permission to perform that action"}), status.FORBIDDEN, constants.json_header) if request.method == 'PUT': if unicorn['blessing']: return make_response(json.dumps({"Error": "The unicorn is already assigned to a blessing"}), status.CONFLICT, constants.json_header) # add to unicorn unicorn.update({"blessing": {'id': bid}}) client.put(unicorn) # add to blessing blessing['unicorns'].append({'id': uid}) client.put(blessing) return make_response('', status.NO_CONTENT, constants.json_header) elif request.method == 'DELETE': if unicorn['blessing'] and unicorn['blessing']['id'] == bid: unicorn.update({'blessing': None}) client.put(unicorn) helpers.remove_unicorn(bid, uid) return make_response("", status.NO_CONTENT, constants.json_header) else: return make_response(json.dumps({"Error": "No unicorn with this unicorn_id is assigned to the blessing with this blessing_id"}), status.NOT_FOUND, constants.json_header) else: return make_response(json.dumps({"Error": "Method not allowed"}), status.METHOD_NOT_ALLOWED, constants.json_header)
def load_cargo(boat_id): owner = verify() if not owner: return json_response(401, error_msg='Invalid JWT') if 'application/json' in request.accept_mimetypes: content = request.get_json() try: validate(instance=content, schema=constants.load_boat_schema) except: return resource_not_found_400( "The request object is missing at least one of the required attributes" ) load_id = content["id"] boat_data = id_validator(client, boat_id, kind=constants.boats) load_data = id_validator(client, load_id, kind=constants.loads) if boat_data and load_data: if not load_data["carrier"]: boat = Boat(boat_data) load_carrier = { "id": load_id, "self": f"{request.url_root}loads/{load_id}" } load = Load(load_data) boat_carrier = { "id": boat_id, "name": boat_data["name"], "self": f"{request.url_root}/boats/{boat_id}" } load.add_carrier(boat_carrier) boat.loads.append(load_carrier) update_entity(client, boat_id, constants.boats, boat) update_entity(client, load_id, constants.loads, load) return json_response(204, error_msg='OK') return resource_not_found_400("Load already assigned to a boat") return resource_not_found_404( "The specified boat and/or load don’t exist") return json_response(406, error_msg='Content must be in JSON format')
def boats_patch(boat_id): owner = verify() if not owner: return json_response(401, error_msg='Invalid JWT') if 'application/json' in request.accept_mimetypes: boat_data = id_validator(client, boat_id, constants.boats) if boat_data: content = request.get_json() try: validate(instance=content, schema=constants.patch_schema) except: return resource_not_found_400( "The request object has incorrect attributes") boat = Boat(boat_data) boat.patch_data(content) error_msg = name_validator(client, content, constants.boats, boat_id) if error_msg: return json_response(403, error_msg=f'{error_msg}') update_entity(client, boat_id, constants.boats, boat) return jsonify(boat.api_return(boat_id)) return resource_not_found_404("No boat with this boat_id exists") return json_response(406, error_msg='Content must be in JSON format')
def main(): """ Part-1: Payment Request Generation """ print("-------------------------------------------------------") print("---PAYMENT REQUEST GENERATION---") cust_privkey, cust_pubkey = rsakeys() bank_privkey, bank_pubkey = rsakeys() print("Customer's private key-", cust_privkey) print("Customer's public key-", cust_pubkey) print("Bank's private key-", bank_privkey) print("Bank's public key-", bank_pubkey) payment_info = 'Some payment information' order_info = 'Some order information' PIMD = get_hash(payment_info) OIMD = get_hash(order_info) POMD = get_hash(PIMD + OIMD) dual_sign = sign(cust_privkey, POMD) key_s = aeskey() encrypted_pi, iv_pi = aesencrypt(payment_info, key_s) encrypted_oimd, iv_oimd = aesencrypt(OIMD, key_s) encrypted_ds, iv_ds = aesencrypt(dual_sign, key_s) digital_envelope = encrypt(bank_pubkey, key_s) """ Part 2: Purchase Request Validation from Merchant side """ merchant_oimd = get_hash(order_info) merchant_pomd = get_hash(PIMD + merchant_oimd) check_sign_merchant = verify(cust_pubkey, merchant_pomd, dual_sign) if check_sign_merchant: print("-------------------------------------------------------") print("[INFO] Merchant Signatures match") print("\tPurchase request validated by merchant") print("\t---PURCHASE REQUEST VALIDATED---") print("-------------------------------------------------------") else: print("-------------------------------------------------------") print("[INFO] Signatures do not match") print("\tPurchace request rejected- Signatures do not match!!") return """ Part 3: Payment authorization """ bank_key_s = decrypt(bank_privkey, digital_envelope) bank_pi = aesdecrypt(encrypted_pi, bank_key_s, iv_pi).decode() bank_oimd = aesdecrypt(encrypted_oimd, bank_key_s, iv_oimd).decode() bank_ds = aesdecrypt(encrypted_ds, bank_key_s, iv_ds) bank_pimd = get_hash(bank_pi) bank_pomd = get_hash(bank_pimd + bank_oimd) check_sign_bank = verify(cust_pubkey, bank_pomd, dual_sign) if check_sign_bank: print("[INFO] Bank Signatures match") print("\tPayment authorized by the bank") print("\t---PAYMENT AUTHORIZATION SUCCESSFUL---") print("-------------------------------------------------------") print("\t---PAYMENT CAPTURE SUCCESSFUL---") print("-------------------------------------------------------") else: print("[INFO] Signatures do not match") print("\tPayment authorization failed- Signatures do not match!!")
def test_verify(): assert verify('abcdefg', 'abcdefg') == True assert verify("abcdefg", "adfghjf") == False