Give Google Service Account access to all my Google Analytics Accounts - google-analytics

My work email has access to around 100 analytic accounts. Is there anyway give a google service account to all of the analytics I have access to with out needing to manually add it to every account?

Working off of Eike's comment, it seems to be possible from Google Apps Scripts:
function listAccounts() {
var accounts = Analytics.Management.Accounts.list();
if (accounts.items && accounts.items.length) {
for (var i = 0; i < accounts.items.length; i++) {
var account = accounts.items[i];
var body =
{
permissions:
{
local: ['READ_AND_ANALYZE'] //or whatever permissions you need
},
userRef:
{
email: 'theemailaddressyouneed'
}
};
Analytics.Management.AccountUserLinks.insert(body, account.id);
}
} else {
Logger.log('No accounts found.');
}
}
You will have to add the "Advanced Google Service" resource: Google Analytics API.
When you run it, you will also need to allow as a user who actually has permissions to add users to GA accounts.
Edit: I forgot to add, this seemed to create a new project for me in the developer console. I got an error message the first time about the project not having the API enabled. Click details or go to the dev console and find this project and enable the Google Analytics API.

Related

retrieve all events within a domain using Google Calendar API

I'm trying to retrieve all the events programmed within a domain entreprise.tn using Google Calendar API.
On google admin console, I create a new project and a new service account with owner role as described by that thread.
I enabled Google Calendar API and Admin SDK like described by that thread.
the list of scopes added on Admin console>Security are :
https://www.googleapis.com/auth/admin.directory.user, https://www.googleapis.com/auth/admin.directory.group, https://www.googleapis.com/auth/admin.directory.resource.calendar, https://www.googleapis.com/auth/calendar.events.readonly, https://www.googleapis.com/auth/calendar.readonly
My code is:
Calendar service = getCalendarService();
List<Event> items = new ArrayList<Event>();
String pageToken = null;
do
{
Events events = service.events().list("service-account-esp1#my-first-project-274515.iam.gserviceaccount.com").setPageToken(pageToken).execute();
items = events.getItems();
for (Event event : items)
{
System.out.println(event.getSummary());
}
pageToken = events.getNextPageToken();
} while (pageToken != null);
if (items.isEmpty())
{
System.out.println("Empty");
}
else
{
System.out.println("Exists");
}
the file my-first-project-274515-361633451f1c.json is the generated file when creating the service account and performing G Suite Domain-Wide Delegation of Authority.
the service-account-esp1#my-first-project-274515.iam.gserviceaccount.com is the client email
It looks ok, all the required configurations are done.
How evere, I got that exception:
avr. 18, 2020 12:28:59 PM
com.google.api.client.util.store.FileDataStoreFactory
setPermissionsToOwnerOnly AVERTISSEMENT: Unable to set permissions for
C:\Users\Administrateur\credentials, because you are running on a
non-POSIX file system. Charge Calendars: Sat Apr 18 12:28:59 BST 2020
a Exception in thread "main" java.lang.IllegalArgumentException at
com.google.common.base.Preconditions.checkArgument(Preconditions.java:128)
at
com.google.api.client.util.Preconditions.checkArgument(Preconditions.java:35)
at
com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets.getDetails(GoogleClientSecrets.java:82)
at
com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow$Builder.(GoogleAuthorizationCodeFlow.java:197)
at
tn.esprit.spring.google.calendar.Service.getCredentials(Service.java:75)
at
tn.esprit.spring.google.calendar.Service.getCalendarService(Service.java:90)
at tn.esprit.spring.google.calendar.Service.main(Test.java:102)
it's blocked on GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES).setDataStoreFactory(DATA_STORE_FACTORY).setAccessType("offline").build();
Could you please tell me what I missed ?.
Thanks in advance.
You should use mail user instead:
Events events = service.events().list(user#entreprise.tn)
.setOrderBy("startTime")
.setSingleEvents(true)
.execute();
HTH

Azure AD Application Add User to Active Directory using Client Credentials

I am trying to add a user to an application Active Directory but with little success. I am using the GraphServiceClient with.Net Core
The documentation here says I need these permissions
Azure AD Graph Client Beta Docs
Application Directory.ReadWrite.All
But I cannot find where in the Azure Portal I can assign this permission.
The code is above, the GraphServiceClient is in beta at the moment and this is not part of the API yet, so I am calling the request manually.
Below is my code for authentication, I am using my applications client secret which is set against the application in the AD. I can read directory data fine.
public async Task AuthenticateRequestAsync(HttpRequestMessage request)
{
try
{
if (null == _configuration)
{
throw new InvalidOperationException("Azure AD Configuration is not set");
}
var authContext = new AuthenticationContext(
$"{_configuration.Instance}/{_configuration.Domain}", false);
var credentials = new ClientCredential(_configuration.ClientId, _configuration.ClientSecret);
var authResult =
await authContext.AcquireTokenAsync("https://graph.microsoft.com/", credentials);
request.Headers.Add("Authorization", "Bearer " + authResult.AccessToken);
}
catch (Exception ex)
{
_logger.Error("Authentication Provider, unable to get token", ex);
}
}
Update - After checking with Rohit's advice, you can see I have the permissions set. But notice they are all in blue with the ticks next to them! I have changed and saved, you can see the save button is disabled. I have clicked Grant Permissions. Is this relevant?
But I cannot find where in the Azure Portal I can assign this
permission.
In Azure portal navigate to Azure Active Directory > App Registrations > Your specific app > Settings > Required Permissions
Click on Add and Select Microsoft Graph
Now, in the Application Permissions section, check "Read and write directory data"
Once you're done, do "Grant Permissions" for Admin consent, as this permission needs it.

Log out from restricted area without triggering security settings

I have a section that requires login and a certain role ("higher than 19"). Whenever I logout from it, I get
Error: permission_denied: Client doesn't have permission to access the desired data.
Reason for this are my security settings:
".read": "root.child('users').child(auth.uid).child('data').child('role').val() > 19",
My logout function:
// Sign out functionality
App.controller('SignOutCtrl', function($scope, $state, Auth) {
$scope.logout = function() {
// Go to landing page
$state.go('home');
// Log user out
Auth.$unauth();
};
});
App.factory('Auth', ['$firebaseAuth', function($firebaseAuth) {
var firebase = new Firebase('https://mysite.firebaseio.com/');
return $firebaseAuth(firebase);
}]);
The $state 'home' doesn't have any reading restrictions, looks like the log out actually happens before I'm being redirected to the 'home'-$state, which triggers the security restrictions.
I guess I'm struggling to understand the very basic concept of how to log out from a restricted site without triggering the security setting, can anyone please explain me how to do that properly?
I would suggest unauthenticating when the logout page is loaded instead of before leaving the restricted page.

Meteor.js google account : filter email and force account choser

In my Meteor.js application, I'm using the accounts-google package in order to be connected with a google account. I have two questions about it.
First, is there a simple way to filter the account used? I would like that the users can connect only with google accounts belonging to my company. Our google account mails end with #mycompany.com. So it would be a simple mail filtering.
I already done that with some post log in hooks but I was wondering if there was a simpler way for doing it.
My second question is how to force the opening of the google account choser. For now, if I try to connect with a wrong google account, and if I only added this account (like in gmail, drive, etc), the google choser doesn't pop and automatically connect with this wrong account. So, in this case, the user is totally blocked (my application disconnect him if he tries to log in with a wrong account but the google account module doesn't propose him to connect with another account).
Thank you for your help.
In order to restrict signup/login to your domain, simply do on the server:
var checkEmailAgainstAllowed = function(email) {
var allowedDomains = ['mycompanydomain.com'];
var allowedEmails = ['otheruser#fromotherdomain.com','anotheruser#fromanotherdomain.com'];
var domain = email.replace(/.*#/,'').toLowerCase();
email = email.toLowerCase();
return _.contains(allowedEmails, email) || _.contains(allowedDomains, domain);
};
Accounts.config({
restrictCreationByEmailDomain: function(email) {
if (!email) {
throw new Meteor.Error(403,'This email address is not allowed');
}
if (!checkEmailAgainstAllowed(email)) {
throw new Meteor.Error(403,'This email domain is not allowed');
}
return true;
}
});
And to login, you'll need on the client:
Meteor.loginWithGoogle({
forceApprovalPrompt: true, //this is what you want, to rerequest approval each time that prompts the google login prompt
loginStyle : "redirect", //or not, depending on your need
requestPermissions : ['profile', 'email'],
requestOfflineToken: true
}, function (err) {
if (err)
// set a session variable to display later if there is a login error
Session.set('loginError', 'reason: ' + err.reason + ' message: ' + err.message || 'Unknown error');
});
Side note:
Alternatively, you can set up your routes so that every time a new route is called, you login, and every time a route is destroyed or on windows's unload, you call logout. This causes login/logout roundtrip everytime the route changes, but you'll make sure that the new user always has a fresh session
Edit:
When you log out of your meteor app, you don't log out of google. That's how oauth works. So, basically, if you want a meteor log out to also log the user out of their google account, so that the next time they come back, they need to provide credentials again, you should do:
Meteor.logout(function(e) {
if (e) {
console.log("Could not log the user out")
} else {
window.location.replace('https://accounts.google.com/Logout');
}
});
This uses the callback of Meteor.logout() so that when the logout is successfull, the user is redirected to google's central account logout url where the user is also logged out of all google services.

$firebaseSimpleLogin and session without re-login

I am using $firebaseSimpleLogin to log into Firebase using email/password.
It is working rather well when I log in using email/password, I could see sessionkey being saved automatically as a cookie.
However, would like to remember the log in such that user only have to log in once.
So I included {rememberMe: true} during auth.
How do I check if the session is still alive at the beginning of the page being loaded?
From your question, I assume you're using Angular JS.
You can execute a run block on your main module, which is run everytime the page is loaded. I don't know much about Angularfire, this is the code I'm using on a hack day project to check auth and redirect to the login page if needed.
FirebaseRef is a wrapper that points to my Firebase instance.
This also makes sure that the currentUser object is available in all scopes.
var minib = angular.module('minib', ['ngRoute', 'firebase']);
minib.run(function($rootScope, $location, $firebaseSimpleLogin, firebaseRef) {
$rootScope.auth = $firebaseSimpleLogin(firebaseRef());
$rootScope.auth.$getCurrentUser().then(function(user) {
if (user) {
$rootScope.currentUser = user;
} else {
$location.path('/login');
}
});
});

Resources