बार-बार लॉगिन मैनेज करना

Classroom ऐड-ऑन के लिए सिलसिलेवार तरीके से निर्देश देने वाली यह सीरीज़ तीसरी है.

सिलसिलेवार तरीके से दिए गए इस निर्देश में, यह मैनेज किया जा सकता है कि हमारे ऐड-ऑन पर लोग बार-बार जाएं. इसके लिए, आपको उपयोगकर्ता को दिए गए क्रेडेंशियल अपने-आप मिल जाएंगे. इसके बाद, उपयोगकर्ताओं को ऐसे पेजों पर भेजा जाता है जिनसे वे तुरंत एपीआई अनुरोध कर सकते हैं. ऐसा करना Classroom ऐड-ऑन के लिए ज़रूरी है.

सिलसिलेवार तरीके से निर्देशों का पालन करते हुए, आपने ये काम किए हैं:

  • हमारे उपयोगकर्ता क्रेडेंशियल के लिए स्थायी स्टोरेज लागू करें.
  • login_hint ऐड-ऑन क्वेरी पैरामीटर को वापस पाएं और उसका आकलन करें. यह साइन-इन करने वाले उपयोगकर्ता का यूनीक Google आईडी नंबर है.

काम पूरा हो जाने पर, अपने वेब ऐप्लिकेशन में उपयोगकर्ताओं को पूरी तरह से अनुमति दी जा सकती है और Google API को कॉल किए जा सकते हैं.

iframe क्वेरी पैरामीटर को समझना

Classroom खोलने पर, वह आपके ऐड-ऑन के अटैचमेंट सेटअप यूआरआई को लोड कर देता है. Classroom, यूआरआई में कई GET क्वेरी पैरामीटर जोड़ता है. इनमें, संदर्भ के हिसाब से काम की जानकारी होती है. उदाहरण के लिए, अगर आपका अटैचमेंट डिस्कवरी यूआरआई https://example.com/addon है, तो Classroom https://example.com/addon?courseId=XXX&itemId=YYY&itemType=courseWork&addOnToken=ZZZ पर सेट सोर्स यूआरएल वाला iframe बनाता है. यहां XXX, YYY, और ZZZ, स्ट्रिंग आईडी हैं. इस स्थिति के बारे में ज़्यादा जानकारी के लिए, iframe गाइड देखें.

डिस्कवरी यूआरएल के लिए पांच क्वेरी पैरामीटर हो सकते हैं:

  • courseId: Classroom के मौजूदा कोर्स का आईडी.
  • itemId: स्ट्रीम आइटम का आईडी, जिसमें उपयोगकर्ता बदलाव कर रहा है या बना रहा है.
  • itemType: स्ट्रीम आइटम का वह टाइप जिसे उपयोगकर्ता बना रहा है या उसमें बदलाव कर रहा है. यह courseWork, courseWorkMaterial या announcement में से कोई एक होता है.
  • addOnToken: ऐसा टोकन जिसका इस्तेमाल, Classroom ऐड-ऑन की कुछ कार्रवाइयों को अनुमति देने के लिए किया जाता है.
  • login_hint: मौजूदा उपयोगकर्ता का Google आईडी.

सिलसिलेवार तरीके से दिए गए इस निर्देश से, login_hint के बारे में जानकारी मिलती है. यह क्वेरी पैरामीटर दिया गया है या नहीं, इसके आधार पर उपयोगकर्ताओं को रूट किया जाता है. इसके मौजूद न होने पर, अनुमति वाले फ़्लो पर या अगर मौजूद हो, तो ऐड-ऑन डिस्कवरी पेज पर भेजा जाता है.

क्वेरी पैरामीटर ऐक्सेस करना

क्वेरी पैरामीटर, आपके वेब ऐप्लिकेशन को यूआरआई स्ट्रिंग में पास किए जाते हैं. इन वैल्यू को आपके सेशन में सेव किया जाता है. इनका इस्तेमाल, अनुमति देने के फ़्लो में किया जाता है. साथ ही, इनका इस्तेमाल उपयोगकर्ता की जानकारी को सेव और फिर से हासिल करने के लिए भी किया जाता है. ये क्वेरी पैरामीटर सिर्फ़ तब पास होते हैं, जब ऐड-ऑन को पहली बार खोला जाता है.

Python

अपने फ़्लास्क रास्तों की परिभाषाओं पर जाएं (अगर आप हमारे दिए गए उदाहरण का इस्तेमाल कर रहे हैं, तो routes.py). आपके ऐड-ऑन लैंडिंग रूट में सबसे ऊपर (हमारे दिए गए उदाहरण में /classroom-addon), login_hint क्वेरी पैरामीटर को फिर से पाएं और सेव करें:

