def delete(self, id): """ Deletes an user. """ try: delete_user(id) except Exception as e: api.abort(code=404, message="User not found" + str(e)) return None, 204
def get(self, id): """ Returns an event with its details. """ try: result = get_info_events(Event.query.get(id)) except Exception as e: api.abort(code=404, message="Event not found" + str(e)) return result
def delete(self, id): """ Deletes a report. """ try: delete_report(id) except Exception as e: api.abort(code=404, message="Report not found" + str(e)) return None, 204
def delete(self, id): """ Deletes an event. """ try: result_event = delete_event(id) except Exception as e: api.abort(code=404, message="Event not found" + str(e)) return result_event.id, 202
def delete(self, id): """ Deletes a particular comment """ try: delete_comment(id) except Exception as e: api.abort(code=404, message="Comment not found" + str(e)) return None, 204
def get(self, id): """ Returns a particular comment with its details """ try: comment = get_info_comments(Comment.query.get(id)) except Exception as e: api.abort(code=404, message="Comment not found" + str(e)) return comment
def get(self, id): """ Returns an user with its details. """ try: result = User.query.filter(User.id == id).one() except Exception as e: api.abort(code=404, message="User not found" + str(e)) return result
def get(self, id): """ Returns a report with its details. """ try: result = Report.query.filter(Report.event_id == id).all() except Exception as e: api.abort(code=404, message="Report not found" + str(e)) return result
def post(self): """ Creates a new user. """ data = request.json try: add_user(data) except Exception as e: api.abort(code=400, message="We had an error with your request, " + str(e)) return None, 201
def get(self, id): """ Returns the events an user had vote """ try: result = User.query.get(id) voted_events = {'events_voting': list({'event_id': x.event_id, 'stars': x.stars} for x in result.voted)} except Exception as e: api.abort(code=404, message="User not found" + str(e)) return voted_events
def get(self): """ Returns the currently injected timeplan as JSON Object. """ AnomalyEngine = app.config['AnomalyEngine'] timeplan = AnomalyEngine.timeplan if timeplan: return timeplan.plan, 200 else: api.abort(400, "no timeplan")
def put(self, id): """ Edit a given user. """ data = request.json try: update_user(id, data) except Exception as e: api.abort(code=404, message="User not found" + str(e)) return None, 205
def put(self, id): """ Update the event details """ data = request.json try: update_event(id, data) except Exception as e: api.abort(code=404, message="Event not found" + str(e)) return id, 202
def get(self, id): """ Returns the events an user had fund """ try: result = User.query.get(id) funded_events = {'events_funding': list({'event_id': x.event_id, 'event_name': Event.query.get(x.event_id).name, 'funding_amount': x.fund_amount} for x in result.backed)} except Exception as e: api.abort(code=404, message="User not found" + str(e)) return funded_events
def get(self, id): """ Returns the events an user had watch """ try: result = User.query.get(id) tests = {'events_watching': list(x.id for x in result.watching)} print(tests) except Exception as e: api.abort(code=404, message="User not found" + str(e)) return tests
def post(self): """ Creates a new event. """ data = request.json auth_header = request.headers.get('Authtoken') user_id = get_id_form_token(auth_header) try: result_event = add_event(data, user_id) except Exception as e: api.abort(code=400, message="We had an error with your request, " + str(e)) return result_event, 201
def get(self, id): """ Returns the money paid to a given event """ try: result = Event.query.get(id) sum = 0.0 for x in result.backers: sum += x.fund_amount except Exception as e: api.abort(code=404, message="User not found" + str(e)) return {'money': sum}
def put(self, id): """ Vote an event with the given stars """ data = request.json auth_header = request.headers.get('Authtoken') user_id = get_id_form_token(auth_header) try: vote_event(id, data, user_id) except Exception as e: api.abort(code=404, message="Event not found" + str(e)) return id, 202
def get(self, id): """ Returns all comments from a given user """ try: User.query.filter(User.id == id).one() except Exception as e: api.abort(code=404, message="User not found" + str(e)) comments = Comment.query.filter(Comment.event_id == id).order_by( Comment.id.desc()).all() return get_info_comments(comments)
def post(self): """ Persist a new listing to file storage, db, and protocol """ timings = {} start_time = time.time() payload = {} uploaded_md5 = None for item in [ 'title', 'description', 'license', 'file_type', 'md5_sum', 'listing_hash' ]: if not request.form.get(item): api.abort(400, (constants.MISSING_PAYLOAD_DATA % item)) else: payload[item] = request.form.get(item) if request.form.get('tags'): payload['tags'] = [ x.strip() for x in request.form.get('tags').split(',') ] filenames = [] md5_sum = request.form.get('md5_sum') if request.form.get('filenames'): filenames = request.form.get('filenames').split(',') for idx, item in enumerate(request.files.items()): destination = os.path.join('/tmp/uploads/') filename = filenames[idx] if idx < len(filenames) else item[0] log.info(f'Saving {filename} to {destination}') if not os.path.exists(destination): os.makedirs(destination) item[1].save(f'{destination}{filename}') with open(f'{destination}{filename}', 'rb') as data: contents = data.read() uploaded_md5 = hashlib.md5(contents).hexdigest() if uploaded_md5 != md5_sum: api.abort(500, (constants.SERVER_ERROR % 'file upload failed')) local_finish = time.time() timings['local_save'] = local_finish - start_time log.info( f'Saving {filename} to S3 bucket {settings.S3_DESTINATION}') s3 = boto3.client('s3') with open(f'{destination}{filename}', 'rb') as data: # apparently this overwrites existing files. # something to think about? s3.upload_fileobj(data, settings.S3_DESTINATION, filename) timings['s3_save'] = time.time() - local_finish os.remove(f'{destination}{filename}') log.info(timings) db = dynamo.dynamo_conn db_entry = db.add_listing(payload) if db_entry == constants.DB_SUCCESS: return {'message': constants.NEW_CANDIDATE_SUCCESS}, 201
def delete(self): """ Reverts all running simulations. """ AnomalyEngine = app.config['AnomalyEngine'] simulations = AnomalyEngine.current_running_simulations() if not simulations: return {"message": "No running simulations"}, 200 for sim in simulations: error = sim.stop() if error: api.abort(500, "Error during stop operation: {}".format(error)) return {"message": "All simulations stopped"}, 201
def get(self, interface): """ Returns status of WAN simulation on the given interface. """ AnomalyEngine = app.config['AnomalyEngine'] simulation = AnomalyEngine.lookup_simulation(interface) if simulation == None: logging.info("Can't find interface " + interface) api.abort(400, "Interface {} doesn't exist".format(interface)) if simulation.is_running(): return simulation.status(), 201 else: return {"message": "No simulation running"}, 200
def get(self, id): """ Returns the average stars of an event """ try: result = Event.query.get(id) sum = 0.0 num = 0 for x in result.votes: sum += x.stars num = num + 1 print(sum/num) except Exception as e: api.abort(code=404, message="User not found" + str(e)) return {'stars': sum/num}
def post(self): _refresh_token = request.json['refresh_token'] try: payload = jwt.decode(_refresh_token, settings.PASSWORD_JWT) refresh_token = RefreshToken.query.filter_by( user_id=payload['uid'], refresh_token=_refresh_token).first() if not refresh_token: raise jwt.InvalidIssuerError # Generate new pair _access_token = jwt.encode( { 'uid': refresh_token.user_id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=15), 'iat': datetime.datetime.utcnow() }, settings.PASSWORD_JWT).decode('utf-8') _refresh_token = jwt.encode( { 'uid': refresh_token.user_id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(days=30), 'iat': datetime.datetime.utcnow() }, settings.PASSWORD_JWT).decode('utf-8') refresh_token.refresh_token = _refresh_token db.session.add(refresh_token) db.session.commit() return { 'access_token': _access_token, 'refresh_token': _refresh_token }, 200 except jwt.ExpiredSignatureError as e: raise e except (jwt.DecodeError, jwt.InvalidTokenError) as e: raise e except Exception as e: api.abort(401, 'Unknown token error' + str(e))
def post(self): data = request.json user = User.query.filter_by(mail=data['mail']).first() if not user: api.abort(code=400, message="Incorrect username or password") if user.password == data['password']: _access_token = jwt.encode( { 'uid': user.id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=15), 'iat': datetime.datetime.utcnow() }, settings.PASSWORD_JWT).decode('utf-8') _refresh_token = jwt.encode( { 'uid': user.id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(days=30), 'iat': datetime.datetime.utcnow() }, settings.PASSWORD_JWT).decode('utf-8') user_agent_string = request.user_agent.string.encode('utf-8') user_agent_hash = hashlib.md5(user_agent_string).hexdigest() refresh_token = RefreshToken.query.filter_by( user_agent_hash=user_agent_hash).first() if not refresh_token: refresh_token = RefreshToken(user_id=user.id, refresh_token=_refresh_token, user_agent_hash=user_agent_hash) else: refresh_token.refresh_token = _refresh_token db.session.add(refresh_token) db.session.commit() return { 'access_token': _access_token, 'refresh_token': _refresh_token }, 200 api.abort(401, 'Incorrect username or password')
def get(self, id): """ Returns a summary about an SEC filing. """ id = urllib.request.unquote(id) ##TODO - Can we encode this on the swagger level? #example_id = "001-05794/121170625" record = self.mongo.find_one({"_id": id}, { "RawText": 0, "InteractiveDataTables": 0 }) if record is None: api.abort(code=404, message="No match found for _id: " + id) return record
def delete(self): """ Reverts all running anomalies. """ AnomalyEngine = app.config['AnomalyEngine'] # No manual reverting of anomalies when in timeplan mode if AnomalyEngine.current_mode == "timeplan": api.abort( 403, "no manual reverting of anomalies when in timeplan mode") current_anomalies = AnomalyEngine.current_running_anomalies() if not current_anomalies: return {'message': 'no running anomalies'}, 200 for anomaly in current_anomalies: AnomalyEngine.revert_anomaly(anomaly) return {'message': 'all running anomalies reverted'}, 201
def post(self, mode): """ Set Injection mode of the host. """ AnomalyEngine = app.config['AnomalyEngine'] if mode != "timeplan" and mode != "manual": api.abort(400, "Please chose 'timeplan' or 'manual' as mode ") if AnomalyEngine.current_mode == mode: return { "message": "Injector Agent is already in %s mode" % mode }, 200 if AnomalyEngine.current_running_anomalies(): api.abort(409, "Cannot change mode when anomalies are running.") if AnomalyEngine.set_mode(mode): return {"message": "mode changed to %s" % mode}, 201 else: return {"message": "mode not changed"}, 400
def get(self, name): """ Returns the status of the given anomaly. """ AnomalyEngine = app.config['AnomalyEngine'] anomaly = AnomalyEngine.lookup_anomaly(name) if anomaly != None: if AnomalyEngine.check_anomaly_status(anomaly): res = { 'name': anomaly.name, 'parameter': AnomalyEngine.last_parameters[anomaly.name], 'running': AnomalyEngine.check_anomaly_status(anomaly) } return res, 200 else: res = { 'name': anomaly.name, 'running': AnomalyEngine.check_anomaly_status(anomaly) } return res, 202 api.abort(404, "Anomaly {} doesn't exist".format(name))
def put(self, interface): """ Update a WAN simulation on given interface """ AnomalyEngine = app.config['AnomalyEngine'] simulation = AnomalyEngine.lookup_simulation(interface) args = simulation_parser.parse_args() params = {key: value for key, value in args.items() if value} if simulation == None: logging.info("Can't find interface " + interface) api.abort(400, "Interface {} doesn't exist".format(interface)) if not simulation.is_running(): api.abort( 405, "There is no simulation running on interface {}".format( interface)) logging.info("Updating WAN simulation on " + interface) logging.info("Using the following simulation params: " + json.dumps(params)) error = AnomalyEngine.start_simulation(simulation, params, update=True) if error: api.abort(500, "Error during execution: {}".format(error)) return simulation.status(), 201