Enhance Your Django Project with Gmail Integration

Gmail stands as one of the world’s most favoured and extensively utilized email services. It offers many features and functionalities that make it easy to communicate and manage your emails.

However, sometimes you may want to integrate Gmail with other applications or platforms, such as Django, a high-level Python web framework that enables rapid development and clean design. It is known for its ability to speed up the Django development process and maintain an attractive design.

By linking Gmail with Django, you can unlock even more possibilities, expanding what you can do with your emails and web applications. This integration allows you to create innovative solutions that improve your email and web experiences.

Prerequisites

Certainly, let’s outline the prerequisites you need before you start integrating Gmail into your Django project:

✅ Django Project: You should have an existing Django project or create a new one to integrate Gmail functionality. Ensure that you have Django installed and configured in your project.

✅ Google Account: You’ll need a Google account to access the Google Cloud Console, where you’ll set up the Gmail API credentials.

✅ Google Cloud Console Project: Create a new project in the Google Cloud Console. This project will be used to enable the Gmail API and generate OAuth 2.0 credentials.

✅ Gmail API Enabled: Inside your Google Cloud Console project, ensure that the Gmail API is enabled. You have the option to activate it within the “APIs & Services” category.

✅ OAuth 2.0 Credentials: Create OAuth 2.0 Client IDs for a web application in your Google Cloud Console project. These credentials are necessary to authenticate your Django application with the Gmail API.

Scope Provided by Google

Google provides a wide range of scopes for its APIs. Scopes are permissions that you request from a user when they authorize your app to access their Google Account data.

The specific scopes that you need will depend on the APIs that you are using. For the Gmail API, you will need to request the gmail.readonly scope to read emails or the gmail.send scope to send emails.

Here is a list of some of the most common scopes provided by Google:

  • Profile: Access basic profile information, such as the user’s name and email address.
  • Email: Access and manage the user’s emails.
  • Calendar: Access and manage the user’s calendar.
  • Drive: Access and manage the user’s files in Google Drive.
  • YouTube: Access and manage the user’s YouTube videos.
  • Maps: Access and manage the user’s Google Maps data.

When requesting scopes, it is important to only request the scopes that you need. This will help to protect user privacy and prevent your app from being abused.

Here are some tips for requesting scopes:

  • Only request the scopes that you need.
  • Use the most narrowly scoped scopes possible.
  • Provide a clear explanation of why you need each scope.
  • Be honest and transparent with users about how you will use their data.

In this blog, we will be using Gmail scopes for the Gmail integration.

['https://www.googleapis.com/auth/gmail.readonly',]

Simplify Your Business with Product Migration & Integration Services

Create OAuth 2.0 Credential

Creating OAuth 2.0 credentials is an essential step when you want to integrate Gmail or any other Google service into your application. These credentials are required for authentication and authorization. Here are the steps to create OAuth 2.0 credentials for your project:

Step 1: Go to Google Cloud Console

Google-cloud-Console
Fig: Google Cloud Console Dashboard

Click on Create or select a project you will see the dialog box below.

Related read: What is Auth0? Features, Benefits And Its Implementation

Step 2: Create a New Project

If you don’t have an existing project, create a new one by clicking the project dropdown at the top of the console and selecting “New Project.” Give your project a meaningful name.

Step 3: Enable the Gmail API

In the left-hand sidebar, click on “APIs & Services” and then “Library.”

Enabling the Gmail API

In the search bar, enter “Gmail API” and choose it.

On the left-hand sidebar, select “APIs & Services,” and then choose “OAuth consent screen.”

Step 4: Set Up the OAuth Consent Screen

In the left-hand sidebar, click on “APIs & Services” and then “OAuth consent screen.”

Choose whether your OAuth consent screen will be for internal or external users and proceed to configure it. Provide a name, email address, and other required information.

Specify the scopes your application will require. For Gmail integration, you may need the gmail.readonly or gmail.send scope, depending on the access your application needs.

Add authorized domains if applicable.

Setting Up OAuth Consent Screen demo

Save and continue to the next step.

Step 5: Create OAuth 2.0 Credentials

In the left-hand sidebar, click on “APIs & Services” and then “Credentials.”

Choose the “Create Credentials” dropdown and then pick “OAuth client ID.”

Choose “Web application” as the application type.

Creating OAuth 2.0 Credentials

Give your OAuth client a name.

Under “Authorized redirect URIs,” specify the callback URL that Google will send the user after authentication. This should be a URL within your Django application to handle the OAuth callback.

Give client a name to OAuth

Click “Create.” and download Credentials.

After creating the OAuth client ID, you’ll be shown the client ID and client secret. Be sure to keep these credentials secret.

You can download the credentials as a JSON file by clicking the download icon next to your newly created OAuth client ID. This JSON file will be used in your Django application to authenticate with the Gmail API.

With these OAuth 2.0 credentials, you can now implement the OAuth 2.0 authentication flow in your Django application to allow it to request access to users’ Gmail accounts. Ensure that you securely store the client ID and client secret in your Django application’s configuration and use them in the OAuth flow to obtain access tokens for Gmail integration.

Retrieve Access and Refresh Token

Once you go through the above steps and successfully create OAuth 2.0 credentials you need to create a Django project.

django-admin startproject project-name

Also, create an app for adding view and create a model for storing access and refreshing tokens.

python manage.py startapp app-name
class GoogleOAuth2LoginAPIView(RetrieveAPIView):
"""
Class for creating an api view for login by gmail.
"""
permission_classes = ()
authentication_classes = ()

def get(self, request, *args, **kwargs):
"""
GET function for request for google login.
"""
client_id = getenv("GOOGLE_CLIENT_ID")
client_secrete = getenv("GOOGLE_CLIENT_SECRET")
redirect_uri = getenv("GOOGLE_REDIRECT_URI")

if 'code' not in request.GET:
auth_uri = ('https://accounts.google.com/o/oauth2/v2/auth?response_type=code'
'&client_id={}&redirect_uri={}&scope={}').format(client_id, redirect_uri, SCOPES)
return redirect(auth_uri)
else:
auth_code = request.GET['code']
data = {'code': auth_code,
'client_id': client_id,
'client_secret': client_secrete,
'redirect_uri': redirect_uri,
'grant_type': 'authorization_code',
}
r = requests.post('https://oauth2.googleapis.com/token', data=data)
request.session['credentials'] = r.text
access_token_response = r.json()

headers = {'Authorization': f'Bearer {access_token_response["access_token"]}'}
personal_info_response = requests.get('https://www.googleapis.com/oauth2/v1/userinfo', headers=headers)
personal_info_response = personal_info_response.json()
print(personal_info_response)

GoogleRequestModel.objects.update_or_create(
access_token=access_token_response["access_token"],
email=personal_info_response["email"],
profile_picture=personal_info_response["picture"]
)

return Response({"message": "Successfully"})

urls.py:

from django.urls import path

from .views import (
GoogleOAuth2LoginAPIView,
)

urlpatterns = [
path("googleLogin/", GoogleOAuth2LoginAPIView.as_view(), name="google-login"),
]
https://98a4-2409-40c2-1034-8a3b-f4b3-fef0-63bc-74ed.ngrok-free.app/integrate/googleLogin/"

OAuth 2.0 Flow Initialization:

Retrieve the client ID, client secret, and redirect the URL from environment variables by using the getenv function.

It checks if the ‘code’ parameter is present in the query string of the request. If not, it constructs the authentication URL and redirects the user to Google for authentication.

If the ‘code’ parameter is present, it indicates that the user has completed the Google authentication process and is being redirected back to your application with an authorization code.

Token Exchange:

When the user returns with an authorization code, the code constructs a POST request to exchange the authorization code for an access token and potentially a refresh token. The access token and other relevant information are stored in the session for future use.

Accessing User Information:

Constructs a request to the Google OAuth 2.0 user info endpoint to retrieve user information. It uses the obtained access token in the request headers. The user information, including the email address and profile picture, is extracted from the response.

Storing User Information:

Updates or creates a GoogleRequestModel object to store the user’s access token, email, and profile picture. This allows you to associate the user’s Google information with your application.

Revoke Token

To revoke an access token, you need to make a POST request to the Google OAuth 2.0 token revocation endpoint. This endpoint allows you to invalidate an access token, effectively revoking the user’s authorization to access resources on their behalf.

class RevokeGoogleAccessTokenAPIView(RetrieveAPIView):
"""
Class for creating a revoke google access token api.
"""
permission_classes = ()
authentication_classes = ()

def get(self, request, *args, **kwargs):
"""
GET function revokes the google access token.
"""
email = request.GET.get("email", None)
if email:
google_info = GoogleRequestModel.objects.filter(email=email).last()
if google_info:
revoke_url = 'https://accounts.google.com/o/oauth2/revoke'

# Construct the token revocation request
revoke_params = {
'token': google_info.access_token
}

response = requests.post(revoke_url, params=revoke_params)
print(response.json())

if response.status_code == 200:
print("Access token revoked successfully.")
return Response({"message": "Access token revoked successfully."})
else:
print("Failed to revoke the access token.")
return Response({"message": "Failed to revoke the access token."})

else:
return Response({"message": "email address is required!"})

Token Revocation:

If an email address is provided, the code attempts to fetch the latest GoogleRequestModel associated with that email address. The GoogleRequestModel likely contains the user’s access token. It constructs the URL for token revocation by appending the access token to the revocation endpoint URL.

Make a POST Request:

Send a POST request to the revocation URL with the access token as a parameter. This request instructs Google to revoke the user’s authorization for your application.
The response is logged and checked for a successful status code (usually 200).

Response:

If the revocation is successful (status code 200), it logs a success message and returns a response indicating that the access token has been revoked.

If the revocation fails (status code other than 200), it logs an error message and returns a response indicating that the revocation has failed.

coma

Conclusion

In conclusion, obtaining and revoking access tokens for Google Gmail accounts via OAuth 2.0 is a crucial aspect of user authentication and security in modern web applications. Here are two points I wanted to highlight.

Getting the Access Token: Access tokens are vital for accessing Google APIs on behalf of a user.

Revoking the Access Token: Token revocation is necessary for actions like user logouts, revoking access, or enhancing security.

Overall, the process of obtaining and revoking access tokens ensures that user data is accessed securely, with user consent and authorization at the forefront. Proper handling of access tokens is crucial for maintaining user privacy and protecting their data in your application. Be sure to handle access tokens securely, validate user consent, and manage token expiration and revocation effectively to ensure a safe and user-friendly experience.

Here is my GitHub repository where you can refer to the code.

Keep Reading

Keep Reading

Leave your competitors behind! Become an EPIC integration pro, and boost your team's efficiency.

Register Here
  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?