Exemplo n.º 1
0
def deploy_profiles(request, job_id, object_name):
	"""
		AJAX endpoint for deploying profiles. Called when fields are finished deploying.
	"""

	job = get_object_or_404(Job, random_id = job_id)

	# If POST request made
	if request.method == 'POST':

		# Parse POST data into array
		all_fields = json.loads(request.body)

		# output data for debugging
		#print all_fields

		# If data exists, set job to deploy profiles
		if all_fields:

			try:

				deploy_profiles_async.delay(job, object_name, all_fields)

			except Exception as ex:

				page_response = {
					'success': False,
					'errorCode': 'Error creating task to deploy profiles',
					'message': ex
				}

				create_error_log('Delay Profile Deployment Error', ex)

		return HttpResponse(
			json.dumps({
				'success': True,
				'message': 'Successfully start profile job'
			}), 
			content_type = 'application/json'
		)

		# No POST method found - return error
	else:

		return HttpResponse(
			json.dumps({'error': 'No POST message.'}), 
			content_type = 'application/json'
		)
Exemplo n.º 2
0
def deploy_profiles(request, job_id, object_name):
    """
		AJAX endpoint for deploying profiles. Called when fields are finished deploying.
	"""

    job = get_object_or_404(Job, random_id=job_id)

    # If POST request made
    if request.method == 'POST':

        # Parse POST data into array
        all_fields = json.loads(request.body)

        # output data for debugging
        #print all_fields

        # If data exists, set job to deploy profiles
        if all_fields:

            try:

                deploy_profiles_async.delay(job, object_name, all_fields)

            except Exception as ex:

                page_response = {
                    'success': False,
                    'errorCode': 'Error creating task to deploy profiles',
                    'message': ex
                }

                create_error_log('Delay Profile Deployment Error', ex)

        return HttpResponse(json.dumps({
            'success':
            True,
            'message':
            'Successfully start profile job'
        }),
                            content_type='application/json')

        # No POST method found - return error
    else:

        return HttpResponse(json.dumps({'error': 'No POST message.'}),
                            content_type='application/json')
Exemplo n.º 3
0
def deploy_profiles_async(job, object_name, all_fields):
    """
		Async task to deploy profiles. This takes longer so is done silently
	"""

    # Deploy layouts - Have to use the Metadata SOAP API because the Tooling REST API wouldn't bloody

    #create_error_log('Reach tasks', '')

    try:

        # work with profiles
        metadata_client = Client(
            'http://fieldcreator.herokuapp.com/static/metadata-33.xml')
        metadata_url = job.instance_url + '/services/Soap/m/' + str(
            settings.SALESFORCE_API_VERSION) + '.0/' + job.org_id
        session_header = metadata_client.factory.create("SessionHeader")
        session_header.sessionId = job.access_token
        metadata_client.set_options(soapheaders=session_header)

        # Dictory of profiles to deploy
        profile_dict = {}

        # Iterate over fields to build profile deployment
        for field in all_fields:

            # Iterate over profiles within field
            for profile in field['profiles']:

                # Only add if at least read is given
                if profile['read']:

                    field_permission = metadata_client.factory.create(
                        'ProfileFieldLevelSecurity')
                    field_permission.field = object_name + '.' + field['name']
                    field_permission.editable = profile['edit']
                    field_permission.readable = profile['read']

                    # If key exists in dict - append new permission. Otherwise start new list and add permission
                    profile_dict.setdefault(profile['fullName'],
                                            []).append(field_permission)

        # Profile list to delpoy
        profile_deploy_list = []

        # If we have some profiles to deploy
        if profile_dict:

            # Iterate over dict
            for profile_name in profile_dict:

                # Create profile Metadata
                new_profile = metadata_client.factory.create("Profile")
                new_profile.fullName = profile_name

                # Get field permissions from dict
                new_profile.fieldPermissions = profile_dict[profile_name]

                # List of profiles to deploy
                profile_deploy_list.append(new_profile)

        # If profiles to deploy
        if profile_deploy_list:

            try:

                # Only allowed to deploy 10 at a time. Split deploy list into chunks
                for profiles_to_deploy in chunks(profile_deploy_list, 10):

                    result = metadata_client.service.updateMetadata(
                        profiles_to_deploy)

                    # Print result
                    create_error_log('Deploy Profiles Result', str(result))

                    # Capture error if exists
                    if not result[0].success:

                        create_error_log('Deploy Profiles Error', str(ex))

            except Exception as ex:

                create_error_log('Deploy Profiles Error', str(ex))

    except Exception as ex:

        create_error_log('Deploy Profiles Error', str(ex))