# If the login_hint query parameter is available, we'll store it in the session.
if flask.request.args.get("login_hint"):
    flask.session["login_hint"] = flask.request.args.get("login_hint")

यह पक्का करें कि login_hint (अगर मौजूद है) को सेशन में सेव किया गया है. इन वैल्यू को सेव करने के लिए, यह सही जगह है. ये कुछ समय के लिए होती हैं और ऐड-ऑन खोलने पर आपको नई वैल्यू मिलती हैं.

# It's possible that we might return to this route later, in which case the
# parameters will not be passed in. Instead, use the values cached in the
# session.
login_hint = flask.session.get("login_hint")

# If there's still no login_hint query parameter, this must be their first
# time signing in, so send the user to the sign in page.
if login_hint is None:
    return start_auth_flow()

Java

अपनी कंट्रोलर क्लास में ऐड-ऑन लैंडिंग रूट पर नेविगेट करें (दिए गए उदाहरण में AuthController.java में /addon-discovery). इस रूट की शुरुआत में, login_hint क्वेरी पैरामीटर को फिर से पाएं और सेव करें.

/** Retrieve the login_hint or hd query parameters from the request URL. */
String login_hint = request.getParameter("login_hint");
String hd = request.getParameter("hd");

यह पक्का करें कि login_hint (अगर मौजूद है) को सेशन में सेव किया गया है. इन वैल्यू को सेव करने के लिए, यह सही जगह है. ये कुछ समय के लिए होती हैं और ऐड-ऑन खोलने पर आपको नई वैल्यू मिलती हैं.

/** If neither query parameter is sent, use the values in the session. */
if (login_hint == null && hd == null) {
    login_hint = (String) session.getAttribute("login_hint");
    hd = (String) session.getAttribute("hd");
}

/** If the hd query parameter is provided, add hd to the session and route
*   the user to the authorization page. */
else if (hd != null) {
    session.setAttribute("hd", hd);
    return startAuthFlow(model);
}

/** If the login_hint query parameter is provided, add it to the session. */
else if (login_hint != null) {
    session.setAttribute("login_hint", login_hint);
}

अनुमति देने के फ़्लो में क्वेरी पैरामीटर जोड़ना

login_hint पैरामीटर को Google के ऑथेंटिकेशन सर्वर पर भी पास किया जाना चाहिए. इससे पुष्टि करने की प्रक्रिया आसान हो जाती है; अगर आपके ऐप्लिकेशन को पता है कि कौनसा उपयोगकर्ता प्रमाणित करने की कोशिश कर रहा है, तो सर्वर साइन-इन फ़ॉर्म में ईमेल फ़ील्ड को पहले से भरकर, लॉगिन फ़्लो को आसान बनाने के लिए संकेत का इस्तेमाल करता है.

Python

अपनी फ़्लास्क सर्वर फ़ाइल में ऑथराइज़ेशन रूट पर जाएं (/authorize हमारे दिए गए उदाहरण में). flow.authorization_url को किए गए कॉल में login_hint आर्ग्युमेंट जोड़ें.

