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

Classroom ऐड-ऑन के वॉकथ्रू सीरीज़ का यह तीसरा चरण है.

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

कदम-दर-कदम निर्देश देने के लिए, आपने ये काम किए हैं:

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

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

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

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

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

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

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

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

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

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

Python

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

# Retrieve the login_hint and hd query parameters.
login_hint = flask.request.args.get("login_hint")
hd = flask.request.args.get("hd")

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

# 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.

# If neither query parameter is available, use the values in the session.
if login_hint is None and hd is None:
    login_hint = flask.session.get("login_hint")
    hd = flask.session.get("hd")

# If there's no login_hint query parameter, then check for hd.
# Send the user to the sign in page.
elif hd is not None:
    flask.session["hd"] = hd
    return start_auth_flow()

# If the login_hint query parameter is available, we'll store it in the
# session.
else:
    flask.session["login_hint"] = login_hint

Java

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

/** 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 और hd सेव किए गए हों. यह इन वैल्यू को सेव करने के लिए सही जगह है. ये बहुत कम समय के लिए सेव की जाती हैं. साथ ही, ऐड-ऑन खोलने पर आपको नई वैल्यू मिलती हैं.

/** 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 और hd पैरामीटर, Google के पुष्टि करने वाले सर्वर पर भी पास किए जाने चाहिए. इनसे पुष्टि करने की प्रक्रिया आसान हो जाती है. अगर आपके ऐप्लिकेशन को यह पता है कि कौनसा उपयोगकर्ता पुष्टि करने की कोशिश कर रहा है, तो सर्वर इस संकेत का इस्तेमाल करके लॉगिन फ़्लो को आसान बनाता है. इसके लिए, साइन-इन फ़ॉर्म में ईमेल फ़ील्ड को पहले से भरा जाता है.

Python

अपनी Flask सर्वर फ़ाइल में, अनुमति देने के रूट पर जाएं (हमारे दिए गए उदाहरण में /authorize). flow.authorization_url को किए जाने वाले कॉल में login_hint और hd तर्क जोड़ें.

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"),
    # If we don't have login_hint, passing hd will reduce the list of
    # accounts in the account chooser to only those with the same domain.
    hd=flask.session.get("hd"))

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 एनोटेशन जोड़ें, ताकि यह पता चल सके कि यह एक POJO है, जिसे डेटाबेस में सेव किया जा सकता है. @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 फ़ाइल सेव होती है. H2 डेटाबेस में पाथ को .gitignore में जोड़ें. डेटाबेस को अपनी पसंद के उपयोगकर्ता नाम और पासवर्ड से सेट करने के लिए ऐप्लिकेशन चलाने से पहले, आपको 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;
}

setDataStoreFactory को GoogleAuthorizationCodeFlow Builder() तरीके में शामिल करने के लिए, 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 Identity पेज] देखें.

// 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 और hd क्वेरी पैरामीटर को ऊपर बताए गए तरीके से हैंडल करना चाहिए. अगर वेबसाइट पर बार-बार आने वाले उपयोगकर्ता हैं, तो स्टोर के क्रेडेंशियल लोड करें. अगर आपको 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 और hd क्वेरी पैरामीटर मैनेज किए हैं.

सबसे पहले, यह देखें कि सेशन में क्रेडेंशियल मौजूद हैं या नहीं. अगर वे ऐसा नहीं करते हैं, तो 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";

ऐड-ऑन को आज़माएं

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

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