Exemplo n.º 4
0
def deploy_field(request, job_id, object_name):
    """
		AJAX endpoint to deploy a field. Fields are deployed one-by-one
	"""

    job = get_object_or_404(Job, random_id=job_id)

    # If POST request made
    if request.method == 'POST':

        # Parse POST data into array
        field_data = json.loads(request.body)

        # Output form data
        #print field_data

        # URL to send deploying data
        request_url = job.instance_url + '/services/data/v' + str(
            settings.SALESFORCE_API_VERSION
        ) + '.0/tooling/sobjects/CustomField/'

        # Set headers for POST request
        headers = {
            'Accept': 'application/json',
            'X-PrettyPrint': 1,
            'Authorization': 'Bearer ' + job.access_token,
            'Content-Type': 'application/json'
        }

        # Set data (the field to deploy)
        data = {
            'Id': None,
            'FullName': object_name + '.' + field_data['name'],
            'Metadata': build_metadata_for_field(field_data)
        }

        # Output POST data
        #print data

        # Response array for the page
        page_response = {}

        # Make RESTful POST
        try:

            r = requests.post(request_url,
                              headers=headers,
                              data=json.dumps(data))
            page_response = r.json()

        except Exception as ex:

            page_response = {
                'success': False,
                'errorCode': 'Error connecting to Tooling API',
                'message': ex
            }

            create_error_log('Deploy Field Error', ex)

        # Return the POST response
        return HttpResponse(json.dumps(page_response),
                            content_type='application/json')

    # No POST method found - return error
    else:

        return HttpResponse(json.dumps({'error': 'No POST message.'}),
                            content_type='application/json')
Exemplo n.º 5
0
def deploy_profiles_async(job, object_name, all_fields):
	"""
		Async task to deploy profiles. This takes longer so is done silently
	"""

	# Deploy layouts - Have to use the Metadata SOAP API because the Tooling REST API wouldn't bloody

	#create_error_log('Reach tasks', '')

	try:

		# work with profiles
		metadata_client = Client('http://fieldcreator.herokuapp.com/static/metadata-33.xml')
		metadata_url = job.instance_url + '/services/Soap/m/' + str(settings.SALESFORCE_API_VERSION) + '.0/' + job.org_id
		session_header = metadata_client.factory.create("SessionHeader")
		session_header.sessionId = job.access_token
		metadata_client.set_options(soapheaders = session_header)

		# Dictory of profiles to deploy
		profile_dict = {}

		# Iterate over fields to build profile deployment
		for field in all_fields:

			# Iterate over profiles within field
			for profile in field['profiles']:

				# Only add if at least read is given
				if profile['read']:

					field_permission = metadata_client.factory.create('ProfileFieldLevelSecurity')
					field_permission.field = object_name + '.' + field['name']
					field_permission.editable = profile['edit']
					field_permission.readable = profile['read']

					# If key exists in dict - append new permission. Otherwise start new list and add permission
					profile_dict.setdefault(profile['fullName'], []).append(field_permission)

		# Profile list to delpoy
		profile_deploy_list = []

		# If we have some profiles to deploy
		if profile_dict:

			# Iterate over dict
			for profile_name in profile_dict:

				# Create profile Metadata
				new_profile = metadata_client.factory.create("Profile")
				new_profile.fullName = profile_name

				# Get field permissions from dict
				new_profile.fieldPermissions = profile_dict[profile_name]

				# List of profiles to deploy
				profile_deploy_list.append(new_profile)


		# If profiles to deploy
		if profile_deploy_list:

			try:

				# Only allowed to deploy 10 at a time. Split deploy list into chunks
				for profiles_to_deploy in chunks(profile_deploy_list, 10):

					result = metadata_client.service.updateMetadata(profiles_to_deploy)

					# Print result
					create_error_log('Deploy Profiles Result', str(result))

					# Capture error if exists
					if not result[0].success:

						create_error_log('Deploy Profiles Error', str(ex))

			except Exception as ex:

				create_error_log('Deploy Profiles Error', str(ex))

	except Exception as ex:

		create_error_log('Deploy Profiles Error', str(ex))
Exemplo n.º 6
0
def deploy_field(request, job_id, object_name):
	"""
		AJAX endpoint to deploy a field. Fields are deployed one-by-one
	"""

	job = get_object_or_404(Job, random_id = job_id)

	# If POST request made
	if request.method == 'POST':

		# Parse POST data into array
		field_data = json.loads(request.body)

		# Output form data
		#print field_data

		# URL to send deploying data
		request_url = job.instance_url + '/services/data/v' + str(settings.SALESFORCE_API_VERSION) + '.0/tooling/sobjects/CustomField/'
		
		# Set headers for POST request
		headers = { 
			'Accept': 'application/json',
			'X-PrettyPrint': 1,
			'Authorization': 'Bearer ' + job.access_token,
			'Content-Type': 'application/json'
		}

		# Set data (the field to deploy)
		data = {
			'Id': None,
			'FullName': object_name + '.' + field_data['name'],
			'Metadata': build_metadata_for_field(field_data)
		}

		# Output POST data
		#print data

		# Response array for the page
		page_response = {}

		# Make RESTful POST
		try:

			r = requests.post(request_url, headers = headers, data = json.dumps(data))
			page_response = r.json()

		except Exception as ex:

			page_response = {
				'success': False,
				'errorCode': 'Error connecting to Tooling API',
				'message': ex
			}

			create_error_log('Deploy Field Error', ex)

		# Return the POST response
		return HttpResponse(
			json.dumps(page_response), 
			content_type = 'application/json'
		)

	# No POST method found - return error
	else:

		return HttpResponse(
			json.dumps({'error': 'No POST message.'}), 
			content_type = 'application/json'
		)