def add_session(): request_data = request.get_json() try: if len(request_data) > 3: raise AuthError( { 'description': 'Please include only the name, trainer_id, and client_id of the session.' }, 400) if not request_data['name']: raise AuthError({'description': 'Session name is missing.'}, 400) if not request_data['trainer_id']: raise AuthError( {'description': 'Session trainer id is missing.'}, 400) if not request_data['client_id']: raise AuthError( {'description': 'Session client id is missing.'}, 400) except AuthError as e: abort(e.status_code, e.error) new_session = Session() new_session.name = request_data['name'] new_session.trainer_id = request_data['trainer_id'] new_session.client_id = request_data['client_id'] new_session.insert() return jsonify({'success': True, 'new_session': new_session.format()})
def add_trainer(): request_data = request.get_json() try: if len(request_data) > 3: raise AuthError( { 'description': 'Please include only the name, gender, and age of trainer.' }, 400) if not request_data['name']: raise AuthError({'description': 'Trainer name is missing.'}, 400) if not request_data['gender']: raise AuthError({'description': 'Trainer gender is missing.'}, 400) if not request_data['age']: raise AuthError({'description': 'Trainer age is missing.'}, 400) except AuthError as e: abort(e.status_code, e.error) new_trainer = Trainer() new_trainer.name = request_data['name'] new_trainer.gender = request_data['gender'] new_trainer.age = request_data['age'] new_trainer.insert() return jsonify({'success': True, 'new_trainer': new_trainer.format()})
def create_reviewer(jwt): body = request.get_json() try: name = body.get('name', None) email = body.get('email', None) reviewers = Reviewer.query.filter(Reviewer.name.like(name)).count() print("current", reviewers) if reviewers > 0: raise AuthError({ 'code': 'Bad request', 'description': "This reviewer is already existent" }, 400) reviewer = Reviewer( name=name, email=email) reviewer.insert() return jsonify({ 'success': True, 'reviewers': [reviewer.format()] }) except Exception as e: print("exception error post reviewer", e) print(e) if isinstance(e, AuthError): raise e abort(406)
def patch_session(id): request_data = request.get_json() try: target_session = Session.query.filter_by(id=id).first() if target_session is None: raise AuthError( { 'code': 'session_not_found', 'description': 'There is no session with the reuqested id to modify.' }, 404) except AuthError as e: abort(e.status_code, e.error) if 'name' in request_data: target_session.name = request_data['name'] if 'trainer_id' in request_data: target_session.trainer_id = request_data['trainer_id'] if 'client_id' in request_data: target_session.client_id = request_data['client_id'] target_session.update() return jsonify({ 'success': True, 'modified_session': target_session.format() })
def patch_client(id): request_data = request.get_json() try: target_client = Client.query.filter_by(id=id).first() if target_client is None: raise AuthError( { 'code': 'client_not_found', 'description': 'There is no client with the reuqested id to modify.' }, 404) except AuthError as e: abort(e.status_code, e.error) if 'name' in request_data: target_client.name = request_data['name'] if 'gender' in request_data: target_client.gender = request_data['gender'] if 'age' in request_data: target_client.age = request_data['age'] target_client.update() return jsonify({ 'success': True, 'modified_client': target_client.format() })
def create_project(jwt): body = request.get_json() try: name = body.get('name', None) category = body.get('category', None) reviewers = Project.query.filter(Project.name.like(name)).count() print("current", reviewers) if reviewers > 0: raise AuthError({ 'code': 'Bad request', 'description': "This project is already existent" }, 400) reviewer = Project( name=name, category=category) reviewer.insert() return jsonify({ 'success': True, 'projects': [reviewer.format()] }) except Exception as e: print("exception error post reviewer", e) print(e) if isinstance(e, AuthError): raise e abort(406)
def patch_answer(answer_id): data = request.get_json() or [] answer = Answer.query.get(answer_id) if not answer: abort("404", "answer not found!") # retrive user_id using username (which is stored in the stack by requires_auth decorator) username = _request_ctx_stack.top.curr_user['sub'] user_id = User.query.filter_by(username=username).with_entities( User.id).one().id # check if current user owns the target answer if user_id != answer.user_id: raise AuthError('You can\'t update others answers', 403) # update content if 'content' in data: # sanitize input content = bleach.clean(data['content']) # supporting markdown answer.content = markdown(content) try: answer.update() except Exception: abort(422) return jsonify({'success': True, 'data': answer.format()})
def patch_question(question_id): data = request.get_json() or [] question = Question.query.get(question_id) if question == None: abort(404, 'question not found') # retrive user_id using username (which is stored in the stack by requires_auth decorator) username = _request_ctx_stack.top.curr_user['sub'] user_id = User.query.filter_by(username=username).with_entities( User.id).one().id # check if current user owns the target question if user_id != question.user_id: raise AuthError('You can\'t update others questions', 403) # update accepted answer if 'accepted_answer' in data: answer = Answer.query.get(data['accepted_answer']) if not answer or answer.question_id != question_id: abort(400, 'the provided answer is not valid') question.accepted_answer = data['accepted_answer'] # update question content if 'content' in data: # sanitize input content = bleach.clean(data['content']) # supporting markdown question.content = markdown(content) try: question.update() except Exception: abort(422) return jsonify({'success': True, 'data': question.format()})
def dss_isa_callback(id): ''' This is the call back end point that other USSes in the DSS network call once a subscription is updated ''' if requires_scope('dss.write.identification_service_areas'): new_flights_url = request.args.get('flights_url', 0) try: assert new_flights_url != 0 redis = redis.Redis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT']) # Get the flights URL from the DSS and put it in flights_dict = redis.hgetall("all_uss_flights") all_flights_url = flights_dict['all_flights_url'] all_flights_url = all_flights_url.append(new_flights_url) flights_dict["all_uss_flights"] = all_flights_url redis.hmset("all_uss_flights", flights_dict) except AssertionError as ae: return Response("Incorrect data in the POST URL", status=400, mimetype='application/json') else: # All OK return a empty response return Response("", status=204, mimetype='application/json') raise AuthError( { "code": "Unauthorized", "description": "You don't have access to this resource" }, 403)
def post_flight_declaration(): if requires_scope('blender.write'): try: assert request.headers['Content-Type'] == 'application/json' except AssertionError as ae: msg = {"message": "Unsupported Media Type"} return Response(json.dumps(msg), status=415, mimetype='application/json') else: req = json.loads(request.data) try: flight_declaration_data = req["flight_declaration"] except KeyError as ke: msg = json.dumps({ "message": "One parameter are required: observations with a list of observation objects. One or more of these were not found in your JSON request. For sample data see: https://github.com/openskies-sh/airtraffic-data-protocol-development/blob/master/Airtraffic-Data-Protocol.md#sample-traffic-object" }) return Response(msg, status=400, mimetype='application/json') else: task = tasks.write_flight_declaration.delay( flight_declaration_data ) # Send a job to the task queuervation) # Send a job to the task queue op = json.dumps({"message": "Submitted Flight Declaration"}) return Response(op, status=200, mimetype='application/json') raise AuthError( { "code": "Unauthorized", "description": "You don't have access to this resource" }, 403)
def assign(a, b): body = request.get_json() reviewer_id = body.get('reviewer_id', None) project_id = body.get('project_id', None) try: reviewer = Reviewer.query.filter_by(id=reviewer_id).one_or_none() project = Project.query.filter_by(id=project_id).one_or_none() previous_assignments = Assignment.query.filter( Assignment.reviewer_id == reviewer_id, Assignment.project_id == project_id).count() if previous_assignments > 0: raise AuthError({ 'code': 'Bad request', 'description': "this assignment is already existent" }, 400) if reviewer is None: raise AuthError({ 'code': 'Bad request', 'description': "reviewer does not exist" }, 400) if project is None: raise AuthError({ 'code': 'Bad request', 'description': "project does not exist" }, 400) assignment = Assignment() assignment.reviewer_id = reviewer_id assignment.project_id = project_id assignment.insert() return jsonify({ 'success': True, 'assignment': assignment.format() }) except Exception as e: print("exception error post reviewer", e) print(e) if isinstance(e, AuthError): raise e abort(422)
def set_air_traffic(): if requires_scope('blender.write'): ''' This is the main POST method that takes in a request for Air traffic observation and processes the input data ''' try: assert request.headers['Content-Type'] == 'application/json' except AssertionError as ae: msg = {"message": "Unsupported Media Type"} return Response(json.dumps(msg), status=415, mimetype='application/json') else: req = json.loads(request.data) try: observations = req['observations'] except KeyError as ke: msg = json.dumps({ "message": "One parameter are required: observations with a list of observation objects. One or more of these were not found in your JSON request. For sample data see: https://github.com/openskies-sh/airtraffic-data-protocol-development/blob/master/Airtraffic-Data-Protocol.md#sample-traffic-object" }) return Response(msg, status=400, mimetype='application/json') else: for observation in observations: lat_dd = observation['lat_dd'] lon_dd = observation['lon_dd'] altitude_mm = observation['altitude_mm'] traffic_source = observation['traffic_source'] source_type = observation['source_type'] icao_address = observation['icao_address'] single_observation = { 'lat_dd': lat_dd, 'lon_dd': lon_dd, 'altitude_mm': altitude_mm, 'traffic_source': traffic_source, 'source_type': source_type, 'icao_address': icao_address } task = tasks.write_incoming_data.delay( single_observation) # Send a job to the task queue op = json.dumps({"message": "OK"}) return Response(op, status=200, mimetype='application/json') raise AuthError( { "code": "Unauthorized", "description": "You don't have access to this resource" }, 403)
def create_dss_subscription(): ''' This module takes a lat, lng box from Flight Spotlight and puts in a subscription to the DSS for the ISA ''' if requires_scope('blender.write'): try: view = request.args.get('view') # view is a bbox list view = [float(i) for i in view.split(",")] except Exception as ke: incorrect_parameters = { "message": "A view bbox is necessary with four values: minx, miny, maxx and maxy" } return Response(json.dumps(incorrect_parameters), status=400, mimetype='application/json') else: b = box(view[0], view[1], view[2], view[3]) co_ordinates = list(zip(*b.exterior.coords.xy)) # Convert bounds vertex list vertex_list = [] for cur_co_ordinate in co_ordinates: lat_lng = {"lng": 0, "lat": 0} lat_lng["lng"] = cur_co_ordinate[0] lat_lng["lat"] = cur_co_ordinate[1] vertex_list.append(lat_lng) # remove the final point vertex_list.pop() # TODO: Make this a asnyc call #tasks.submit_dss_subscription(vertex_list = vertex_list, view_port = view) myDSSubscriber = rid_dss_operations.RemoteIDOperations() subscription_respone = myDSSubscriber.create_dss_subscription( vertex_list=vertex_list, view_port=view) if subscription_respone['created']: msg = {"message": "DSS Subscription created"} else: msg = { "message": "Error in creating DSS Subscription, please check the log or contact your administrator." } return Response(json.dumps(msg), status=200, mimetype='application/json') raise AuthError( { "code": "Unauthorized", "description": "You don't have access to this resource" }, 403)
def delete_answer(answer_id): answer = Answer.query.get(answer_id) if answer == None: abort(404) # retrive user_id using username (which is stored in the stack by requires_auth decorator) username = _request_ctx_stack.top.curr_user['sub'] user_id = User.query.filter_by(username=username).with_entities( User.id).one().id # check if the current user owns the target answer if user_id != answer.user_id: if not requires_permission('delete:answers'): raise AuthError( 'You don\'t have ' 'the authority to delete other users answers', 403) try: answer.delete() except Exception: abort(422) return jsonify({'success': True, 'deleted_id': int(answer_id)})
def retrieve_clothes_reservations(payload, clothes_id): """retrieve reservation information about that clothes. Users can check theri own reservation information. AUthError will be returned if trying to check another user's reservation. Staffs and managers can retrieve all reservation information. Returns: json object with following attributes { 'success': True, 'clothes': formatted clothes of the given clothes_id, 'user': formatted user who has reserved that clothes, } """ selection = Reserve.query.filter_by(clothes_id=clothes_id).all() # if the given clothes has not been reserved, abort 404 if len(selection) == 0: abort(404) # if two or more user reserved the same clothe, abort umprocessable if len(selection) >= 2: abort(422) reservation = selection[0] # querying who is accessing and check role access_user = User.query.filter_by(auth0_id=payload['sub']).first() role = access_user.role # if user role is "user", check if access user_id matches # reservation user_id reserved_user = reservation.user if role == 'user' and access_user.id != reserved_user.id: raise AuthError( { 'code': 'Invalid_claims', 'description': 'Unauthorized access by user' }, 401) # query clothes clothes = reservation.clothes return jsonify({ 'success': True, 'clothes': clothes.format(), 'user': reserved_user.format() })
def retrieve_user_reservations(payload, user_id): """Get all reservations which the given user has made. Users can get reservations only through their own user_id. AuthError will be raised if trying to see another user's reservation. Staffs and managers can retrieve all reservation information. Returns: json object with following attributes { 'success': True, 'clothes': list of formatted clothes which the given user has reserved, 'user': formatted user who has reserved those clothes } """ # check if that user indeed exists user = User.query.get(user_id) if user is None: abort(404) # querying who is accessing and check role access_user = User.query.filter_by(auth0_id=payload['sub']).first() role = access_user.role # if user role is "user", check if access user_id matches if role == 'user' and access_user.id != user_id: raise AuthError( { 'code': 'Invalid_claims', 'description': 'Unauthorized access by user' }, 401) # query reserations reservations = Reserve.query.filter_by(user_id=user_id).all() # query clothes clothes = [] for reservation in reservations: clothes.append(reservation.clothes.format()) return jsonify({ 'success': True, 'clothes': clothes, 'user': user.format() })
def delete_client(id): try: target_client = Client.query.filter_by(id=id).first() if target_client is None: raise AuthError( { 'code': 'client_not_found', 'description': 'There is no client with the reuqested id to delete.' }, 404) except AuthError as e: abort(e.status_code, e.error) target_client.delete() return jsonify({ 'success': True, 'deleted_client': target_client.format() })
def create_book(payload): body = json.loads(request.get_data()) name = body['name'] pages = body['pages'] try: author_id = body['author'] except KeyError: raise AuthError( { "error": "invalid_request", "description": "There is missing author in request" }, 400) except: abort(422) try: book = Book(name=name, pages=pages, author=author_id, reader=[]) book.insert() return jsonify({"book": book.format()}) except: abort(422, sys.exc_info()[0].__name__)
def delete_trainer(id): try: target_trainer = Trainer.query.filter_by(id=id).first() if target_trainer is None: raise AuthError( { 'code': 'trainer_not_found', 'description': 'There is no trainer with the reuqested id to delete.' }, 404) except AuthError as e: abort(e.status_code, e.error) target_trainer.delete() return jsonify({ 'success': True, 'deleted_trainer': target_trainer.format() })
def get_clients(): if request.get_json(): abort(405) try: clients = Client.query.all() if clients is None: raise AuthError( { 'code': 'no_clients', 'description': 'There are no clients on system yet.' }, 404) except AuthError as e: abort(e.status_code, e.error) clients_formatted = [] for client in clients: clients_formatted.append(client.format()) return jsonify({'success': True, 'clients': clients_formatted})
def get_sessions(): if request.get_json(): abort(405) try: sessions = Session.query.all() if sessions is None: raise AuthError( { 'code': 'no_sessions', 'description': 'There are no sessions on system yet.' }, 404) except AuthError as e: abort(e.status_code, e.error) sessions_formatted = [] for session in sessions: sessions_formatted.append(session.format()) return jsonify({'success': True, 'sessions': sessions_formatted})
def get_trainers(): if request.get_json(): abort(405) try: trainers = Trainer.query.all() if trainers is None: raise AuthError( { 'code': 'no_trainers', 'description': 'There are no trainers on system yet.' }, 404) except AuthError as e: abort(e.status_code, e.error) trainers_formatted = [] for trainer in trainers: trainers_formatted.append(trainer.format()) return jsonify({'success': True, 'trainers': trainers_formatted})
def post_geo_fence(): if requires_scope('blender.write'): try: assert request.headers['Content-Type'] == 'application/json' except AssertionError as ae: msg = {"message": "Unsupported Media Type"} return Response(json.dumps(msg), status=415, mimetype='application/json') else: geo_fence = json.loads(request.data) task = tasks.write_geo_fence.delay( geo_fence) # Send a job to the task queue op = json.dumps({"message": "Geofence submitted successfully"}) return Response(op, status=200, mimetype='application/json') raise AuthError( { "code": "Unauthorized", "description": "You don't have access to this resource" }, 403)
def delete_reservations(payload, user_id): """Delete all reservations which the given user has made. Users can delete reservations through their own user_id. AuthError will be returned if trying to delete reservations through another user's user_id. Staffs and managers can delete any reservations. Returns: json object with following attribute { "success": True, "clothes": list of formatted clothes of which reservations have been just deleted, "user": formatted user who has just canceled those reservations } """ # check if that user indeed exists user = User.query.get(user_id) if user is None: abort(404) # querying who is accessing and check role access_user = User.query.filter_by(auth0_id=payload['sub']).first() role = access_user.role # if user role is "user", check if access user_id matches if role == 'user' and access_user.id != user_id: raise AuthError( { 'code': 'Invalid_claims', 'description': 'Unauthorized access by user' }, 401) # delete reservations error = False formatted_user = user.format() reservations = Reserve.query.filter_by(user_id=user_id)\ .order_by(Reserve.clothes_id).all() try: formatted_clothes = [] for reservation in reservations: clothes = reservation.clothes clothes.status = "" formatted_clothes.append(clothes.format()) # commit deletion for reservation in reservations: reservation.delete() except Exception: for reservation in reservations: reservation.rollback() error = True print(sys.exc_info()) finally: for reservation in reservations: reservation.close_session() if error: abort(422) else: return jsonify({ 'success': True, 'clothes': formatted_clothes, 'user': formatted_user })
def create_reservations(payload, user_id): """Post reservations to our server. Users can post reservations through their own user_id. AuthError will be returned if trying to post reservations through another user's user_id. Returns: json object with following attribute { "success": True, "clothes": list of formatted clothes which has been just reserved, "user": formatted user who has just reserved those clothes } """ error = False # get posted data from json request body = request.get_json() keys = body.keys() # if request does not have json body, abort 400 if body is None: abort(400) # if json does not have key 'auth0_id', abort 400 if 'auth0_id' not in keys: abort(400) # if json does not have key 'reservation', abort 400 if 'reservations' not in keys: abort(400) # if auth0_id in body does not match auth0_id in payload, abort 401 if body['auth0_id'] != payload['sub']: abort(401) # query who is accessing access_user = User.query.filter_by(auth0_id=payload['sub']).first() # check if user_id in URL matches the access user id if user_id != access_user.id: raise AuthError( { 'code': 'Invalid_claims', 'description': 'Unauthorized access by user' }, 401) # query clothes and store them in variable "clothes" if not isinstance(body['reservations'], list): abort(400) for value in body['reservations']: if not isinstance(value, int): abort(400) # check if all clothes indeed exist clothes = [] for clothes_id in body['reservations']: # query clothes selection = Clothes.query.get(clothes_id) if selection is None: abort(404) # if that clothes has been already reserved, abort 422 if selection.status == "reserved": abort(422) clothes.append(selection) # query user user = User.query.get(user_id) formatted_user = user.format() # make reservations try: reservations = [] formatted_clothes = [] for item in clothes: new_reservation = Reserve() new_reservation.user = user new_reservation.clothes = item item.status = "reserved" reservations.append(new_reservation) # commit these reservations for reservation in reservations: reservation.insert() formatted_clothes.append(reservation.clothes.format()) except Exception: # rollback all sessions for reservation in reservations: reservation.rollback() error = True print(sys.exc_info()) finally: # close all sessions for reservation in reservations: reservation.close_session() if error: abort(422) else: return jsonify({ 'success': True, 'clothes': formatted_clothes, 'user': formatted_user })
def cancel_reservation(payload, clothes_id): """Users can cancel their own reservations. AUthError will be returned if user_id is not match. Staffs and managers can delete any reservation. Returns: json object with following attributes { 'success': True, 'clothes': formatted clothes of the given clothes_id, 'user': formatted user who has canceled that reservation } """ selection = Reserve.query.filter_by(clothes_id=clothes_id).all() # if the given clothes has not been reserved, abort 404 if len(selection) == 0: abort(404) # if two or more user reserved the same clothe, abort umprocessable if len(selection) >= 2: abort(422) # check if access user_id matches reservation user_id reservation = selection[0] # querying who is accessing and check role access_user = User.query.filter_by(auth0_id=payload['sub']).first() role = access_user.role # if user role is "user", check if access user_id matches # reservation user_id reservation_user = reservation.user if role == 'user' and access_user.id != reservation_user.id: raise AuthError( { 'code': 'Invalid_claims', 'description': 'Unauthorized access by user' }, 401) # query clothes clothes = reservation.clothes # set error status error = False # cancel that reservation try: clothes.status = "" reservation.delete() formatted_clothes = clothes.format() formatted_user = reservation_user.format() except Exception: reservation.rollback() error = True print(sys.exc_info()) finally: reservation.close_session() clothes.close_session() if error: abort(422) else: return jsonify({ 'success': True, 'clothes': formatted_clothes, 'user': formatted_user })