def meeting(meeting_id): if request.method == 'PUT': meeting_data = Meeting(**get_request_data(request), e_tag=request.headers.get('If-Match')) if not meeting_data.validate(): return json_response({"message": "Meeting form is invalid"}, 400) return meeting_data.update(db.meetings, meeting_id, db.rooms, g.user) elif request.method == 'GET': return find_one_response(db.meetings, meeting_id) else: return delete_one_response(db.meetings, meeting_id)
def put(self, username): """Update a user""" data = get_request_data(request) updated_user = keycloak_client.update_user_properties( username, keycloak_client.realm, **data) if updated_user: return jsonify(updated_user) else: return json_response( "Cannot update '{0}' properties. Check if client exists or properties are valid" .format(username), 400, )
def run_function(): data = utils.get_request_data() device = _select_device() if not device: return utils.make_json_response( 400, "Bad Request: No device available." ) code, status = _send_function_trigger(device.name, data) if code == 200: device.last_triggered = datetime.now() device.save() return utils.make_json_response(code, status)
def compare_live(): request_data = df.get_request_data(request) images = request_data.get('images') pattern = request_data.get('pattern', 'open-close-open') if (not images) or (not isinstance(images, list)): raise BadRequest( 'Invalid request body. List of images shoud be specified.') result, pattern = df.compare_live_image(images, request.headers.get('app_id')) out = {'status': 'success', 'message': result, 'pattern': pattern} return jsonify(out)
def compare_dp_cam_images(): request_data = df.get_request_data(request) dp = request_data.get('display_picture') cam_pic = request_data.get('cam_picture') if (not dp) or (not cam_pic): raise BadRequest( 'Invalid request body. display_picture and cam_picture should be sent.' ) result = df.compare_dp_cam_images(dp, cam_pic) out = {'status': 'success', 'message': result} return jsonify(out)
def register(): data = utils.get_request_data() if (models.User.objects.filter(username=data["username"]).count() > 0 or models.User.objects.filter(email=data["email"]).count() > 0): raise exception_handler.BadRequest("user already exist") user = models.User() user.username = data['username'] user.email = data['email'] user.password = data['password'] user.save() return utils.make_json_response(200, user.to_dict())
def update_algorithm(algorithm_id): data = utils.get_request_data() if not (set(data.keys()) <= set(UPDATE_ALGORITHM_FIELDS)): return utils.make_json_response( 400, "Invalid parameter keys: %s" % str(set(data.keys()) - set(UPDATE_ALGORITHM_FIELDS))) algorithm, error = _get_algorithm_by_id(algorithm_id) if error: return utils.make_json_response(**error) for k, v in data.items(): setattr(algorithm, k, v) algorithm.save() return utils.make_json_response(200, algorithm.to_dict())
def update_action(action_id): data = utils.get_request_data() if not (set(data.keys()) <= set(UPDATE_ACTION_FIELDS)): return utils.make_json_response( 400, "Invalid parameter keys: %s" % str(set(data.keys()) - set(UPDATE_ACTION_FIELDS))) action, error = _get_action_by_id(action_id) if error: return utils.make_json_response(**error) for k, v in data.items(): setattr(action, k, v) action.save() return utils.make_json_response(200, action.to_dict())
def create_algorithm(): data = utils.get_request_data() if not (set(data.keys()) <= set(CREATE_ALGORITHM_FIELDS)): return utils.make_json_response( 400, "Invalid parameter keys: %s" % str(set(data.keys()) - set(CREATE_ALGORITHM_FIELDS))) algorithm = models.Algorithm() for k, v in data.items(): setattr(algorithm, k, v) try: algorithm.save() except mongoengine.errors.NotUniqueError as e: return utils.make_json_response(409, e.__str__()) return utils.make_json_response(200, algorithm.to_dict())
def register_camera(): data = utils.get_request_data() camera = models.Camera() camera.name = data['name'] actions, errors = _validate_camera_actions(data['actions']) if not errors: camera.action_dict = actions else: return utils.make_json_response(400, errors) camera.streaming_url = RTMP_SERVER + '/' + data['name'] camera.last_updated = datetime.datetime.now() camera.save() notifier = CameraNotifier(camera.id, camera.streaming_url) notifier.notify_agent_start() return utils.make_json_response(200, camera.to_dict())
def put(self, protocol, client_id): """Update a client""" data = get_request_data(request) if (protocol == "saml") and ("definition" in data): data = keycloak_client.client_description_converter( data["definition"]) updated_client = keycloak_client.update_client_properties( client_id, **data) if updated_client: return jsonify(updated_client) else: return json_response( "Cannot update '{0}' properties. Check if client exists or properties are valid" .format(client_id), 400, )
def create_action(): data = utils.get_request_data() if not (set(data.keys()) <= set(CREATE_ACTION_FIELDS)): return utils.make_json_response( 400, "Invalid parameter keys: %s" % str(set(data.keys()) - set(CREATE_ACTION_FIELDS))) errors = _validate_action_params(data['params']) if errors: return utils.make_json_response(400, errors) action = models.Action() for k, v in data.items(): setattr(action, k, v) try: action.save() except mongoengine.errors.NotUniqueError as e: return utils.make_json_response(409, e.__str__()) return utils.make_json_response(200, action.to_dict())
def account_login(): req = get_request_data() with get_db_cursor(commit=True) as cur: cur.execute(''' SELECT account_id FROM accounts WHERE email = %(email)s AND password = %(password)s ''', req) res = cur.fetchone() if res is None: raise InvalidUsage('Email not found or password invalid.', 'email_or_password_invalid') else: account_id = res['account_id'] return success_response({'data': {'account_id': account_id}})
def user(u_login): if u_login != g.user.login: return json_response( {"message": "You are not allowed to see or modify different user"}, 403) if request.method == 'PUT': user_data = User(**get_request_data(request), e_tag=request.headers.get('If-Match')) if not user_data.validate(): return json_response({"message": "User form is invalid"}, 400) return user_data.update(db.users, u_login) elif request.method == 'GET': return find_one_response(db.users, u_login, 'login') else: return delete_one_response(db.users, u_login, 'login')
def register_device(): data = utils.get_request_data() device = models.Device() try: device.name = data['name'] except KeyError: return utils.make_json_response( 400, "Error registering device: device name not found." ) device.last_updated = datetime.now() try: device.save() except mongoengine.errors.NotUniqueError as e: return utils.make_json_response(409, str(e)) return utils.make_json_response(200, device.to_dict())
def login(): data = utils.get_request_data() try: user = models.User.objects.get(username=data["username"]) except models.User.DoesNotExist: user = None if not user or not user.verify_password(data["password"]): raise exception_handler.Unauthorized( "username or password does not match") success = login_user(user, data["remember_me"], True) user.last_login = datetime.datetime.now() user.save() identity_changed.send(current_app._get_current_object(), identity=Identity(user.username)) return utils.make_json_response(200, user.to_dict())
def store_image(): user = df.get_request_data(request) id = user.get('id') image = user.get('image') if (not id) or (not image): raise BadRequest( 'Invalid request body, id and image should be specified.') msg = df.save_image_in_db(id, image, request.headers.get('app_id')) if isinstance(msg, int): out = { 'status': 'success', 'message': 'image saved in db for user {}'.format(id) } return jsonify(out)
def cancel_appt_by_time(): data = utils.get_request_data() try: date = data['date'] start_time = data['start_time'] except KeyError: return utils.make_json_response( 400, "Sorry I cannot cancel your appointment " "without a date and a start time.") appt_time = datetime.strptime(date + ' ' + start_time, '%b %d %Y %I:%M%p') appt, error = _get_appt_by_appt_time(appt_time) if error: return utils.make_json_response( 404, "I am not able to find your appointment on %s, at %s" % (date, start_time)) appt.delete() return utils.make_json_response( 200, "Your appointment has been successfully canceled.")
def schedule_appt(): data = utils.get_request_data() try: start_time = data['start_time'] date = data['date'] except KeyError: return utils.make_json_response( 400, "Sorry I cannot schedule appointment:" " You did not specify a date and a time.") if not _validate_date(date): return utils.make_json_response( 400, "Sorry we are closed on weekends." " Appointments can only be scheduled from Monday to Friday.") if not _validate_start_time(start_time): appt_slots = list( map( lambda x: str(x - 12) + "PM" if x > 12 else str(x) + "AM" if x < 12 else str(x) + "PM", APPT_SLOTS)) return utils.make_json_response( 400, "Appointments can only be scheduled at " + " ".join(map(lambda x: "%s, " % x, appt_slots))) appt = models.Appointment() try: appt_time = datetime.strptime(date + ' ' + start_time, '%b %d %Y %H:%M') except ValueError: return utils.make_json_response(400, "You need to provide a valid time.") appt.appt_time = appt_time print(appt_time) try: appt.save() except mongoengine.errors.NotUniqueError as e: return utils.make_json_response(409, _unavailable_message(appt_time)) s_time = int(start_time.split(':')[0]) if s_time > 12: start_time = str(s_time - 12) + 'PM' elif s_time == 12: start_time = str(s_time) + 'PM' else: start_time = str(s_time) + 'AM' return utils.make_json_response( 200, "Your appointment is scheduled on %s, at %s" % (date, start_time))
def room(room_id): if request.method == 'PUT': room_data = Room(**get_request_data(request), e_tag=request.headers.get('If-Match')) if not room_data.validate(): return json_response({"message": "Room form is invalid"}, 400) return room_data.update(db.rooms, room_id) elif request.method == 'GET': return find_one_response(db.rooms, room_id) else: if find_one(db.meetings, room_id, 'room_id'): return json_response( { "message": "Cannot delete room because there is a meeting that is associated with " "that room" }, 400) return delete_one_response(db.rooms, room_id)
def account_signup(): req = get_request_data() with get_db_cursor(commit=True) as cur: cur.execute(''' SELECT account_signup(%(first_name)s, %(last_name)s, %(height)s, %(weight)s, %(sex)s, %(dob)s, %(email)s, %(password)s, %(diabetes_type)s, %(high_blood_pressure)s, %(pregnant)s, %(insulin_tdd)s, %(background_dose)s, %(pre_meal_target)s, %(post_meal_target)s) AS response ''', req) res = cur.fetchone()['response'] if not res['success']: raise InvalidUsage(res['message'], res['status']) return success_response({'data': {'account_id': res['account_id']}})
def transfer_meetings(u_login): user_data = find_one(db.users, u_login, 'login') if user_data is None: return json_response({"message": "User does not exist"}, 404) user_data = User(**user_data) data = get_request_data(request) if data.get('user_login') is None: return json_response( {"message": "Missing user_login in the request body"}, 400) new_user_data = find_one(db.users, data.get('user_login'), 'login') if new_user_data is None: return json_response({"message": "User does not exist"}, 404) new_user_data = User(**new_user_data) db.meetings.find_and_modify( query={"user_id": str(user_data.get_id())}, update={"$set": { "user_id": str(new_user_data.get_id()) }}) return json_response("", 200)
def update_camera(camera_id): data = utils.get_request_data() if not (set(data.keys()) <= set(UPDATE_CAMERA_FIELDS)): return utils.make_json_response( 400, "Invalid parameter keys: %s" % str(set(data.keys()) - set(UPDATE_CAMERA_FIELDS))) camera, error = _get_camera_by_id(camera_id) if error: return utils.make_json_response(**error) if 'name' in data.keys(): url = camera.streaming_url camera.streaming_url = url.replace(url.split('/')[-1], data['name']) if 'actions' in data.keys(): actions, errors = _validate_camera_actions(data['actions']) if errors: return utils.make_json_response(400, errors) data['action_dict'] = actions data.pop('actions', None) for k, v in data.items(): setattr(camera, k, v) camera.save() camera.last_updated = datetime.datetime.now() return utils.make_json_response(200, camera.to_dict())
def update_algorithm_result(camera_id): camera, error = _get_camera_by_id(camera_id) if error: return utils.make_json_response(**error) data = utils.get_request_data() for algorithm, result in data.items(): camera.algorithm_status[algorithm] = 'idle' try: action_list = camera.action_dict[algorithm][result] except KeyError: action_list = camera.action_dict[algorithm]['else'] for action in action_list: if not action: pass action_invoker = ActionInvoker(camera_id) action_invoker.invoke_action(action['params'], action['action']) # Algorithms cooldown time: 15 seconds. time.sleep(15) algorithm_invoker = AlgorithmInvoker(camera_id) algorithm_invoker.reactivate_algorithms([algorithm]) camera.save() return utils.make_json_response(200, {"status": "complete"})
def update_task(tasktitle): data = utils.get_request_data() try: task = models.Task.objects.get(title=tasktitle) except models.Task.DoesNotExist: raise exception_handler.BadRequest('task %s not exist' % tasktitle) print(data['content']) if data.get('title'): print(task.content) task.title = data['title'] if data.get('content'): task.content = data['content'] if data.get('status') and data['status'] in [ 'todo', 'ongoing' ] and datetime.datetime.now() > task.due_time: raise exception_handler.BadRequest('due time %s already passed' % task.due_time) if data.get('status') and data[ 'status'] == 'overdue' and datetime.datetime.now() < task.due_time: left_days, left_hours, left_minutes = utils.shifttimedelta( task.due_time - datetime.datetime.now()) raise exception_handler.BadRequest( 'still %s days %s hours %s minutes left' % (left_days, left_hours, left_minutes)) if data.get('status'): task.status = data['status'] if data.get('tags'): task.tags = data['tags'] if data.get('due_time'): task.due_time = datetime.datetime.strptime(data['due_time'], '%b %d %Y %I:%M%p') task.update_time = datetime.datetime.now() task.save() return utils.make_json_response(200, task.to_dict())
def post(self): data = get_request_data(request) validation = validate_protocol_data(data, self.auth_protocols) if validation: return validation return self.common_create(data)
def users(): if request.method == 'POST': user_data = User(**get_request_data(request)) if not user_data.validate(): return json_response({"message": "User form is invalid"}, 400) return user_data.create(db.users)
def account_signup(): req = get_request_data() facebook_user_id = None if 'facebook_auth_token' in req: try: fb = requests.get('https://graph.facebook.com/debug_token', params={ 'input_token': req['facebook_auth_token'], 'access_token': current_app.config['FB_ACCESS_TOKEN'] }).json() if 'error' in fb: error_msg = fb['error']['message'] error_type = fb['error']['type'] current_app.logger.error('{}: {}'.format( error_type, error_msg)) raise InvalidUsage(error_msg, error_type) if not fb['data']['is_valid']: raise InvalidUsage('Invalid Facebook login session.', 'invalid_facebook_login') facebook_user_id = fb['data']['user_id'] fb = requests.get( 'https://graph.facebook.com/v2.5/me?access_token={}' '&fields=email'.format(req['facebook_auth_token'])).json() if 'email' not in fb: raise InvalidUsage('Email from Facebook account is required', 'facebook_email_required') req['email'] = fb['email'] except RequestException as e: current_app.logger.error(e) raise InvalidUsage( 'Error contacting Facebook for ' 'authorization verification.', 'facebook_communication_error') req['password_hash'] = generate_password_hash(req['password']) req['facebook_user_id'] = facebook_user_id fields = [ 'account_type', 'username', 'first_name', 'last_name', 'company_name', 'email', 'phone_number', 'bio', 'latitude', 'longitude' ] for f in fields: if f not in req: req[f] = None # Set these fields to empty string if not present # Because they cannot be saved as NULL in database # TODO probably better to make fields empty by default in DB for f in ['first_name', 'last_name', 'company_name']: if not req[f]: req[f] = '' with db.get_db_cursor(commit=True) as cur: cur.execute( ''' SELECT account_signup (%(account_type)s, %(username)s, %(password_hash)s, %(first_name)s, %(last_name)s, %(company_name)s, %(email)s, %(phone_number)s, %(bio)s, %(latitude)s, %(longitude)s, %(facebook_user_id)s) AS response ''', req) res = cur.fetchone()['response'] if not res['success']: raise InvalidUsage(res['message'], res['status']) cur.execute( ''' SELECT row_to_json(accounts) as account_info FROM accounts WHERE account_id = %(account_id)s ''', res) account = cur.fetchone()['account_info'] # Send confirm email and SMS pin send_registration_email.delay(account) send_cell_phone_sms.delay(account) # Slack notif send_notif.delay(title='New Signup', first_name=account['first_name'], email=account['email'], username=account['username'], facebook_user_id=account['facebook_user_id']) errors = [] if 'facebook_auth_token' in req: try: remote = (requests.get( 'https://graph.facebook.com/v2.5/me' '?access_token={}&fields=cover'.format( req['facebook_auth_token'])).json())['cover']['source'] img = requests.get(remote) image_id = account_upload_and_resize_image( cur, BytesIO(img.content), 'cover.jpg', account['account_uuid'], 'cover', 'Facebook cover photo.', 'Retreived {}.'.format( datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) cur.execute( ''' UPDATE accounts SET cover_photo_id=%s WHERE account_uuid=%s ''', (image_id, account['account_uuid'])) except Exception: current_app.logger.exception( "Error retreiving cover photo from Facebook") errors.append('Error retreiving cover photo from Facebook.') try: img = requests.get( 'http://graph.facebook.com/v2.5/{}/picture?type=large'. format(facebook_user_id)) image_id = account_upload_and_resize_image( cur, BytesIO(img.content), 'profile.jpg', account['account_uuid'], 'profile', 'Facebook profile photo.', 'Retreived {}.'.format( datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) cur.execute( ''' UPDATE accounts SET profile_photo_id=%s WHERE account_uuid=%s ''', (image_id, account['account_uuid'])) except Exception: current_app.logger.exception( "Error retreiving profile photo from Facebook") errors.append('Error retreiving profile photo from Facebook.') resp = success_response( {'data': { 'account_uuid': account['account_uuid'] }}) if len(errors) > 0: resp['errors'] = errors return resp
def handle_exception(e): log.exception("Error for request => url: %s, data: %s, ip: %s, method: %s" % (request.url, get_request_data(request), request.remote_addr, request.method)) return render_template('errors/500.html'), 500
def access_denied(e): log.exception("Error for request => url: %s, data: %s, ip: %s, method: %s" % (request.url, get_request_data(request), request.remote_addr, request.method)) return render_template('errors/403.html'), 403
def verify_post_data(self, parameters): data = get_request_data(self.request) for k, v in parameters.items(): if data.get(k) in (None, ""): raise Exception(v) return data
def user_login(): login_data = LoginData(**get_request_data(request)) if not login_data.validate(): return json_response({"message": "Missing login or password"}, 400) return login_data.login_response(db.users)