Unable to load accounts with Google Analytics Api - google-analytics-api

I'm having issues trying to retrive accounts list with google analytics API.
I'm connecting without problems with Oauth2 granting right permission to my App.
$client = new Google_Client();
$client->setAccessType("offline");
$client->setIncludeGrantedScopes(true);
$client->setAuthConfig('path/to/credentials.json');
$client->addScope(array(Google_Service_Analytics::ANALYTICS));
$client->setRedirectUri(getRedirectUri());
...
I'm also able to do some queries with code like the following:
$service = new Google_Service_AnalyticsReporting($client);
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate("2019-01-01");
$dateRange->setEndDate("2019-06-30");
// Create the Metrics objects.
$sessions = new Google_Service_AnalyticsReporting_Metric();
$sessions->setExpression("ga:sessions");
$sessions->setAlias("ga:sessions");
...
When I try to retrive accounts list I receive an error 500
$analytics = new Google_Service_Analytics($client);
$accounts = $analytics->management_accounts->listManagementAccounts();
$items = $accounts->getItems();
print_r($accounts);
If I do instead
$analytics = new Google_Service_Analytics($client);
var_dump($analytics->management_accounts);
I'm able to see a json output where no listManagementAccounts is viewable and no account id is available.
Any suggestion on what I'm doing wrong?

I sorted it out deleting and creating again API credentials in Google Console.
Code was fine.

Related

Service Account for google sheets returns not found

I am trying to read a spreadsheet using a service account (I cannot use OAuth, which works, since the process will be running on a server to periodically check sheet data)
I tried several approaches. If I follow the example using oauth I can see the sheet values. However, I need the run the script without any GUI on the background.
I have found this tutorial https://github.com/juampynr/google-spreadsheet-reader
I have created a projec, service account, added viewer role, shared the spreadsheet with the service account email. Generated the key.
It seems that the test program can connect to the google services but the moment it request the spreadsheet the end result is "404 not found".
require 'vendor/autoload.php';
$service_account_file = '/secrets/readsheetmar2019-08b737d1c1cb._portfolio_test.json';
$spreadsheet_id = '1TAWybckPrnWlQxBZh0ScDsFOvftwi2dvTBNGarSdY30';
$spreadsheet_range = '';
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $service_account_file);
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope(Google_Service_Sheets::SPREADSHEETS_READONLY);
$client->fetchAccessTokenWithAssertion();
$service = new Google_Service_Sheets($client);
//added by me
if ($client->isAccessTokenExpired()) {
print "expired\n";
}else{
print "not expired\n";
}
$result = $service->spreadsheets_values->get($spreadsheet_id, $spreadsheet_range);
var_dump($result->getValues());
Error:PHP Fatal error: Uncaught exception 'Google_Service_Exception' with message '
Error 404 (Not Found)!!1
When the access token retrieved by OAuth2 is used, the Spreadsheet of $spreadsheet_id = '1TAWybckPrnWlQxBZh0ScDsFOvftwi2dvTBNGarSdY30'; can retrieve the values.
When the access token retrieved by Service Account is used, Error 404 (Not Found)!!1 is returned.
If my understanding is correct, please confirm the following points.
Confirmation points:
As a test run, please set the range $spreadsheet_range = '';.
For example, it's $spreadsheet_range = 'Sheet1'.
If the error message of The caller does not have permission is returned, please confirm as follows.
Whether the Spreadsheet of 1TAWybckPrnWlQxBZh0ScDsFOvftwi2dvTBNGarSdY30 is sharing the email of Service Account.
If you didn't share the Service Account to the Spreadsheet, please share the email of client_email in the file of readsheetmar2019-08b737d1c1cb._portfolio_test.json to the Spreadsheet you want to access.
If the error message of Google Sheets API has not been used in project ### before or it is disabled. is returned, please enable Sheets API.
If this was not the solution for your issue, I apologize.

How to use Azure AD Graph API to create a new AppRoleAssignment

I'm trying to figure out how to create a new appRoleAssignment using the Azure AD Graph API. (It appears that the newer Microsoft Graph does NOT support creating app role assignments just yet). I want to use the default role.
var assignment = new Dictionary<string, string>();
assignment["id"] = "00000000-0000-0000-0000-000000000000";
assignment["principalId"] = "user-guid";
assignment["resourceId"] = "service-principal-guid";
var url = "https://graph.windows.net/{tenant.onmicrosoft.com}/servicePrinciapls/{service-principal-guid}/appRoleAssignments";
I also tried posting to:
var url = "https://graph.windows.net/{tenant.onmicrosoft.com}/appRoleAssignments";
I'm POSTing the data in the hopes to create the assignment but it is giving a 404 error.
The assignment dictionary gets converted to JSON and posted.
In this answer we discussed the endpoint to GET app role assignments for a user. The same endpoint is the one you would POST to to create a new app role assignment:
POST https://graph.windows.net/{tenant-id}/users/{id}/appRoleAssignments?api-version=1.6
...
{
"principalId":"{user-object-id}",
"resourceId":"{service-principal-object-id}",
"id":"00000000-0000-0000-0000-000000000000"
}
(In the example above, we use 00000000-0000-0000-0000-000000000000 as the app role ID because we want to create a default assignment (i.e. "no role"). This would correspond to the id of an AppRole in the ServicePrincipal object if we wanted to assign the user to a specific app role.)
Instead of using the servicePrincipal collection, we need to use the user entity to create the appRoleAssignment for the users. Here is an example for your reference:
POST:https://graph.windows.net/{tenant}/users/{userObjectId}/appRoleAssignments?api-version=1.6
authorization: Bearer {access_token}
Content-Type: application/json
{
"id":"00000000-0000-0000-0000-000000000000",
"resourceId":"{servicePrincipId}",
"principalId":"{userObjectId}"
}