authorization_url, state = flow.authorization_url(
    # Enable offline access so that you can refresh an access token without
    # re-prompting the user for permission. Recommended for web server apps.
    access_type="offline",
    # Enable incremental authorization. Recommended as a best practice.
    include_granted_scopes="true",
    # The user will automatically be selected if we have the login_hint.
    login_hint=flask.session.get("login_hint"),

Java

AuthService.java क्लास में, authorize() तरीके पर जाएं. मेथड में login_hint और hd को पैरामीटर के तौर पर जोड़ें. साथ ही, ऑथराइज़ेशन यूआरएल बिल्डर में login_hint और hd आर्ग्युमेंट जोड़ें.

String authUrl = flow
    .newAuthorizationUrl()
    .setState(state)
    .set("login_hint", login_hint)
    .set("hd", hd)
    .setRedirectUri(REDIRECT_URI)
    .build();

उपयोगकर्ता के क्रेडेंशियल के लिए, परसिस्टेंट स्टोरेज जोड़ना

अगर ऐड-ऑन लोड होने पर, आपको क्वेरी पैरामीटर के तौर पर login_hint मिलता है, तो इसका मतलब है कि उपयोगकर्ता ने हमारे ऐप्लिकेशन के लिए, अनुमति वाला फ़्लो पहले ही पूरा कर लिया है. उन्हें फिर से साइन इन करने के लिए मजबूर करने के बजाय, आपको उनके पिछले क्रेडेंशियल वापस पाने चाहिए.

याद रखें कि अनुमति देने का फ़्लो पूरा होने के बाद, आपको रीफ़्रेश टोकन मिला था. इस टोकन को सेव करें. ऐक्सेस टोकन पाने के लिए इसका फिर से इस्तेमाल किया जा सकता है. यह टोकन कम समय के लिए दिखता है और Google API का इस्तेमाल करने के लिए ज़रूरी होता है. आपने पहले इन क्रेडेंशियल को सेशन में सेव कर लिया था, लेकिन वेबसाइट पर बार-बार आने वाले लोगों को मैनेज करने के लिए आपको क्रेडेंशियल स्टोर करने होंगे.

उपयोगकर्ता स्कीमा तय करना और डेटाबेस सेट अप करना

User के लिए डेटाबेस स्कीमा सेट अप करें.

Python

उपयोगकर्ता स्कीमा तय करना

User में ये एट्रिब्यूट शामिल होते हैं:

  • id: उपयोगकर्ता का Google आईडी. यह login_hint क्वेरी पैरामीटर में दी गई वैल्यू से मेल खानी चाहिए.
  • display_name: उपयोगकर्ता का नाम और सरनेम, जैसे कि "ऐलेक्स स्मिथ".
  • email: उपयोगकर्ता का ईमेल पता.
  • portrait_url: उपयोगकर्ता की प्रोफ़ाइल फ़ोटो का यूआरएल.
  • refresh_token: पहले से हासिल किया गया रीफ़्रेश टोकन.

इस उदाहरण में, SQLite का इस्तेमाल करके स्टोरेज लागू किया गया है, जो Python के साथ नेटिव तौर पर काम करता है. यह हमारे डेटाबेस को आसानी से मैनेज करने के लिए, flask_sqlalchemy मॉड्यूल का इस्तेमाल करता है.

डेटाबेस को सेट अप करना

पहले, हमारे डेटाबेस के लिए फ़ाइल की जगह के बारे में बताएं. अपने सर्वर की कॉन्फ़िगरेशन फ़ाइल (हमारे दिए गए उदाहरण में config.py) पर जाएं और यह फ़ाइल जोड़ें.

import os

# Point to a database file in the project root.
DATABASE_FILE_NAME = os.path.join(
    os.path.abspath(os.path.dirname(__file__)), 'data.sqlite')

class Config(object):
    SQLALCHEMY_DATABASE_URI = f"sqlite:///{DATABASE_FILE_NAME}"
    SQLALCHEMY_TRACK_MODIFICATIONS = False

यह 'फ़्लैस्क' को उसी डायरेक्ट्री में data.sqlite फ़ाइल पर ले जाता है जिसमें आपकी main.py फ़ाइल है.

इसके बाद, अपने मॉड्यूल डायरेक्ट्री पर जाएं और एक नई models.py फ़ाइल बनाएं. अगर आपने हमारे दिए गए उदाहरण को फ़ॉलो किया है, तो यह webapp/models.py है. User टेबल तय करने के लिए, नई फ़ाइल में इन्हें जोड़ें. अगर अलग हो, तो अपने मॉड्यूल का नाम webapp से बदलें.

from webapp import db

# Database model to represent a user.
class User(db.Model):
    # The user's identifying information:
    id = db.Column(db.String(120), primary_key=True)
    display_name = db.Column(db.String(80))
    email = db.Column(db.String(120), unique=True)
    portrait_url = db.Column(db.Text())

    # The user's refresh token, which will be used to obtain an access token.
    # Note that refresh tokens will become invalid if:
    # - The refresh token has not been used for six months.
    # - The user revokes your app's access permissions.
    # - The user changes passwords.
    # - The user belongs to a Google Cloud organization
    #   that has session control policies in effect.
    refresh_token = db.Column(db.Text())

आखिर में, अपने मॉड्यूल की __init__.py फ़ाइल में, नए मॉडल इंपोर्ट करने और डेटाबेस बनाने के लिए, यह जानकारी जोड़ें.

from webapp import models
from os import path
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy(app)

# Initialize the database file if not created.
if not path.exists(config.DATABASE_FILE_NAME):
    db.create_all()

Java

उपयोगकर्ता स्कीमा तय करना

User में ये एट्रिब्यूट शामिल होते हैं:

  • id: उपयोगकर्ता का Google आईडी. यह login_hint क्वेरी पैरामीटर में दी गई वैल्यू से मेल खाना चाहिए.
  • email: उपयोगकर्ता का ईमेल पता.

मॉड्यूल की resources डायरेक्ट्री में schema.sql फ़ाइल बनाएं. Spring इस फ़ाइल को पढ़ता है और उसके हिसाब से डेटाबेस के लिए एक स्कीमा जनरेट करता है. User एट्रिब्यूट, id, और email को दिखाने के लिए, टेबल में टेबल का नाम, users, और कॉलम चुनें.

CREATE TABLE IF NOT EXISTS users (
    id VARCHAR(255) PRIMARY KEY, -- user's unique Google ID
    email VARCHAR(255), -- user's email address
);

डेटाबेस के लिए User मॉडल तय करने के लिए, Java क्लास बनाएं. दिए गए उदाहरण में यह User.java है.

@Entity एनोटेशन जोड़कर बताएं कि यह एक पीओजेओ है जिसे डेटाबेस में सेव किया जा सकता है. @Table एनोटेशन को उस टेबल के नाम के साथ जोड़ें जिसे आपने schema.sql में कॉन्फ़िगर किया था.

ध्यान दें कि कोड के उदाहरण में, दो एट्रिब्यूट के लिए कंस्ट्रक्टर और सेटर शामिल हैं. डेटाबेस में किसी उपयोगकर्ता को बनाने या अपडेट करने के लिए, AuthController.java में कंस्ट्रक्टर और सेटर का इस्तेमाल किया जाता है. आपके हिसाब से गैटर और toString तरीके भी शामिल किए जा सकते हैं. हालांकि, सिलसिलेवार तरीके से दिए गए इस खास तरीके के लिए, इन तरीकों का इस्तेमाल नहीं किया जाता. इन्हें छोटा रखने के लिए, इस पेज पर दिए गए कोड के उदाहरण से इन्हें हटा दिया जाता है.

/** An entity class that provides a model to store user information. */
@Entity
@Table(name = "users")
public class User {
    /** The user's unique Google ID. The @Id annotation specifies that this
     *   is the primary key. */
    @Id
    @Column
    private String id;

    /** The user's email address. */
    @Column
    private String email;

    /** Required User class no args constructor. */
    public User() {
    }

    /** The User class constructor that creates a User object with the
    *   specified parameters.
    *   @param id the user's unique Google ID
    *   @param email the user's email address
    */
    public User(String id, String email) {
        this.id = id;
        this.email = email;
    }

    public void setId(String id) { this.id = id; }

    public void setEmail(String email) { this.email = email; }
}

डेटाबेस में CRUD की कार्रवाइयां मैनेज करने के लिए, UserRepository.java नाम का इंटरफ़ेस बनाएं. यह इंटरफ़ेस, CrudRepository के इंटरफ़ेस के बारे में ज़्यादा जानकारी देता है.

/** Provides CRUD operations for the User class by extending the
 *   CrudRepository interface. */
@Repository
public interface UserRepository extends CrudRepository<User, String> {
}

कंट्रोलर क्लास, क्लाइंट और डेटा स्टोर करने की जगह के बीच कम्यूनिकेशन की सुविधा देती है. इसलिए, UserRepository क्लास इंजेक्ट करने के लिए, कंट्रोलर क्लास कंस्ट्रक्टर को अपडेट करें.

/** Declare UserRepository to be used in the Controller class constructor. */
private final UserRepository userRepository;

/**
*   ...
*   @param userRepository the class that interacts with User objects stored in
*   persistent storage.
*/
public AuthController(AuthService authService, UserRepository userRepository) {
    this.authService = authService;
    this.userRepository = userRepository;
}

डेटाबेस को सेट अप करना

उपयोगकर्ता से जुड़ी जानकारी सेव करने के लिए, ऐसे H2 डेटाबेस का इस्तेमाल करें जो स्प्रिंग बूट के साथ काम करता हो. इस डेटाबेस का इस्तेमाल सिलसिलेवार निर्देशों में भी Classroom से जुड़ी अन्य जानकारी को सेव करने के लिए किया जाता है. H2 डेटाबेस को सेट अप करने के लिए, application.properties में यह कॉन्फ़िगरेशन जोड़ना ज़रूरी है.

# Enable configuration for persistent storage using an H2 database
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:file:./h2/userdb
spring.datasource.username=<USERNAME>
spring.datasource.password=<PASSWORD>
spring.jpa.hibernate.ddl-auto=update
spring.jpa.open-in-view=false

spring.datasource.url कॉन्फ़िगरेशन, h2 नाम की एक डायरेक्ट्री बनाता है. इसमें userdb फ़ाइल सेव होती है. .gitignore में, H2 डेटाबेस का पाथ जोड़ें. ऐप्लिकेशन को चलाने से पहले, आपको अपनी पसंद के उपयोगकर्ता नाम और पासवर्ड के साथ डेटाबेस सेट करने के लिए, spring.datasource.username और spring.datasource.password अपडेट करने होंगे. ऐप्लिकेशन चलाने के बाद, डेटाबेस का उपयोगकर्ता नाम और पासवर्ड अपडेट करने के लिए, जनरेट की गई h2 डायरेक्ट्री मिटाएं, कॉन्फ़िगरेशन अपडेट करें, और ऐप्लिकेशन को फिर से चलाएं.

spring.jpa.hibernate.ddl-auto कॉन्फ़िगरेशन को update पर सेट करने से, यह पक्का होता है कि ऐप्लिकेशन के रीस्टार्ट होने पर, डेटाबेस में सेव किया गया डेटा सुरक्षित रहेगा. ऐप्लिकेशन के रीस्टार्ट होने पर, हर बार डेटाबेस को मिटाने के लिए, इस कॉन्फ़िगरेशन को create पर सेट करें.

spring.jpa.open-in-view कॉन्फ़िगरेशन को false पर सेट करें. यह कॉन्फ़िगरेशन डिफ़ॉल्ट रूप से चालू होता है. इससे, परफ़ॉर्मेंस से जुड़ी ऐसी समस्याएं हो सकती हैं जिनसे प्रोडक्शन में समस्या का पता लगाना मुश्किल हो.

जैसा कि पहले बताया गया है, बार-बार आने वाले उपयोगकर्ता के क्रेडेंशियल पाने के लिए ज़रूरी है. यह सुविधा, GoogleAuthorizationCodeFlow में पहले से मौजूद क्रेडेंशियल स्टोर से मिलने वाली सहायता की मदद से मिलती है.

AuthService.java क्लास में, उस फ़ाइल का पाथ तय करें जहां क्रेडेंशियल क्लास सेव की गई है. इस उदाहरण में, फ़ाइल को /credentialStore डायरेक्ट्री में बनाया गया है. .gitignore में, क्रेडेंशियल स्टोर का पाथ जोड़ें. जब उपयोगकर्ता, ऑथराइज़ेशन फ़्लो शुरू करता है, तब यह डायरेक्ट्री जनरेट होती है.

private static final File dataDirectory = new File("credentialStore");

इसके बाद, AuthService.java फ़ाइल में एक ऐसा तरीका बनाएं जो FileDataStoreFactory ऑब्जेक्ट बनाता और दिखाता है. यह वह डेटास्टोर है जिसमें क्रेडेंशियल सेव होते हैं.

/** Creates and returns FileDataStoreFactory object to store credentials.
 *   @return FileDataStoreFactory dataStore used to save and obtain users ids
 *   mapped to Credentials.
 *   @throws IOException if creating the dataStore is unsuccessful.
 */
public FileDataStoreFactory getCredentialDataStore() throws IOException {
    FileDataStoreFactory dataStore = new FileDataStoreFactory(dataDirectory);
    return dataStore;
}

GoogleAuthorizationCodeFlow Builder() तरीके में setDataStoreFactory को शामिल करने के लिए, AuthService.java में getFlow() तरीके को अपडेट करें और डेटास्टोर सेट करने के लिए, getCredentialDataStore() को कॉल करें.

GoogleAuthorizationCodeFlow authorizationCodeFlow =
    new GoogleAuthorizationCodeFlow.Builder(
        HTTP_TRANSPORT,
        JSON_FACTORY,
        getClientSecrets(),
        getScopes())
    .setAccessType("offline")
    .setDataStoreFactory(getCredentialDataStore())
    .build();

इसके बाद, getAndSaveCredentials(String authorizationCode) तरीके को अपडेट करें. पहले, इस तरीके से क्रेडेंशियल को कहीं भी सेव किए बिना लिया जाता था. डेटास्टोर में यूज़र आईडी से इंडेक्स किए गए क्रेडेंशियल सेव करने का तरीका अपडेट करें.

यूज़र आईडी, id_token का इस्तेमाल करके TokenResponse ऑब्जेक्ट से मिल सकता है. हालांकि, पहले इसकी पुष्टि ज़रूरी है. ऐसा न करने पर, क्लाइंट ऐप्लिकेशन, सर्वर पर बदले गए उपयोगकर्ता आईडी भेजकर उपयोगकर्ताओं की पहचान चुरा सकते हैं. हमारा सुझाव है कि आप id_token की पुष्टि करने के लिए, Google API क्लाइंट लाइब्रेरी का इस्तेमाल करें. ज़्यादा जानकारी के लिए, [Google आईडी टोकन की पुष्टि करने से जुड़ा Google का आइडेंटिटी पेज] देखें.

// Obtaining the id_token will help determine which user signed in to the application.
String idTokenString = tokenResponse.get("id_token").toString();

// Validate the id_token using the GoogleIdTokenVerifier object.
GoogleIdTokenVerifier googleIdTokenVerifier = new GoogleIdTokenVerifier.Builder(
        HTTP_TRANSPORT,
        JSON_FACTORY)
    .setAudience(Collections.singletonList(
        googleClientSecrets.getWeb().getClientId()))
    .build();

GoogleIdToken idToken = googleIdTokenVerifier.verify(idTokenString);

if (idToken == null) {
    throw new Exception("Invalid ID token.");
}

id_token की पुष्टि होने के बाद, मिले क्रेडेंशियल के साथ सेव करने के लिए userId पाएं.

// Obtain the user id from the id_token.
Payload payload = idToken.getPayload();
String userId = payload.getSubject();

userId को शामिल करने के लिए, कॉल को flow.createAndStoreCredential पर अपडेट करें.

// Save the user id and credentials to the configured FileDataStoreFactory.
Credential credential = flow.createAndStoreCredential(tokenResponse, userId);

AuthService.java क्लास में कोई ऐसा तरीका जोड़ें जो किसी उपयोगकर्ता के क्रेडेंशियल तब दिखाए, जब वह डेटास्टोर में मौजूद हो.

/** Find credentials in the datastore based on a specific user id.
*   @param userId key to find in the file datastore.
*   @return Credential object to be returned if a matching key is found in the datastore. Null if
*   the key doesn't exist.
*   @throws Exception if building flow object or checking for userId key is unsuccessful. */
public Credential loadFromCredentialDataStore(String userId) throws Exception {
    try {
        GoogleAuthorizationCodeFlow flow = getFlow();
        Credential credential = flow.loadCredential(userId);
        return credential;
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
}

क्रेडेंशियल वापस पाएं

Users को फ़ेच करने का तरीका तय करें. आपको login_hint क्वेरी पैरामीटर में, id दिया गया है. इसका इस्तेमाल किसी उपयोगकर्ता के रिकॉर्ड को पाने के लिए किया जा सकता है.

Python

def get_credentials_from_storage(id):
    """
    Retrieves credentials from the storage and returns them as a dictionary.
    """
    return User.query.get(id)

Java

AuthController.java क्लास में, यूज़र आईडी के आधार पर डेटाबेस से उपयोगकर्ता को वापस पाने का तरीका तय करें.

/** Retrieves stored credentials based on the user id.
*   @param id the id of the current user
*   @return User the database entry corresponding to the current user or null
*   if the user doesn't exist in the database.
*/
public User getUser(String id) {
    if (id != null) {
        Optional<User> user = userRepository.findById(id);
        if (user.isPresent()) {
            return user.get();
        }
    }
    return null;
}

स्टोर क्रेडेंशियल

क्रेडेंशियल सेव करते समय दो स्थितियां आती हैं. अगर उपयोगकर्ता का id पहले से डेटाबेस में है, तो मौजूदा रिकॉर्ड को नई वैल्यू के साथ अपडेट करें. अगर ऐसा नहीं है, तो User का नया रिकॉर्ड बनाएं और उसे डेटाबेस में जोड़ें.

Python

सबसे पहले उपयोगिता का एक ऐसा तरीका बताएं जो स्टोरेज या अपडेट व्यवहार को लागू करता है.

def save_user_credentials(credentials=None, user_info=None):
    """
    Updates or adds a User to the database. A new user is added only if both
    credentials and user_info are provided.

    Args:
        credentials: An optional Credentials object.
        user_info: An optional dict containing user info returned by the
            OAuth 2.0 API.
    """

    existing_user = get_credentials_from_storage(
        flask.session.get("login_hint"))

    if existing_user:
        if user_info:
            existing_user.id = user_info.get("id")
            existing_user.display_name = user_info.get("name")
            existing_user.email = user_info.get("email")
            existing_user.portrait_url = user_info.get("picture")

        if credentials and credentials.refresh_token is not None:
            existing_user.refresh_token = credentials.refresh_token

    elif credentials and user_info:
        new_user = User(id=user_info.get("id"),
                        display_name=user_info.get("name"),
                        email=user_info.get("email"),
                        portrait_url=user_info.get("picture"),
                        refresh_token=credentials.refresh_token)

        db.session.add(new_user)

    db.session.commit()

दो स्थितियों में, अपने डेटाबेस में क्रेडेंशियल सेव किए जा सकते हैं: जब उपयोगकर्ता अनुमति देने के फ़्लो के खत्म होने पर आपके ऐप्लिकेशन पर वापस आता है और एपीआई कॉल जारी करते समय. हमने पहले सेशन credentials कुंजी को यहां से सेट किया था.

अपने callback रास्ते के आख़िर में मौजूद save_user_credentials पर कॉल करें. उपयोगकर्ता का नाम एक्सट्रैक्ट करने के बजाय, user_info ऑब्जेक्ट को बनाए रखें.

# The flow is complete! We'll use the credentials to fetch the user's info.
user_info_service = googleapiclient.discovery.build(
    serviceName="oauth2", version="v2", credentials=credentials)

user_info = user_info_service.userinfo().get().execute()

flask.session["username"] = user_info.get("name")

save_user_credentials(credentials, user_info)

एपीआई को कॉल करने के बाद, आपको क्रेडेंशियल भी अपडेट करने चाहिए. इस मामले में, अपडेट किए गए क्रेडेंशियल को save_user_credentials तरीके में आर्ग्युमेंट के तौर पर दिया जा सकता है.

# Save credentials in case access token was refreshed.
flask.session["credentials"] = credentials_to_dict(credentials)
save_user_credentials(credentials)

Java

सबसे पहले, H2 डेटाबेस में User ऑब्जेक्ट को सेव या अपडेट करने का तरीका तय करें.

/** Adds or updates a user in the database.
*   @param credential the credentials object to save or update in the database.
*   @param userinfo the userinfo object to save or update in the database.
*   @param session the current session.
*/
public void saveUser(Credential credential, Userinfo userinfo, HttpSession session) {
    User storedUser = null;
    if (session != null && session.getAttribute("login_hint") != null) {
        storedUser = getUser(session.getAttribute("login_hint").toString());
    }

    if (storedUser != null) {
        if (userinfo != null) {
            storedUser.setId(userinfo.getId());
            storedUser.setEmail(userinfo.getEmail());
        }
        userRepository.save(storedUser);
    } else if (credential != null && userinfo != null) {
        User newUser = new User(
            userinfo.getId(),
            userinfo.getEmail(),
        );
        userRepository.save(newUser);
    }
}

दो स्थितियों में, अपने डेटाबेस में क्रेडेंशियल सेव किए जा सकते हैं: जब उपयोगकर्ता अनुमति देने के फ़्लो के खत्म होने पर आपके ऐप्लिकेशन पर वापस आता है और एपीआई कॉल जारी करते समय. हमने पहले सेशन credentials कुंजी को यहां से सेट किया था.

/callback रास्ते के आखिर में मौजूद saveUser पर कॉल करें. आपको उपयोगकर्ता के ईमेल को एक्सट्रैक्ट करने के बजाय, user_info ऑब्जेक्ट को रखना चाहिए.

/** This is the end of the auth flow. We should save user info to the database. */
Userinfo userinfo = authService.getUserInfo(credentials);
saveUser(credentials, userinfo, session);

एपीआई को कॉल करने के बाद, आपको क्रेडेंशियल भी अपडेट करने चाहिए. इस मामले में, अपडेट किए गए क्रेडेंशियल को saveUser तरीके में आर्ग्युमेंट के तौर पर दिया जा सकता है.

/** Save credentials in case access token was refreshed. */
saveUser(credentials, null, session);

वे क्रेडेंशियल जिनकी समयसीमा खत्म हो चुकी है

ध्यान दें कि रीफ़्रेश टोकन के अमान्य होने की कुछ वजहें हो सकती हैं. इनमें शामिल हैं:

  • रीफ़्रेश टोकन, छह महीने से इस्तेमाल नहीं किया गया है.
  • उपयोगकर्ता आपके ऐप्लिकेशन की ऐक्सेस अनुमतियां रद्द कर देता है.
  • उपयोगकर्ता अपने पासवर्ड बदल लेता है.
  • उपयोगकर्ता, Google Cloud के किसी ऐसे संगठन से जुड़ा हो जिसके पास सेशन कंट्रोल की नीतियां लागू हैं.

अगर उपयोगकर्ता के क्रेडेंशियल अमान्य हो जाते हैं, तो उपयोगकर्ता को ऑथराइज़ेशन फ़्लो से फिर से भेजकर, नए टोकन पाएं.

उपयोगकर्ता को अपने-आप रूट करें

ऐड-ऑन लैंडिंग रूट में बदलाव करके यह पता लगाएं कि उपयोगकर्ता ने हमारे ऐप्लिकेशन को पहले अनुमति दी है या नहीं. अगर ऐसा है, तो उन्हें हमारे मुख्य ऐड-ऑन पेज पर रूट करें. अगर ऐसा नहीं है, तो उन्हें साइन इन करने का प्रॉम्प्ट दिखाएं.

Python

पक्का करें कि ऐप्लिकेशन के लॉन्च होने पर, डेटाबेस फ़ाइल बन गई है. इन्हें मॉड्यूल शुरू करने वाले टूल (जैसे कि हमारे दिए गए उदाहरण में webapp/__init__.py) में या सर्वर को लॉन्च करने वाले मुख्य तरीके में डालें.

# Initialize the database file if not created.
if not os.path.exists(DATABASE_FILE_NAME):
    db.create_all()

इसके बाद, आपके तरीके को login_hint क्वेरी पैरामीटर को हैंडल करना चाहिए, जैसा कि ऊपर बताया गया है. इसके बाद, अगर आपकी वेबसाइट पर बार-बार आने वाला उपयोगकर्ता है, तो स्टोर के क्रेडेंशियल लोड करें. आप जानते हैं कि अगर आपको login_hint मिला है, तो वह बार-बार आने वाला विज़िटर है. इस उपयोगकर्ता के लिए सेव किए गए सभी क्रेडेंशियल वापस पाएं और उन्हें सेशन में लोड करें.

stored_credentials = get_credentials_from_storage(login_hint)

# If we have stored credentials, store them in the session.
if stored_credentials:
    # Load the client secrets file contents.
    client_secrets_dict = json.load(
        open(CLIENT_SECRETS_FILE)).get("web")

    # Update the credentials in the session.
    if not flask.session.get("credentials"):
        flask.session["credentials"] = {}

    flask.session["credentials"] = {
        "token": stored_credentials.access_token,
        "refresh_token": stored_credentials.refresh_token,
        "token_uri": client_secrets_dict["token_uri"],
        "client_id": client_secrets_dict["client_id"],
        "client_secret": client_secrets_dict["client_secret"],
        "scopes": SCOPES
    }

    # Set the username in the session.
    flask.session["username"] = stored_credentials.display_name

आखिर में, अगर हमारे पास उपयोगकर्ता के क्रेडेंशियल नहीं हैं, तो उन्हें साइन इन पेज पर भेज दें. अगर हम ऐसा करते हैं, तो उन्हें मुख्य ऐड-ऑन पेज पर भेज दें.

if "credentials" not in flask.session or \
    flask.session["credentials"]["refresh_token"] is None:
    return flask.render_template("authorization.html")

return flask.render_template(
    "addon-discovery.html",
    message="You've reached the addon discovery page.")

Java

ऐड-ऑन लैंडिंग रूट पर जाएं (दिए गए उदाहरण में /addon-discovery). जैसा कि ऊपर बताया गया है, यहां से आपने login_hint क्वेरी पैरामीटर को मैनेज किया होता है.

सबसे पहले, देखें कि सेशन में क्रेडेंशियल मौजूद हैं या नहीं. अगर ऐसा नहीं होता है, तो startAuthFlow तरीके को कॉल करके, उपयोगकर्ता को ऑथराइज़ेशन फ़्लो से रूट करें.

/** Check if the credentials exist in the session. The session could have
 *   been cleared when the user clicked the Sign-Out button, and the expected
 *   behavior after sign-out would be to display the sign-in page when the
 *   iframe is opened again. */
if (session.getAttribute("credentials") == null) {
    return startAuthFlow(model);
}

इसके बाद, अगर आपकी वेबसाइट पर बार-बार आने वाले लोग हैं, तो उपयोगकर्ता को H2 डेटाबेस से लोड करें. अगर आपको login_hint क्वेरी पैरामीटर मिलता है, तो इसका मतलब है कि यह आपकी वेबसाइट पर बार-बार आने वाला ट्रैफ़िक है. अगर उपयोगकर्ता H2 डेटाबेस में मौजूद है, तो पहले सेट अप किए गए क्रेडेंशियल डेटास्टोर से क्रेडेंशियल लोड करें और सेशन में क्रेडेंशियल सेट करें. अगर क्रेडेंशियल डेटास्टोर से क्रेडेंशियल नहीं मिले हैं, तो startAuthFlow को कॉल करके उपयोगकर्ता को ऑथराइज़ेशन फ़्लो के ज़रिए रूट करें.

/** At this point, we know that credentials exist in the session, but we
 *   should update the session credentials with the credentials in persistent
 *   storage in case they were refreshed. If the credentials in persistent
 *   storage are null, we should navigate the user to the authorization flow
 *   to obtain persisted credentials. */

User storedUser = getUser(login_hint);

if (storedUser != null) {
    Credential credential = authService.loadFromCredentialDataStore(login_hint);
    if (credential != null) {
        session.setAttribute("credentials", credential);
    } else {
        return startAuthFlow(model);
    }
}

आखिर में, उपयोगकर्ता को ऐड-ऑन लैंडिंग पेज पर भेजें.

/** Finally, if there are credentials in the session and in persistent
 *   storage, direct the user to the addon-discovery page. */
return "addon-discovery";

ऐड-ऑन का परीक्षण करें

अपने Teacher टेस्ट यूज़र के तौर पर, Google Classroom में साइन इन करें. क्लासवर्क टैब पर जाएं और नया असाइनमेंट बनाएं. टेक्स्ट एरिया के नीचे मौजूद, ऐड-ऑन बटन पर क्लिक करें. इसके बाद, अपना ऐड-ऑन चुनें. ऐसा करने से, iframe खुल जाता है और ऐड-ऑन उस अटैचमेंट सेटअप यूआरआई को लोड करता है, जिसे आपने Google Workspace Marketplace SDK टूल के ऐप्लिकेशन कॉन्फ़िगरेशन पेज में तय किया है.

बधाई हो! अब आप अगले चरण पर जाने के लिए तैयार हैं: अटैचमेंट बनाना और उपयोगकर्ता की भूमिका की पहचान करना.