def post(self, data): try: data['i_hash'], data['i_priv_key'] = g.geth.create_account() issuer = create_issuer(data) g.sesh.commit() log_kv(LOG_INFO, {'message': 'successfully created issuer account'}) return success_response({'jwt': generate_jwt(issuer)}, http_code=201) except GethException as ge: g.sesh.rollback() log_kv( LOG_ERROR, { 'error': 'raised exception from geth_keeper while creating issuer account', 'exception': ge.exception, 'exc_message': ge.message }) return error_response(ge.message) except Exception as err: g.sesh.rollback() log_kv( LOG_ERROR, { 'error': 'an exception occurred while creating issuer account', 'exception': str(err) }) return error_response("Couldn't create issuer", http_code=200)
def get_issuer_jwt(data): # Gather up login details. login_deets = GetIssuerLoginDetails().execute_n_fetchone( binds=data, close_connection=True) if login_deets is None: log_kv( LOG_WARNING, { 'warning': 'could not find login details for issuer', 'username': data['username'] }) return error_response("Authorization Failed for Issuer Login.") # If we got some deets back then check if passwords match. if data['password'] == login_deets['password']: del login_deets['password'] log_kv(LOG_DEBUG, { 'debug': 'successfully logged in issuer', 'username': data['username'] }) return success_response({'jwt': generate_jwt(login_deets)}) else: log_kv( LOG_INFO, { 'message': 'authorization failed for issuer', 'username': data['username'] }) return error_response("Authorization Failed for Issuer Login.")
def delete(self, data): # Get trade specified by requester. trade = GetTradeByTRID().execute_n_fetchone(data, schema_out=False) # Make sure got a trade. if trade is None: return error_response('No trade request specified for that tr_id.') # Make sure trade is in correct state to delete. if trade['status'] != TradeStatus.REQUESTED.value: return error_response('Trade is not in a valid state to delete.') # Ensure requester has access to cancel this trade. if trade['trader_c_id'] != g.collector_info['c_id']: log_kv(LOG_INFO, {'info': "Attempted deletion of trade request not owned by authorized collector", 'c_id': g.collector_info['c_id']}) return error_response('Authorized collector does not have ownership over this trade.') # If identity has be verified update the status. data.update({'new_status': TradeStatus.CANCELED.value}) if UpdateTradeStatus().execute(data): g.sesh.commit() return success_response(status='Trade request canceled.') else: g.sesh.rollback() return error_response(status='Unable to cancel trade request.')
def delete_customer(id): try: customer = Customer.query.get(id) if not customer: return jsonify(error_response("Customer doesn't exist")) db.session.delete(customer) db.session.commit() return jsonify(success_response('Successfully Deleted.')) except: return jsonify(error_response('Something went wrong'))
def delete(self, todo_id=None): if not todo_id: return error_response(404, 'Todo with id {} not found'.format(todo_id)) try: Todo.todos.pop(todo_id) return ok_response("Success") except KeyError as e: return error_response( 404, 'Todo with id {} not found'.format(e.message))
def patch(self, todo_id=None): if not todo_id: return error_response(400, 'id not found') if not request.json: return error_response(400, 'Body required!') body = request.json try: todo = Todo.todos[todo_id] todo['status'] = body['status'] return ok_response(todo) except KeyError as e: return error_response( 404, 'Todo with id {} not found'.format(e.message))
def update_customer(id): customer = Customer.query.get(id) if not customer: return jsonify(error_response("Customer doesn't exist")) name = request.json['name'] dob = request.json['dob'] dob_object = parse_date(dob) if not dob_object: return jsonify(error_response("Invalid Date")) updated_at = datetime.datetime.now() customer.name = name customer.dob = dob_object customer.updated_at = updated_at db.session.commit() return customer_schema.jsonify(customer)
def post(self, data): # Get needed issuer, and contract data. collector = GetCollectorByCID().execute_n_fetchone( {'c_id': g.collector_info['c_id']}) contract = GetContractByConID().execute_n_fetchone( {'con_id': data['con_id']}, schema_out=False) try: g.geth.perform_transfer(contract['con_addr'], contract['con_abi'], data['t_id'], src_acct=collector['c_hash'], dest_acct=data['destination_wallet_hash']) UpdateTokenStatus().execute({ 'new_status': TokenStatus.EXTERNAL.value, 'this_id': data['t_id'] }) g.sesh.commit() except Exception as e: g.sesh.rollback() log_kv(LOG_ERROR, { 'error': str(e), 'message': "Could not perform external token transfer!" }, exception=True) return error_response( 'Unable to perform transfer. Please check the given wallet address', status_code=423) return success_response("Went through.")
def get(self): collector = GetCollectorByCID().execute_n_fetchone( {'c_id': g.collector_info['c_id']}, close_connection=True) if collector: # Try and get out the eth balance. try: balance = g.geth.get_eth_balance(collector['c_hash']) except GethException as e: log_kv(LOG_ERROR, { 'error': "Couldn't retrieve eth balance", 'c_id': g.collector_info['c_id'], 'exception': e.exception, 'geth_message': e.message }, exception=True) balance = 'Not available at this time.' collector.update({'eth_balance': balance}) return success_response(collector) else: log_kv( LOG_WARNING, { 'warning': 'could not get collector account', 'collector_id': g.collector_info['c_id'] }) return error_response(status="Couldn't retrieve collector info.", status_code=-1, http_code=200)
def get(self): """ Method to use for get requests to the /contract method. :return: """ contracts = GetContractsByIssuerID().execute_n_fetchall( {'i_id': g.issuer_info['i_id']}) if contracts is not None: log_kv( LOG_INFO, { 'message': 'succesfully retrieved issuer\'s contracts', 'issuer_id': g.issuer_info['i_id'] }) # Add the constraints to the contract object. for contract in contracts: contract.update( {'constraints': get_all_constraints(contract['con_id'])}) return success_response({'contracts': contracts}) else: log_kv( LOG_WARNING, { 'warning': 'could not get contract for issuer', 'issuer_id': g.issuer_info['i_id'] }) return error_response( status="Couldn't retrieve contract with that con_id", status_code=-1, http_code=200)
def get(self, todo_id=None): if not todo_id: return ok_response({"todos": Todo.todos.values()}) try: return ok_response(Todo.todos[todo_id]) except KeyError as e: return error_response( 404, 'Todo with id {} not found'.format(e.message))
def decorator(*args, **kwargs): token = None if 'Authorization' in request.headers or 'x-access-token' in request.headers or 'token' in request.json: token = request.headers.get( 'x-access-token', None) or request.json.get( 'token', None) or request.headers.get('Authorization') token = token.replace('Bearer ', '') else: return jsonify(error_response('Token required')) try: decoded = jwt.decode(token, app.config['JWT_SECRET']) user = User.query.filter_by(id=decoded['id']).first() if not user: return jsonify(success_response('Invalid User')) except: return jsonify(error_response('Invalid Token')) return f(*args, **kwargs)
def get_all_tradable(keyword=None): contracts = GetAllTradableContracts(keyword).execute_n_fetchall({}, close_connection=True, load_out=True) if contracts is not None: log_kv(LOG_DEBUG, {'debug': 'succesfully got all contracts'}) return success_response({'contracts': contracts}) else: log_kv(LOG_ERROR, {'warning': 'could not pull all contracts!!!'}) return error_response(status="Couldn't retrieve contracts")
def claims(data): results, msg, err_code = claim_token_for_user( data['con_id'], g.collector_info['c_id'], data['location']['latitude'], data['location']['longitude'], data.get('constraints', {}), g.sesh) if results: g.sesh.commit() return success_response(msg) else: g.sesh.rollback() return error_response(msg, status_code=err_code)
def signup(): try: if {'username', 'password'} <= request.json.keys(): username = request.json['username'] password = request.json['password'] hashed_password = generate_password_hash(password, method='sha256') new_user = User(username, hashed_password) db.session.add(new_user) db.session.commit() return jsonify({'message': "User successfully created"}), 200 else: return jsonify( error_response( 'Please submi0t a username and a password')), 400 except Exception as e: if os.environ.get('ENV', None) == 'production': return jsonify(error_response('Something went wrong')), 500 else: return jsonify(error_response(str(e))), 500
def add_customer(): name = request.json['name'] dob = request.json['dob'] dob_object = parse_date(dob) if not dob_object: return jsonify(error_response("Invalid Date")) new_customer = Customer(name, dob_object) db.session.add(new_customer) db.session.commit() return customer_schema.dump(new_customer)
def decorated_function(*args, **kwargs): # Verify we something and the jwt contains the needed info. user_info = parse_jwt_out_of_auth() if not user_info or 'c_id' not in user_info: return error_response("Access Denied", http_code=403) # If we get it and its valid put it on the global request object. g.collector_info = user_info return f(*args, **kwargs)
def claim_by_qr_code(data): results, msg, err_code = claim_qr_code(data['con_id'], data['t_id'], g.collector_info['c_id'], data['location']['latitude'], data['location']['longitude']) if results: g.sesh.commit() return success_response(msg) else: g.sesh.rollback() return error_response(msg, status_code=err_code)
def post(self, data): try: # If the user already exists, return a jwt to them collector = GetCollectorByUsername().execute_n_fetchone( {'username': data['username']}) if collector: log_kv( LOG_INFO, { 'message': 'the given user already exists', 'username': data['username'] }) return success_response({'jwt': generate_jwt(collector)}, http_code=201) # Create the collector account and bind the hash and private key data['c_hash'], data['c_priv_key'] = g.geth.create_account() collector = create_collector(data) g.sesh.commit() log_kv(LOG_INFO, {'message': 'successfully created collector'}) return success_response({'jwt': generate_jwt(collector)}, http_code=201) except GethException as ge: log_kv( LOG_ERROR, { 'error': 'a geth_exception occurred while creating collector account', 'exception': ge.exception, 'exc_message': ge.message }) return error_response(ge.message) except Exception as e: log_kv( LOG_ERROR, { 'error': 'an exception occurred while creating collector account', 'exception': str(e) }) return error_response(str(e), http_code=200)
def get_collection(): # Get collection for user. collection = GetCollection().execute_n_fetchall( {'c_id': g.collector_info['c_id']}, close_connection=True) if collection is not None: return success_response({'collection': collection}) else: log_kv( LOG_ERROR, { 'error': 'could not get a user\'s collection', 'collector_id': g.collector_info['c_id'] }) return error_response("Couldn't retrieve collectors collection.")
def login(): username = None password = None auth = request.authorization or None if auth: username = auth.username password = auth.password else: username = request.json['username'] password = request.json['password'] if (username and password): user = User.query.filter_by(username=username).first() if check_password_hash(str(user.password), password): token = jwt.encode( { 'id': user.id, 'exp': datetime.datetime.now() + datetime.timedelta(hours=24) }, app.config['JWT_SECRET']) return jsonify({'token': token.decode('UTF-8')}) return jsonify(error_response('Invalid credentials')), 401 else: return jsonify(error_response('No credentials')), 400
def wrapper(*args, **kwargs): schema = schema_cls(**schema_kwargs) json = request.get_json(force=True) try: if dump: data = schema.dump(json) else: data = schema.load(json) return f(data=data, *args, **kwargs) except ValidationError as err: log_kv(LOG_ERROR, { 'exception': str(err), 'error': "failed to validate schema." }, exception=True) return error_response("Validation Failed", errors=err.messages)
def analytics(con_id): # Get contract. data = g.sesh.execute( """ select num_created, qr_code_claimable from contracts where contracts.con_id = :contract_id;""", { "contract_id": con_id }).fetchall() # Check that the data is there if len(data) == 0: return error_response("Con id doesn't exist") num_created = data[0]['num_created'] qr_code_claimable = data[0]['qr_code_claimable'] # Figure out how many have been claimed. d_num_claimed = g.sesh.execute( """select count(*) as count1 from tokens where tokens.con_id=:contract_id and status='S';""", { 'contract_id': con_id }).fetchall() num_claimed = d_num_claimed[0]['count1'] if qr_code_claimable: constraints = None else: constraints = get_all_constraints(con_id) return success_response({ 'num_claimed': num_claimed, 'num_unclaimed': num_created - num_claimed, 'num_created': num_created, 'coordinates': claimed_coordinates(con_id), 'loc_constraints': loc_constraints(con_id), 'time_windows': token_time_windows(con_id), 'qr_code_claimable': qr_code_claimable, 'constraints': constraints, 'price_and_time': price_and_timestamps(con_id), 'traded': num_trades(con_id), 'num_traded_tokens': num_traded_tokens(con_id) })
def get_collector_by_username(username): collector = GetCollectorByUsername().execute_n_fetchone( {'username': username}, close_connection=True) if collector: log_kv(LOG_INFO, { 'message': 'successfully created collector', 'username': username }) return success_response(collector) else: log_kv(LOG_WARNING, { 'warning': 'could not create collector', 'username': username }) return error_response( status="Couldn't retrieve collector with that username", status_code=-1, http_code=200)
def get_contract_by_name(name): contracts_by_name = GetContractByName().execute_n_fetchall( {'name': '%' + name + '%'}, close_connection=True) if contracts_by_name is not None: log_kv(LOG_DEBUG, { 'debug': 'found contract by name', 'contract_name': name }) return success_response({'contracts': contracts_by_name}) else: log_kv(LOG_WARNING, { 'warning': 'could not find contract by name', 'contract_name': name }) return error_response( status="Couldn't retrieve contract with that con_id", status_code=-1, http_code=200)
def get_contract_by_con_id(con_id): contract = GetContractByConID().execute_n_fetchone({'con_id': con_id}) constraints = get_all_constraints(con_id) g.sesh.close() if contract: log_kv(LOG_DEBUG, { 'debug': 'successfully retrieved contract', 'contract_id': con_id }) contract.update({'constraints': constraints}) return success_response({'contract': contract}) else: log_kv(LOG_WARNING, { 'warning': 'could not find contract', 'contract_id': con_id }) return error_response( status="Couldn't retrieve contract with that con_id", status_code=-1, http_code=200)
def get_issuer_by_username(username): """ This method retrieves issuer data for the given username. :param username: username of issuer to retrieve. :return: """ issuer = GetIssuerByUsername().execute_n_fetchone({'username': username}, close_connection=True) if issuer: log_kv(LOG_INFO, { 'message': 'Successfully found issuer', 'issuer_username': username }) return success_response(issuer) else: log_kv(LOG_WARNING, { 'warning': 'Could not find account', 'issuer_username': username }) return error_response( status="Couldn't retrieve issuer with that username", status_code=-1, http_code=200)
def post(self): """ Method to use for post requests to the /contract method. :return: HTTP response """ try: # Parse out the data from the contract request. data = ContractRequest().loads(request.form['json_data']) except ValidationError as er: return error_response('Validation Failed', errors=er.messages) # Check to ensure we are not over the max token limit. if data['num_created'] > MAX_TOKEN_LIMIT: log_kv( LOG_WARNING, { 'warning': 'issuer tried to create contract over limit', 'issuer_id': g.issuer_info['i_id'], 'num_tokens': data['num_created'] }) return error_response( "Could not create a token contract with that many individual token. Max is {}" .format(MAX_TOKEN_LIMIT), status_code=89) # Update the original data given after validation for contract creation binds. data.update({'i_id': g.issuer_info['i_id']}) # If we have an image save it. file_location = 'default.png' if 'token_image' in request.files: file_location = save_file(request.files['token_image'], Folders.CONTRACTS.value, g.issuer_info['i_id']) data.update({'pic_location': file_location}) # If meta data is persistent save it. if 'meta_json_data' in request.form: data['metadata_location'] = save_json_data( request.form['meta_json_data'], g.issuer_info['i_id']) else: img_location = "project-token.com/contract/image=" + data[ 'pic_location'] data['metadata_location'] = save_json_data( DEFAULT_JSON_METADATA.format(name=data['name'], description=data['description'], img_loc=img_location), g.issuer_info['i_id']) try: # Get the received constraints in array format for the smart contract code_constraints, date_constraints, loc_constraints = self.get_constraints( data) # Issue the contract on the ETH network issuer = GetIssuerInfo().execute_n_fetchone( binds={'i_id': g.issuer_info['i_id']}) # Ensure we retrieved an issuer. if issuer is None: return error_response('Failed to retrieve issuer specified.', status_code=45) data['con_tx'], data['con_abi'], data[ 'gas_price'] = g.geth.issue_contract( issuer['i_hash'], issuer_name=issuer['username'], name=data['name'], desc=data['description'], img_url=data['pic_location'], num_tokes=data['num_created'], code_reqs=code_constraints, date_reqs=date_constraints, loc_reqs=loc_constraints, tradable=data['tradable'], metadata_uri=data['metadata_location']) # Insert into the database con_id, t_ids = insert_bulk_tokens(data['num_created'], data, g.sesh) # It is either qr_codes or other contstraints it cannot be both. if data['qr_code_claimable']: # Get all tokens to associate qr code with. for t_id in t_ids: # Generate the data to place in qr code. json_data_dict = dumps({ 'con_id': con_id, 't_id': t_id, 'jwt': generate_jwt({ 'con_id': con_id, 't_id': t_id }) }) # Make qr_code and save it. qrc = qrcode.make(json_data_dict) saved_location = save_qrcode(qrc, con_id, t_id) # If we successfully saved the image persist it into database. if saved_location is None: log_kv(LOG_ERROR, {'error': 'failed to make qrcode.'}) else: UpdateQRCODE().execute({ 'qr_code_location': saved_location, 'con_id': con_id, 't_id': t_id }) elif 'constraints' in data: # If constraints were passed in we need to process them. process_constraints(data['constraints'], con_id) g.sesh.commit() log_kv( LOG_INFO, { 'message': 'succesfully issued contract!', 'issuer_id': g.issuer_info['i_id'] }) return success_response('Success in issuing token!', http_code=201) except GethException as e: g.sesh.rollback() log_kv(LOG_ERROR, { 'error': 'a geth_exception occurred while issuing contract', 'issuer_id': g.issuer_info['i_id'], 'exception': e.exception, 'exc_message': e.message }, exception=True) return error_response(e.message) except Exception as e: g.sesh.rollback() log_kv(LOG_ERROR, { 'error': 'an exception occurred while issuing contract', 'issuer_id': g.issuer_info['i_id'], 'exception': str(e) }, exception=True) return error_response( "Couldn't create new contract. Exception {}".format(str(e)))
def get_customer(id): customer = Customer.query.get(id) if not customer: return jsonify(error_response("Customer doesn't exist")) return customer_schema.jsonify(customer)
def post(self): if not request.json: return error_response(400, 'Body required!') todo = request.json # add validation for json body todo = Todo(description=todo['description'], status=todo['status']) return ok_response(todo.get_dict(), code=StatusCodes.CREATED)