How to force subscribe a user in your domain to a Google Calendar with Google Apps Script.

force subscribe a user in your domain to a Google Calendar with Google Apps Script

If you have tried to seamlessly subscribe a user to a Google Calendar as part of an automation workflow in Google Apps Script and discovered that all that happens is that the user gets an automated email request to join, and then it is up to them to accept the calendar invitation to add it to their live calendar list, you’re in the right place.

While providing an invitation gateway makes a lot of sense for Google Workspace consumer(free) accounts where you don’t want strangers to subscribe you to calendars that you don’t want to be a member of, it can be a little frustrating for Google Workspace business and organisations that need users to see a particular calendar.

You’ve probably experienced this, but you can’t always rely on your users to accept these invitations to add a calendar. Then down the track, the user is left scratching their head wondering why they are not getting the calendar events like everyone else.

Some reasons why you might need to force subscribe a user to a calendar

Think of it this way, imagine you’ve just started work at your new company and as a part of your onboarding process, you’ve accepted an invite to your new Google Workspace domain email and now have a bunch of calendar invites to accept. Plus learn everything you need to about the job. You’re likely to forget.

What about if you are transferring to a new branch in the company or your manager created a new Google Group for you to work under and they have shared a calendar to a Group. Well, guess what? You won’t even get an email to invite you to the group. You won’t even know you are a member.

What about if you need to add new students to classes and each class shares a classroom calendar. Can you expect all the little darlings to accept the calendar invite?

What you’ll need.

In this tutorial, we will assume that you are working on a Google Workspace Domain (paid account) and that you are on speaking terms with your Google Workspace Super Admin (Hint! Snacks are their weakness!)

Force subscribing users to a Google Calendar isn’t as easy as it used to be. Before we even write our code we will need to:

  1. Create or assign a Google Cloud Project.
  2. Create a Service Account.
  3. Supplicate yourself to your Google Workspace Super Admin and request Domain-wide Delegation of Authority for your project.
  4. Add the service account JSON to your script.
  5. Add an OAuth library to your script.

via GIPHY

This means traversing the Dark Woods of Google known as the Google Cloud Console. Don’t worry, I will step you through the process with instructions and images and get you back to the safety of your trusty Google Apps Script IDE so that we can finally write some code.

Set up

The first thing we need to do is to create a new Google Apps Script project.

Head over your script.google.com and create a stand-alone project and give it a title and save.

Adding the OAuth2 Library

We’ll also be using the OAuth2 for Apps Script library for our project. This is an open-source library gifted from Google Workspace devs and updates and supported by the community.

To add the library copy the following ID:

1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF

In your Apps Script IDE on the left sidebar select the + next to the Libraries header (1). A popup dialogue will appear. Paste in the ID (2).

Select Lookup (3). If you pasted in the ID successfully, you’ll see a version appear along with a suggested identifier.

Select Add (4). The dialogue will close and you should see the library appear in your Libraries list in the sidebar (5).

Adding the OAuth2 library to Google Apps Script ID
Click to expand!

Creating A Service Account

Creating a Google Cloud service account will allow us to impersonate a user in our domain so that we can programmatically accept and display a calendar after it has been shared with them.

The service account will generate a custom email address along with credentials in JSON form for you to use to call the service account in your script.

Time to head over to the Google Cloud Console. Yeah, I know scary stuff. Take a breath and we will do this together.

Let’s go!

Link to: Google Cloud Console✨✨✨

Select a Google Cloud Project

In the top menu bar, you will see a selected account (The console will usually open to the last project you were working on). If you are happy to work in this project skip to the next bit.

Click on the project name and a dialogue will appear.

Force Subscribe Users to Calendar_Create or select an account

Either select an existing account or create a NEW PROJECT.

Force Subscribe Users to Calendar_Create or select an account2
Click to expand!

If you are creating a new project, you will be navigated to a new page. All you need to do here is to create a name for your project (1), ensure that your organisation and locations are pointed to the domain you are working in and then hit Create (3).

Force Subscribe Users to Calendar_Create a project

