Calling the metadata API in Apex requires admin permission (or at least the "Modify All Data" access). To run the code as a non-admin user I am thinking I need to first login as the sys admin, get a session ID, pass it to the request header, and then make the call. The problem is, I don't know how to do it inside Apex!
More precisely I need the readMetadata()
method in the Metadata API to run as an admin user. Here's how the method currently looks:
public MetadataAPI.IReadResult readMetadata(String type_x,String[] fullNames) {
MetadataAPI.readMetadata_element request_x = new MetadataAPI.readMetadata_element();
request_x.type_x = type_x;
request_x.fullNames = fullNames;
MetadataAPI.IReadResponseElement response_x;
Map<String, MetadataAPI.IReadResponseElement> response_map_x = new Map<String, MetadataAPI.IReadResponseElement>();
response_map_x.put('response_x', response_x);
WebServiceCallout.invoke(
this,
request_x,
response_map_x,
new String[]{endpoint_x,
'',
'http://soap.sforce.com/2006/04/metadata',
'readMetadata',
'http://soap.sforce.com/2006/04/metadata',
'readMetadataResponse',
'MetadataAPI.read' + type_x + 'Response_element'}
);
response_x = response_map_x.get('response_x');
return response_x.getResult();
}
Basically it's about unwrapping the WebServiceCallout class (it's what SF uses to call its API), putting the session ID into its header, and then re-wrapping it.
Let me know if you have any ideas to share!