def get_or_update_user(username): ''' GET: Returns the user info (username) PUT: Updates user info (pwd) DELETE: Deletes user ''' try: user = User.objects.get(username=username) except User.DoesNotExist: raise UserException('User does not exist.') if request.method == 'GET': return jsonify(username=user.username, message='User retrieved successfully') elif request.method == 'PUT' and g.user.username == username: # Method should be used only for changing password try: user.hash_password(request.json['password']) user.save() return jsonify(message='Password updated successfully.') except: raise BadRequestException('There was an error in the request.') elif request.method == 'DELETE' and auth.username == username: user.delete() return jsonify(message='User deleted.') else: raise BadRequestException( 'Your request was not understood by the server.')
def decorated_function(*args, **kwargs): """ Function to check headers are present and check their validity """ logger.info("Secured decorator has started") logger.debug("Details passed to the secured decorator", extra={"headers": request.headers}) if "x-remote-user" in request.headers: username = request.headers["x-remote-user"] if "x-remote-user-groups" in request.headers: groups = request.headers["x-remote-user-groups"] logger.info(f"Groups from header: {groups}") groups = groups.split(",") # map groups to roles roles = [] for group in groups: if group in group_role_map: roles.extend(group_role_map[group]) logger.info("Raw roles list: {groups}".format(groups=roles)) roles = list(set(roles)) return f(username, roles, *args, **kwargs) else: logger.info( "X-Remote-User-Groups header is missing from request") raise BadRequestException( "X-Remote-User-Groups header is missing") else: logger.info("X-Remote-User header is missing") raise BadRequestException("X-Remote-User header is missing")
def create_user(): ''' Assumes a request with Content-Type: application/json. The json should be of the form: { "username":<username>, "password":<password> } ''' user_data = request.json # check that the request is well formed. if 'username' not in user_data or 'password' not in user_data: raise BadRequestException('Malformed request.') # check that user does not exist if User.objects(username=user_data['username']).first(): raise UserException('Username already exists.') else: user = User(username=user_data['username']) user.hash_password(user_data['password']) user.save() token = create_token(user) return jsonify(message='User created successfully.', user=user.to_json(), token=token)
def change_instance(username, roles, instanceid): instance = get_instances_by_username_and_id(username=username, instanceid=instanceid) logger.info(f"Got instance data {instance}") if len(instance) > 0: # check request is valid if request.json: missing = check_for_keys(dict=request.json, keys=["state"]) if missing: raise BadRequestException( f"The following keys are missing from the request: {missing}" ) else: if request.json["state"] not in ["stopped", "running"]: raise BadRequestException("Invalid state request") else: if request.json["state"] == "stopped": stop_instance( instanceid=instance[instanceid]["instanceid"]) return success_json_response({ "desktop_id": instanceid, "status": "okay", "message": "stopping instance" }) elif request.json["state"] == "running": start_instance( instanceid=instance[instanceid]["instanceid"]) return success_json_response({ "desktop_id": instanceid, "status": "okay", "message": "starting instance" }) else: raise BadRequestException("Request should be JSON") else: raise ResourceNotFoundException( f"An instance with id '{instanceid}' was not found")
def decorated_function(*args, **kwargs): """ Function to check headers are present and check their validity """ if "roles" in kwargs: if "admin" in kwargs["roles"]: return f(*args, **kwargs) else: logger.info("User does not have admin role") raise AccessDeniedException("Required role is not present") else: logger.info("Roles kwarg is missing") raise BadRequestException("Could not find role information")
def _return_response(self, response, returnHeader=False): if response.status_code in SUCCESS_CODES: try: if returnHeader: return (response.headers, response.json()) return response.json() except ValueError: if returnHeader: return (response.headers, {'text': response.text}) else: return {'text': response.text} elif response.status_code in APPLICATION_ERRORS: raise ServiceUnavailableException(response.text) elif response.status_code in USER_ERRORS: raise ForbiddenException(response.text) else: raise BadRequestException(response.text)
def _return_response(self, response, returnHeader=False): """ returns the response object if the call was successful else raises the appropriate error """ if response.status_code in SUCCESS_CODES: try: if returnHeader: return (response.headers, response.json()) return response.json() except ValueError: if returnHeader: return (response.headers, {'text': response.text}) else: return {'text': response.text} elif response.status_code in APPLICATION_ERRORS: raise ServiceUnavailableException(response.text) elif response.status_code in USER_ERRORS: raise ForbiddenException(response.text) else: raise BadRequestException(response.text)
def create_instance(username, roles): # check if the request is JSON if request.json: missing = check_for_keys( dict=request.json, keys=["action", "machine_def_id", "screen_geometry"]) if missing: raise BadRequestException( f"The following keys are missing from the request: {missing}") else: if request.json["action"] not in ["create"]: raise BadRequestException("Invalid action") if request.json["screen_geometry"] not in [ "1920x1080", "1280x720" ]: raise BadRequestException("Invalid screen geometry") # get entitlements entitlements = get_entitlements_for_roles(roles, username) selected_entitlement = None for entitlement in entitlements: if entitlement["machine_def_id"] == request.json[ "machine_def_id"]: selected_entitlement = entitlement if selected_entitlement: if selected_entitlement[ "total_allowed_instances"] - selected_entitlement[ "current_instances"] > 0: # we can provision it # get machine def machine_def = get_machine_def( machine_def_id=selected_entitlement["machine_def_id"]) desktop_id = get_rand_string(8) # if an override id was set then use it if "desktop_id" in request.json: desktop_id = request.json["desktop_id"] # create task to provision response = create_desktop_instance( desktop_id=desktop_id, ami_id=machine_def["ami_id"], machine_username=username, screen_geometry=request.json["screen_geometry"], machine_def_id=selected_entitlement["machine_def_id"], instance_type=machine_def["instance_type"], user_data=machine_def["user_data"]) if response: return success_json_response({ "desktop_id": desktop_id, "status": "okay", "message": "created task to create instance" }) else: return success_json_response({"status": "error"}) else: raise NoAvailableCapacity( "No available capacity to start this instance") else: raise ResourceNotFoundException( "No matching machine_def found") else: raise BadRequestException("Request should be JSON")
def validate_file(request): """Validate request and raise an Exception if necessary""" if not _validate_file_structure(request): raise BadRequestException('Request structure is not valid.') elif not _validate_content_type(request.files['file_name']): raise BadRequestException('Invalid content type given.')