You will then be navigated to your new project dashboard.

Note! You do not need to connect your Google Apps Script project to the Google Cloud project. They can run independently.

Get to the service account page

You can get to the service account page in a number of ways:

  1. In the sidebar, select IAM and admin > Service accounts

    Force Subscribe Users to Calendar_get to service account page1
    Click to expand!
  2.  From the search menu at the top type “Service Accounts”.

    Force Subscribe Users to Calendar_get to service account page2
    Click to expand!
  3. Or via this link (https://console.cloud.google.com/iam-admin/serviceaccounts) and then select your project.

Create the service account

On the Service Account sub-menu bar select Create Service Account. 

Force Subscribe Users to Calendar_create a service account

Add the title you will give the service account (1). Note that you will see the Service Account ID update automatically (2). You can change it but we will leave it. Also, note there that you can see your service account email address being built too.

Next, add a description so you know in 3 months time what on earth you were building here (3).

Finally, select Create and Continue (4).

Force Subscribe Users to Calendar_create a service account step1

Next, you will be given the option to “Grant this service account access to the project”. Now that you have created your very own non-human entity in the form of a service account (beep bop boop blerg!), you can assign the account certain roles with certain permission in the connected project.

Let’s hold off on the A.I. apocalypse for now and skip this step.

Force Subscribe Users to Calendar_create a service granting access to project

Lastly, you can grant access to what users or groups can impersonate or access the service account. This is useful if you only want a select group to have access. If we leave it blank it will stay open for anyone who has access to the script to run the service account to be able to use it. Let’s skip this for this tutorial.

Force Subscribe Users to Calendar_create a service account granting user access

Get the Service Account key

After you click done you will be sent back to the main Service Accounts page of your project. We’ll need to create an account key.

Click on the vertical ellipses on the right our your new service account. Select Manager keys.

Force Subscribe Users to Calendar_created service account v2
Click to expand!

A new page will appear. Select Add key > Create new key.

Force Subscribe Users to Calendar_created service account key

A dialogue box will pop up. Ensure that JSON is selected and then select create. Your JSON key will now be downloaded and another dialogue box will appear. Select Close. 

Go ahead and open up the JSON file you downloaded. Select the contents and head over to your Google Apps Script project.

Create a new *.gs file and name it ‘AUTH’. Set a global constant variable as AUTH and paste in your JSON data. Your AUTH.gs file should look a little like this:

Save your apps script project and head back to the Service Account cloud console.

Add the Calendar API & Scope

Add the Calendar API to the project

Next, we need to add the Calendar API to the service account project.

In the search menu of your Google Cloud console type “Calendar API” (1). It should be the first option that comes up.  Give it a good old click (2)

Force Subscribe Users to Calendar_add Calendar API 1

You should now see the Calendar API page. Select Enable.

Get the Calendar Scopes

We also need the authorisation scopes for our calendar project. We can find them by searching the Google API scope lists under the Calendar API. Or copy and paste  the scope below into a comment in your Google Apps Script project for now:

// https://www.googleapis.com/auth/calendar

Get Domain-wide Delegation of Authority for your project

Now it’s time to make friends with your favourite Google Workspace super administrator (Remember the snacks!). If that’s you, well it’s time to reconcile that self-loathing and re-friend yourself, you amazing, beautiful human! 🐐♥

via GIPHY

Domain-wide delegation of authority allows apps to access user data or act on a user’s behalf to carry out an action. For our tutorial, we want to accept a calendar from us, the dev, and add it to their calendar list.

You will need access to the Admin console to authorise your Service Account for this. Click on the link below to get there:

Google Workspace Admin Console

In the sidebar menu select Security > Access and data control > API controls. Or use this link:

https://admin.google.com/ac/owl/domainwidedelegation

Force Subscribe Users to Calendar_Domain wide delegation of authority API ControlsScroll down the page to the Domain Wide Delegation section and select Manager Domain Wide Delegation.

Force Subscribe Users to Calendar_Manager Domain Wide Delegation link
Click to Expand!

Next, select Add new and a dialogue box will appear (1).

You can find the Client ID in the JSON file that you downloaded and put into the variable AUTH in your ‘AUTH.gs’ file. In our example file above you can find it on line 12 as 100394991316082213951 (2):

Copy and paste in your scope that you saved previously: https://www.googleapis.com/auth/calendar (3)

Then hit Authorise (4).

 

Force Subscribe Users to Calendar_Manager Domain Wide Delegation Add new client ID
Click to Expand!

You should sheet your new API client added to your list:

Force Subscribe Users to Calendar_Manager Domain Wide Delegation new client added

Your all done here. Now go ahead and close the Admin Console and head back to your Google Apps Script project, because guess what? It is time to code. Yay!!!!!

Note! The layout and navigation of certain parts of the Google Workspace Admin Console can change quite regularly I’ve noticed over the years. Even at the time of writing this, I noticed that Google’s documentation on the topic was a little out of date. You may have to bounce from this tutorial to Googles docs or search around on your own to figure out the updated locations. It shouldn’t be too hard to figure out. 

The Code…finally!!!

We’ve finally made it to the part we love the most, the code. Here is the full code below with an example runsies() function to run the code that you can copy, paste and update into your own project.

The script basically runs a two-step process.

First, we run the shareCalendar() function to share our calendar from our list of calendars with the selected user.

Second, we assume the selected user’s account and accept the subscription invite to the calendar and display it in their calendar list.

Before running the code out in the wild it is probably a good idea to test it on a dummy user account different from your own or an account of someone who is happy to be your test user.

 

 

Looking to learn more about Google Apps Scripts in a more structured format? Udemy has some great courses that can get you from the basics to a real Google Apps Script pro.

Got a more specific problem you need help with, but don’t have the time to develop the skills? Make an enquiry on my 'Hire me!' page. I occasionally pick up projects. Alternatively, Fiverr’s your best bet to find a skilled Google Apps Script developer to solve your problem quickly and professionally. *

*The above affiliate links have been carefully researched to get you to what you specifically need. If you decide to click on one of these links it will cost you just the same as going to the site. If you decide to sign up, I just get a little pocket money to help pay for the costs of running this website.

runsies()

The runsies() function is an example function that runs the function to share the calendar with the user and then runs the function to add the calendar to the user’s calendar list.

We need to set 3 main variables for this project:

  1. The user’s email.
  2. The calendar that we want to share. To find the calendar email (kinda looks like a service account doesn’t is 😉) go to your Google Calendar and select the calendar that you want to share by clicking on the 3 vertical ellipses that appear when you hover over it. Then select Settings and sharing. 
    Google Calendar Setting and Sharing option
    Select Integratecalendar(1). You will find the id under Calendar ID (2).
    Calendar Setting Integrate Calendar Calendar ID
  3. me, my email: This is the email of the user running the script. We use the Google Apps Script Sessions class to get the active user and then apply the getEmail() method to get their email. This saves having to re-enter the person’s email each time we run the script.

Next, we run the shareCalendar(calendar, me, user) function which will share the selected calendar with the user. Once the calendar is shared, we run the addCalendarToUserList(user, calendar) function.

getOAuthService(user)

The getOAuthService(user) function calls our OAuth2 library with our selected parameters so that we can assume our service accounts identity.

The function takes the user whose identity that we will assume as an argument.

We run this function two times for our project from:

  • shareCalendar() – Here the user is our own account or the variable we defined as me. So that we can assume our own account.
  • addCalendarToUserList() – Here the user argument is the user to who we wish to add our calendar too.

Note that the private key and the issuer on lines 11 and 12  are both collected from our AUTH object in our ‘AUTH.gs’ file.

You can also see that the subject on line 13 is set to our user email parameter.

shareCalendar(calId, me, user)

The shareCalendar() function assumes the active user account and then sends a post request to the Google Calendar API to add a new user to the selected calendar with the role, ‘reader’.

Note! You could use the inbuild Calendar API advance service and not worry about calling the getOAuthService(me) function here, but I decided for a bit of consistency and to better show how the service account works to use the service account. You can find an example of this in a previous tutorial on this topic here: 

Google Apps Script: How to force subscribe Google Group Members to a Google Calendar for G Suite [Update 06 Apr 2022]

This function takes 3 arguments:

  1. calId – the calendar  ID.
  2. me – the currently active user running the script.
  3. user – the user who the active user wants to share their calendar with.

Set up the service account

Our first task is to create a new instance of our getOAuthService(me) (This is done behind the scenes in the OAuth library). Note here that we assume the me variable to act as the user running the script. Line 11

After we reset the service (Line 12), effectively flushing the service’s stored data, we check to see that we have access to our service account before setting up to send our request to the Google Calendar API (Line 14).

The Google Calendar API – ACL

To assign access privileges to a calendar we will post to the aptly name Access Control List or ACL method.

This method is called from the HTTP request:

https://www.googleapis.com/calendar/v3/calendars/${calId}/acl

Here we add our calendar id from our calId parameter and assigned it to our endPoint function. Line 23

The request will require a set of header information that includes the content type which will be in JSON format (Line 28) and the Authorisation. The authorisation details are generated for us by the OAuth library that we assigned to our service variable. We call the getAccessToken() of this library to display the access token here. Line 29

The request also takes a payload containing a JSON object with the properties that we wish to change. If you look up at lines 16 to 19, you can see that we have set the role to have ‘reader’ access only (Line 16), then assigned our user email to the scope as a user (not a group email).

Fetching the HTTP request

On line 25, we use the fetch() method in the Google Apps Script UrlFetchApp class to send our HTTP request to the Calendar API.

The first argument is our HTTP request URL in the endPoint variable.

The second argument is an object containing our method (POST), headers, and payload for our request.

When this fetch request is made and is successful it will return a JSON object containing a summary of the changes that will look similar to this:

We have logged this just out of interest here and you could delete the console log if you wish. We have also returned this response out of the shareCalendar() function should you wish to use it for something else.

addCalendarToUserList(user, calendar)

The addCalendarToUserList(user, calendar) function first assumes the user’s account before accessing their calendar list accepting the new calendar and displaying it in their list.

The function takes two arguments:

  • user: the user who received the new calendar subscription request.
  • calendar: the calendar id (email).

Note: I’ve already covered a lot of the same workflow in the shareCalendar() function. So I will only cover the differences below. 

As you can see, setting up the OAuth service is virtually the same. In this function, however, we set the argument for getOAuthService(user) to the user so we can work on their behalf.

The Google Calendar API – Calendar List

This time around we need to update the user’s calendar list. That is the list of calendars you can find on the bottom right sidebar that you can check or uncheck to display.

All headers and the method of this HTTP request are the same as the shareCalendar()function.

For our content this time we need to provide the shared calendar id (Line 16). Any new unaccepted calendar subscription request is automatically set to ‘hidden’ from the list (Line 17). We need to set this hidden then to false and to ensure it is displaying on the user’s list of calendars set selected to true (Line 18). This is the same as checking the box beside the calendar.

The returned JSON in the response variable should look a little like this:

Conclusion

As you can see this is not a clean-cut process and involves several steps to:

  1. Create a Google Apps Script Project.
  2. Create or use an existing Google Cloud project.
  3. Add the OAuth library.
  4. Create a Service Account.
  5. Add the service account JSON to your Apps Script Project.
  6. Apply Domain-Wide Delegation of Authority to your service account project.
  7. And finally, write your script.

It really makes you feel for the developers who regularly develop in other languages outside of Google Apps Script.

If you have found the tutorial helpful, why not shout me a coffee? I'd really appreciate it.

Other Service Account examples

I found it takes a few goes in different scenarios to feel confident in using service accounts. Below I have provided a list of other excellent tutorials and references on the topic that well work a run-through:

If you have found the tutorial helpful, why not shout me a coffee? I'd really appreciate it.

~Yagi

One thought on “How to force subscribe a user in your domain to a Google Calendar with Google Apps Script.”

Leave a Reply

%d bloggers like this: