সার্ভার-সাইড অনুমোদন বাস্তবায়ন

Gmail API-এর অনুরোধগুলিকে OAuth 2.0 শংসাপত্র ব্যবহার করে অনুমোদিত হতে হবে৷ যখন আপনার অ্যাপ্লিকেশন ব্যবহারকারীর পক্ষে Google API অ্যাক্সেস করতে হবে তখন আপনার সার্ভার-সাইড ফ্লো ব্যবহার করা উচিত, উদাহরণস্বরূপ যখন ব্যবহারকারী অফলাইন থাকে। এই পদ্ধতির জন্য আপনার ক্লায়েন্ট থেকে আপনার সার্ভারে একটি এককালীন অনুমোদন কোড পাস করতে হবে; এই কোডটি আপনার সার্ভারের জন্য একটি অ্যাক্সেস টোকেন এবং রিফ্রেশ টোকেন অর্জন করতে ব্যবহৃত হয়।

সার্ভার-সাইড Google OAuth 2.0 বাস্তবায়ন সম্পর্কে আরও জানতে, ওয়েব সার্ভার অ্যাপ্লিকেশনের জন্য OAuth 2.0 ব্যবহার করা দেখুন।

বিষয়বস্তু

একটি ক্লায়েন্ট আইডি এবং ক্লায়েন্ট সিক্রেট তৈরি করুন

Gmail API ব্যবহার শুরু করার জন্য, আপনাকে প্রথমে সেটআপ টুল ব্যবহার করতে হবে, যা আপনাকে Google API কনসোলে একটি প্রকল্প তৈরি করতে, API সক্ষম করার এবং শংসাপত্র তৈরি করার মাধ্যমে নির্দেশিত করে।

  1. শংসাপত্র পৃষ্ঠা থেকে, আপনার OAuth 2.0 শংসাপত্র তৈরি করতে শংসাপত্র তৈরি করুন > OAuth ক্লায়েন্ট আইডি বা একটি পরিষেবা অ্যাকাউন্ট তৈরি করতে শংসাপত্র তৈরি করুন > পরিষেবা অ্যাকাউন্ট কী-তে ক্লিক করুন।
  2. আপনি যদি একটি OAuth ক্লায়েন্ট আইডি তৈরি করেন, তাহলে আপনার আবেদনের ধরন নির্বাচন করুন।
  3. ফর্মটি পূরণ করুন এবং তৈরি করুন ক্লিক করুন।

আপনার অ্যাপ্লিকেশনের ক্লায়েন্ট আইডি এবং পরিষেবা অ্যাকাউন্ট কীগুলি এখন শংসাপত্র পৃষ্ঠায় তালিকাভুক্ত করা হয়েছে৷ বিস্তারিত জানার জন্য, একটি ক্লায়েন্ট আইডি ক্লিক করুন; আইডি প্রকারের উপর নির্ভর করে প্যারামিটারগুলি পরিবর্তিত হয়, তবে ইমেল ঠিকানা, ক্লায়েন্ট সিক্রেট, জাভাস্ক্রিপ্টের উত্স, বা ইউআরআইগুলি পুনঃনির্দেশিত হতে পারে।

ক্লায়েন্ট আইডিটি নোট করুন কারণ আপনাকে পরে এটি আপনার কোডে যোগ করতে হবে।

অনুমোদনের অনুরোধগুলি পরিচালনা করা

যখন একজন ব্যবহারকারী প্রথমবার আপনার অ্যাপ্লিকেশন লোড করে, তখন অনুরোধ করা অনুমতির সুযোগের সাথে তাদের Gmail অ্যাকাউন্ট অ্যাক্সেস করার জন্য আপনার অ্যাপ্লিকেশনের অনুমতি দেওয়ার জন্য তাদের একটি ডায়ালগ উপস্থাপন করা হয়। এই প্রাথমিক অনুমোদনের পরে, আপনার অ্যাপের ক্লায়েন্ট আইডি পরিবর্তিত হলে বা অনুরোধকৃত স্কোপগুলি পরিবর্তিত হলে ব্যবহারকারীকে শুধুমাত্র অনুমতি ডায়ালগ দিয়ে উপস্থাপন করা হয়।

ব্যবহারকারীকে প্রমাণীকরণ করুন

