Fetching Google Calendar Events Using Service Account

There are two possible ways through which we can access Google APIs in our application:

  1. Using OAuth 2 Consent
  2. Using Service Account

In the first method, we can call Google APIs on behalf of end users, and in this, user consent is required. On the other hand, in the second method, we can call Google APIs on behalf of the service account and no user consent is required.

Now, suppose our use case is to access Google Calendar events of any employee of our organization from the backend without requiring any user interaction, then we need to go with the service account method. A service account is basically an account that belongs to our application instead of any end user and our app will be called a calendar API without the need of the user.

Flow of Approach:

Step1: Create a google cloud project on the GCP console:

a) Go to the GCP console, and click on the project dropdown. Click on NEW PROJECT on the top right of the opened window. Give the name of the project and then click on Create.

b) Now select the APIs & Services option under Quick Access on the google console dashboard of the newly created project. Also, copy the project number and save it for future use.

c) Now Click on the ENABLE APIS AND SERVICES option and type Calendar in the search box and select Google Calendar API. Then click on enable button to add calendar API to created project.

Step 2: Create a service account and save its credentials:

a) Click on the manage button and then on CREATE CREDENTIALS to create a service account. Select Application data under Which API are you using? question and no in the next question as shown in the image below and click next.

c) Now fill in the service account name and select the owner role for giving access to this service account to the project. We can skip the Grant user’s access to this service account step as it is optional and click done.

d) Now our service account has been set up. To create credentials click on the email of the service account -> KEYS tab -> ADD KEY->select JSON->create. Credentials will be created and downloaded as JSON files.

Step 3: Set up domain-wide delegation:

To access the calendar events of any employee of our organization we have to do domain wide delegation. Through domain-wide delegation, we authorize the service accounts to access users’ data without requiring each user to give consent. It allows apps to access users’ data across the organization’s Google Workspace environment. The steps for this are given below:

  1. Go to the Admin console of the organization.
  2. Then Go to Menu -> Security -> Access and data control -> API controls.
  3. Then click Manage Domain Wide Delegation.
  4. Click Add New and enter the service account client ID which will be present in the JSON file that we have downloaded when we created the service account.
  5. In OAuth Scopes enter https://www.googleapis.com/auth/calendar.readonly as scope because we have to retrieve only google calendar events in our case.
  6. In the last click Authorize.

Set up NodeJs App:

Now we will set up our node application to call google calendar API for retrieving events of users.

Run the following commands in the terminal:

  • NPM INIT -Y
  • NPM I GOOGLEAPIS (FOR GOOGLE APIS)

Create an index.js file. This will be the main file where we call google calendar API to fetch particular user’s events.

Step 5: Create a JWT client and call calendar API:

Paste the below code in the index.js file. In the code below we are accessing Google calendar events of user1@xyz.com of xyz organization using the above-created service account.

const { google } = require(“googleapis”); const serviceAccount = require(“./service-account-credentials.json”); (async () => { const SCOPES = “https://www.googleapis.com/auth/calendar.readonly”; const GOOGLE_PRIVATE_KEY = serviceAccount.private_key; const GOOGLE_CLIENT_EMAIL = serviceAccount.client_email; const GOOGLE_PROJECT_NUMBER = YOUR_PROJECT_NUMBER; const GOOGLE_CALENDAR_ID = “user1@xyz.com”; const SUBJECT_EMAIL = “user2@xyz.com”; const getListOfEvents = async (maxResults = 10) => { //Declaring JWT token client const jwtClient = new google.auth.JWT( GOOGLE_CLIENT_EMAIL, null, GOOGLE_PRIVATE_KEY, SCOPES, SUBJECT_EMAIL ); //Using JWT client to request to Google servers which will then return an access token. const calendar = google.calendar({ version: “v3”, project: GOOGLE_PROJECT_NUMBER, auth: jwtClient, }); //Using access token to call Google Calendar events API const eventList = await calendar.events.list({ calendarId: GOOGLE_CALENDAR_ID, timeMin: new Date().toISOString(), maxResults, singleEvents: true, orderBy: “startTime”, }); console.log( `GoogleCalendarService: getListOfEvents : ${GOOGLE_CALENDAR_ID}`, eventList.data.items ); return eventList.data; }; await getListOfEvents(); })();

Code flow:

  1. Firstly we have to declare all required credentials from the JSON file of the service account that we have stored earlier.
  2. Define the scope to fetch Google calendar events as https://www.googleapis.com/auth/calendar.readonly.
  3. Assign previously saved project number (i.e. Project number of the project in which we have created this service account) in GOOGLE_PROJECT_NUMBER variable.
  4. Assign the email id of the user in GOOGLE_CLIENT_EMAIL whose google calendar events we want to access.
  5. SUBJECT_EMAIL will be an email of a user on behalf of whom we will be using the Google calendar so it can be any user of our organization because we have done domain-wide delegation for our company.
  6. Then we have to use the client’s email and private key to create a signed JWT.
  7. This JWT client will be then used to send the request to the Google OAuth 2.0 Authorization Server, which returns an access token.
  8. The application then uses the access token to access a Google API.

That’s it now we can run the above code by using the command node index.js and can fetch Google calendar events of any user of our organization.

Latest

SENTRY integration in your React Native App for Error/Crash tracking

Sentry captures data by using an SDK within your...

Recall the concepts of useCallback.

useCallback hook is one of the best hooks offered...

Value of Comments in the code!!

During my journey of Software Development, I am always...

YOLO:Bullet Paced Algorithm

http://sh017.hostgator.tempwebhost.net/media/33949d0e61af4b50f374c534713f56b3 According to world health organization, more than 1.35 million...

Featured

Developing Enterprise Application in Node.js – CJS Vs ESM

Node.js is a popular runtime environment for building server-side...

Integrating your web react applications with their React Native(android and IOS) apps using QR code

Integrating a web application with Android and iOS apps...

YOLO: Bullet Paced Algorithm – popular choice for object detection in autonomous vehicles 

According to world health organization, more than 1.35 million...

Importance of Test Scalar Tool

TestScalar is quick to access, convenient to execute, easy to track. Our popular web-based test planning software lets you focus on what matters: meeting...

From Requirements to Reporting: How to Use a Test Case Management Tool to Ace Your Software Testing

The Software Testing Life Cycle (STLC) is a process that describes the stages of testing software. It includes planning, design, execution, and reporting of...

YOLO:Bullet Paced Algorithm

http://sh017.hostgator.tempwebhost.net/media/33949d0e61af4b50f374c534713f56b3 According to world health organization, more than 1.35 million people die every year because of vehicle accidents . Vehicle safety features started with passive safety...

LEAVE A REPLY

Please enter your comment!
Please enter your name here