List Storage Accounts only listing a few classic storage accounts

List Storage Accounts https://management.core.windows.net//services/storageservices
says that it lists the storage accounts that are available in the specified subscription and the get storage account keys work only for these storage accounts that are returned as part of this call.
But the response is giving me only few storage accounts which are classic, how do i get the other storage accounts?
But the response is giving me only few storage accounts which are
classic, how do i get the other storage accounts?
By "other" storage accounts, I guess you're meaning "Azure Resource Manager (ARM)" storage accounts. There's a different API to get ARM storage accounts that make use of Azure AD based authentication.
To learn more about ARM API to list storage accounts, please see this link: https://learn.microsoft.com/en-us/rest/api/storagerp/storageaccounts#StorageAccounts_List.
To learn more about how to authenticate/authorize ARM API calls, please see this link: https://learn.microsoft.com/en-us/rest/api/
I agree with Gaurav Mantri, if you’d like to list ARM storage accounts under a specified subscription, please use this API:
GET https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.Storage/storageAccounts?api-version=2016-12-01
And the following code sample works fine on my side, please refer to it.
string tenantId = "{tenantId}";
string clientId = "{clientId}";
string clientSecret = "{secret}";
string subscriptionid = "{subscriptionid}";
string authContextURL = "https://login.windows.net/" + tenantId;
var authenticationContext = new AuthenticationContext(authContextURL);
var credential = new ClientCredential(clientId, clientSecret);
var result = await authenticationContext.AcquireTokenAsync(resource: "https://management.azure.com/", clientCredential: credential);
if (result == null)
{
throw new InvalidOperationException("Failed to obtain the JWT token");
}
string token = result.AccessToken;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(string.Format("https://management.azure.com/subscriptions/{0}/providers/Microsoft.Storage/storageAccounts?api-version=2016-12-01", subscriptionid));
request.Method = "GET";
request.Headers["Authorization"] = "Bearer " + token;
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.GetResponse();
//extract data from response
}
catch (WebException ex)
{
//ex.Message;
}
Besides, this article explained how to create AD application and service principal that can access resources, please refer to it.
Thanks for your response,by other storage accounts I meant the storage accounts under the classic storage accounts itself which were not getting listed.
Instead of using
https://management.core.windows.net//services/storageservices
I used the REST API's
for the new storage accounts
/management.azure.com/subscriptions/id/providers/Microsoft.Storage/storageAccounts?api-version=2016-12-01
for classic:
/management.azure.com/subscriptions//providers/Microsoft.ClassicStorage/storageAccounts?api-version=
and to get keys
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/listKeys?api-version=2016-12-01
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ClassicStorage/storageAccounts/{accountName}/listKeys?api-version=2016-11-01

[orientdb]: get the current user when authenticating with tokens

How can i get the rid of the current user (OUser) via the binary api. I am using the inbuilt token based authentication.
I would expect two approaches:
a function like currentUserRID() or something. I looked in the documentation but found nothing.
decrypting the token to unlock the userId/name. I tried this approach but couldn't manage to. I looked here: https://github.com/orientechnologies/orientdb/issues/2229 and also https://groups.google.com/forum/#!topic/orient-database/6sUfSAd4LXo
I find your post just now, may be is too late but you can do like this:
OServer server = OServerMain.create(); // for exemple
ODatabaseDocumentTx db = new ODatabaseDocumentTx(BDDURL).open("admin","admin"); // admin is juste for this exemple
OTokenHandlerImpl handler = new OTokenHandlerImpl(server);
OToken tok = handler.parseWebToken(yourtoken);
OUser user = tok.getUser(db);

SPFieldUserValue and SharePoint Metadata

I am using SPFieldUserValue to fetch the users from sharepoint list which is having person column. But my metadata service is facing some problem and it is showing error in navigation of my sharepoint site as -
"The Managed Metadata Service or Connection is currently not
available. The Application Pool or Managed Metadata Web Service may
not have been started. Please Contact your Administrator."
Does this have any connection to SPFieldUserValue function of sharepoint?
When i use this function i get the error as -
Value does not fall within the expected range
I just came across the problem which was causing the exception of value does not fall within the expected range.
I was trying to get list data and putting it into datatable and on datatable i was trying to fetch the user from sharepoint site.
Instead of datatable if i directly get data from sharepoint list, thn there is no exception.
Error Due to
DataTable dtrqacaml = RQA2list.GetItems(oRQA2Query).GetDataTable();
DataView dtview = new DataView(dtrqacaml);
DataTable dtdistinct = dtview.ToTable(true, "RQA_Manager2");
foreach(DataRow dr in dtdistinct.Rows)
{
SPFieldUserValue userValue = new SPFieldUserValue(SPContext.Current.Web, dr["RQA_Manager2"].ToString());
.
.
}
Error Resolution
foreach (SPListItem li in CClist.Items)
{
SPFieldUserValue userValue = new SPFieldUserValue(SPContext.Current.Web, li["CC_Person"].ToString());
.
.
}