এই প্রাথমিক সাইন-ইনটি একটি অনুমোদন ফলাফল বস্তু প্রদান করে যাতে একটি অনুমোদন কোড থাকে যদি সফল হয়।

একটি অ্যাক্সেস টোকেনের জন্য অনুমোদন কোড বিনিময় করুন

অনুমোদন কোড হল একটি এককালীন কোড যা আপনার সার্ভার একটি অ্যাক্সেস টোকেনের জন্য বিনিময় করতে পারে। এই অ্যাক্সেস টোকেনটি সীমিত সময়ের জন্য ব্যবহারকারীর ডেটাতে আপনার অ্যাপ্লিকেশন অ্যাক্সেস দেওয়ার জন্য Gmail API-এ পাস করা হয়েছে।

যদি আপনার অ্যাপ্লিকেশনটির offline অ্যাক্সেসের প্রয়োজন হয়, আপনার অ্যাপ প্রথমবার অনুমোদন কোড বিনিময় করে, এটি একটি রিফ্রেশ টোকেনও পায় যা এটি একটি পূর্ববর্তী টোকেনের মেয়াদ শেষ হওয়ার পরে একটি নতুন অ্যাক্সেস টোকেন পেতে ব্যবহার করে। আপনার অ্যাপ্লিকেশন পরবর্তী ব্যবহারের জন্য এই রিফ্রেশ টোকেন (সাধারণত আপনার সার্ভারে একটি ডাটাবেসে) সংরক্ষণ করে।

নিম্নলিখিত কোড নমুনাগুলি offline অ্যাক্সেস সহ একটি অ্যাক্সেস টোকেনের জন্য একটি অনুমোদন কোড বিনিময় এবং রিফ্রেশ টোকেন সংরক্ষণ করে।

পাইথন

আপনার client_secrets.json ফাইলের অবস্থানের সাথে CLIENTSECRETS_LOCATION মান প্রতিস্থাপন করুন।

import logging
from oauth2client.client import flow_from_clientsecrets
from oauth2client.client import FlowExchangeError
from apiclient.discovery import build
# ...


# Path to client_secrets.json which should contain a JSON document such as:
#   {
#     "web": {
#       "client_id": "[[YOUR_CLIENT_ID]]",
#       "client_secret": "[[YOUR_CLIENT_SECRET]]",
#       "redirect_uris": [],
#       "auth_uri": "https://accounts.google.com/o/oauth2/auth",
#       "token_uri": "https://accounts.google.com/o/oauth2/token"
#     }
#   }
CLIENTSECRETS_LOCATION = '<PATH/TO/CLIENT_SECRETS.JSON>'
REDIRECT_URI = '<YOUR_REGISTERED_REDIRECT_URI>'
SCOPES = [
    'https://www.googleapis.com/auth/gmail.readonly',
    'https://www.googleapis.com/auth/userinfo.email',
    'https://www.googleapis.com/auth/userinfo.profile',
    # Add other requested scopes.
]

class GetCredentialsException(Exception):
  """Error raised when an error occurred while retrieving credentials.

  Attributes:
    authorization_url: Authorization URL to redirect the user to in order to
                       request offline access.
  """

  def __init__(self, authorization_url):
    """Construct a GetCredentialsException."""
    self.authorization_url = authorization_url


class CodeExchangeException(GetCredentialsException):
  """Error raised when a code exchange has failed."""


class NoRefreshTokenException(GetCredentialsException):
  """Error raised when no refresh token has been found."""


class NoUserIdException(Exception):
  """Error raised when no user ID could be retrieved."""


def get_stored_credentials(user_id):
  """Retrieved stored credentials for the provided user ID.

  Args:
    user_id: User's ID.
  Returns:
    Stored oauth2client.client.OAuth2Credentials if found, None otherwise.
  Raises:
    NotImplemented: This function has not been implemented.
  """
  # TODO: Implement this function to work with your database.
  #       To instantiate an OAuth2Credentials instance from a Json
  #       representation, use the oauth2client.client.Credentials.new_from_json
  #       class method.
  raise NotImplementedError()


def store_credentials(user_id, credentials):
  """Store OAuth 2.0 credentials in the application's database.

  This function stores the provided OAuth 2.0 credentials using the user ID as
  key.

  Args:
    user_id: User's ID.
    credentials: OAuth 2.0 credentials to store.
  Raises:
    NotImplemented: This function has not been implemented.
  """
  # TODO: Implement this function to work with your database.
  #       To retrieve a Json representation of the credentials instance, call the
  #       credentials.to_json() method.
  raise NotImplementedError()


def exchange_code(authorization_code):
  """Exchange an authorization code for OAuth 2.0 credentials.

  Args:
    authorization_code: Authorization code to exchange for OAuth 2.0
                        credentials.
  Returns:
    oauth2client.client.OAuth2Credentials instance.
  Raises:
    CodeExchangeException: an error occurred.
  """
  flow = flow_from_clientsecrets(CLIENTSECRETS_LOCATION, ' '.join(SCOPES))
  flow.redirect_uri = REDIRECT_URI
  try:
    credentials = flow.step2_exchange(authorization_code)
    return credentials
  except FlowExchangeError, error:
    logging.error('An error occurred: %s', error)
    raise CodeExchangeException(None)


def get_user_info(credentials):
  """Send a request to the UserInfo API to retrieve the user's information.

  Args:
    credentials: oauth2client.client.OAuth2Credentials instance to authorize the
                 request.
  Returns:
    User information as a dict.
  """
  user_info_service = build(
      serviceName='oauth2', version='v2',
      http=credentials.authorize(httplib2.Http()))
  user_info = None
  try:
    user_info = user_info_service.userinfo().get().execute()
  except errors.HttpError, e:
    logging.error('An error occurred: %s', e)
  if user_info and user_info.get('id'):
    return user_info
  else:
    raise NoUserIdException()


def get_authorization_url(email_address, state):
  """Retrieve the authorization URL.

  Args:
    email_address: User's e-mail address.
    state: State for the authorization URL.
  Returns:
    Authorization URL to redirect the user to.
  """
  flow = flow_from_clientsecrets(CLIENTSECRETS_LOCATION, ' '.join(SCOPES))
  flow.params['access_type'] = 'offline'
  flow.params['approval_prompt'] = 'force'
  flow.params['user_id'] = email_address
  flow.params['state'] = state
  return flow.step1_get_authorize_url(REDIRECT_URI)


def get_credentials(authorization_code, state):
  """Retrieve credentials using the provided authorization code.

  This function exchanges the authorization code for an access token and queries
  the UserInfo API to retrieve the user's e-mail address.
  If a refresh token has been retrieved along with an access token, it is stored
  in the application database using the user's e-mail address as key.
  If no refresh token has been retrieved, the function checks in the application
  database for one and returns it if found or raises a NoRefreshTokenException
  with the authorization URL to redirect the user to.

  Args:
    authorization_code: Authorization code to use to retrieve an access token.
    state: State to set to the authorization URL in case of error.
  Returns:
    oauth2client.client.OAuth2Credentials instance containing an access and
    refresh token.
  Raises:
    CodeExchangeError: Could not exchange the authorization code.
    NoRefreshTokenException: No refresh token could be retrieved from the
                             available sources.
  """
  email_address = ''
  try:
    credentials = exchange_code(authorization_code)
    user_info = get_user_info(credentials)
    email_address = user_info.get('email')
    user_id = user_info.get('id')
    if credentials.refresh_token is not None:
      store_credentials(user_id, credentials)
      return credentials
    else:
      credentials = get_stored_credentials(user_id)
      if credentials and credentials.refresh_token is not None:
        return credentials
  except CodeExchangeException, error:
    logging.error('An error occurred during code exchange.')
    # Drive apps should try to retrieve the user and credentials for the current
    # session.
    # If none is available, redirect the user to the authorization URL.
    error.authorization_url = get_authorization_url(email_address, state)
    raise error
  except NoUserIdException:
    logging.error('No user ID could be retrieved.')
  # No refresh token has been retrieved.
  authorization_url = get_authorization_url(email_address, state)
  raise NoRefreshTokenException(authorization_url)

সঞ্চিত শংসাপত্র সহ অনুমোদন

যখন ব্যবহারকারীরা একটি সফল প্রথম-বারের অনুমোদন প্রবাহের পরে আপনার অ্যাপটি পরিদর্শন করে, তখন আপনার অ্যাপ্লিকেশন ব্যবহারকারীকে পুনরায় অনুরোধ না করে অনুরোধগুলি অনুমোদন করতে একটি সঞ্চিত রিফ্রেশ টোকেন ব্যবহার করতে পারে।

আপনি যদি ইতিমধ্যেই ব্যবহারকারীকে প্রমাণীকরণ করে থাকেন, আপনার অ্যাপ্লিকেশন তার ডাটাবেস থেকে রিফ্রেশ টোকেনটি পুনরুদ্ধার করতে পারে এবং সার্ভার-সাইড সেশনে টোকেন সংরক্ষণ করতে পারে। যদি রিফ্রেশ টোকেন প্রত্যাহার করা হয় বা অন্যথায় অবৈধ হয়, তাহলে আপনাকে এটি ধরতে হবে এবং যথাযথ ব্যবস্থা নিতে হবে।

OAuth 2.0 শংসাপত্র ব্যবহার করা

পূর্ববর্তী বিভাগে দেখানো হিসাবে OAuth 2.0 শংসাপত্রগুলি পুনরুদ্ধার করা হলে, সেগুলি একটি Gmail পরিষেবা অবজেক্ট অনুমোদন করতে এবং API এ অনুরোধ পাঠাতে ব্যবহার করা যেতে পারে।

একটি পরিষেবা অবজেক্ট ইনস্ট্যান্টিয়েট করুন

এই কোড নমুনা দেখায় কিভাবে একটি পরিষেবা অবজেক্ট ইনস্ট্যান্ট করা যায় এবং তারপর API অনুরোধ করার জন্য এটি অনুমোদন করা যায়।

পাইথন

from apiclient.discovery import build
# ...

def build_service(credentials):
  """Build a Gmail service object.

  Args:
    credentials: OAuth 2.0 credentials.

  Returns:
    Gmail service object.
  """
  http = httplib2.Http()
  http = credentials.authorize(http)
  return build('gmail', 'v1', http=http)

অনুমোদিত অনুরোধ পাঠান এবং প্রত্যাহার করা শংসাপত্রগুলি পরীক্ষা করুন৷

নিম্নলিখিত কোড স্নিপেট বার্তাগুলির একটি তালিকা পুনরুদ্ধার করতে একটি অনুমোদিত Gmail পরিষেবা উদাহরণ ব্যবহার করে৷

যদি একটি ত্রুটি ঘটে, কোডটি একটি HTTP 401 স্ট্যাটাস কোডের জন্য পরীক্ষা করে, যা ব্যবহারকারীকে অনুমোদন URL-এ পুনঃনির্দেশ করে পরিচালনা করা উচিত।

আরও Gmail API অপারেশন API রেফারেন্সে নথিভুক্ত করা হয়েছে।

পাইথন

from apiclient import errors
# ...

def ListMessages(service, user, query=''):
  """Gets a list of messages.

  Args:
    service: Authorized Gmail API service instance.
    user: The email address of the account.
    query: String used to filter messages returned.
           Eg.- 'label:UNREAD' for unread Messages only.

  Returns:
    List of messages that match the criteria of the query. Note that the
    returned list contains Message IDs, you must use get with the
    appropriate id to get the details of a Message.
  """
  try:
    response = service.users().messages().list(userId=user, q=query).execute()
    messages = response['messages']

    while 'nextPageToken' in response:
      page_token = response['nextPageToken']
      response = service.users().messages().list(userId=user, q=query,
                                         pageToken=page_token).execute()
      messages.extend(response['messages'])

    return messages
  except errors.HttpError, error:
    print 'An error occurred: %s' % error
    if error.resp.status == 401:
      # Credentials have been revoked.
      # TODO: Redirect the user to the authorization URL.
      raise NotImplementedError()

পরবর্তী পদক্ষেপ

একবার আপনি Gmail API অনুরোধগুলি অনুমোদন করতে স্বাচ্ছন্দ্য বোধ করলে, আপনি বিকাশকারী গাইড বিভাগে বর্ণিত বার্তা, থ্রেড এবং লেবেলগুলি পরিচালনা শুরু করতে প্রস্তুত৷

আপনি API রেফারেন্সে উপলব্ধ API পদ্ধতি সম্পর্কে আরও জানতে পারেন।