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

यह Classroom के ऐड-ऑन के बारे में जानकारी देने वाली सीरीज़ का तीसरा वॉकथ्रू है.

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

इस वॉकट्रू के दौरान, आपको ये काम करने होंगे:

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

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

आईफ़्रेम के क्वेरी पैरामीटर के बारे में जानकारी

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

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

  • 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

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

/** Retrieve the login_hint query parameter from the request URL if present. */
String login_hint = request.getParameter("login_hint");

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

/** If login_hint wasn't sent, use the values in the session. */
if (login_hint == null) {
    login_hint = (String) session.getAttribute("login_hint");
}

/** If the there is still no login_hint, route the user to the authorization
 *  page. */
if (login_hint == null) {
    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

अपनी Flask सर्वर फ़ाइल में, अनुमति देने वाले रूट पर जाएं (/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 को पैरामीटर के तौर पर जोड़ें. साथ ही, login_hint और आर्ग्युमेंट को अनुमति देने वाले यूआरएल बिल्डर में जोड़ें.

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

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

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

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

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

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

Python

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

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

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

इस उदाहरण में, SQLite का इस्तेमाल करके स्टोरेज को लागू किया गया है. 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

इससे Flask को 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, इस फ़ाइल को पढ़ता है और इसके हिसाब से डेटाबेस के लिए स्कीमा जनरेट करता है. टेबल को टेबल के नाम, users, और कॉलम के साथ तय करें. इन कॉलम में User एट्रिब्यूट, id, और email को दिखाया जाएगा.

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 में कॉन्फ़िगर किए गए टेबल के नाम के साथ @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 डेटाबेस का इस्तेमाल करें. यह डेटाबेस, Spring Boot में पहले से मौजूद होता है. इस डेटाबेस का इस्तेमाल, बाद के वॉकट्रू में भी किया जाता है. इससे 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;
}

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

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

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

उपयोगकर्ता आईडी को TokenResponse ऑब्जेक्ट से id_token का इस्तेमाल करके हासिल किया जा सकता है. हालांकि, इसकी पुष्टि करना ज़रूरी है. ऐसा न होने पर, क्लाइंट ऐप्लिकेशन सर्वर को बदले गए उपयोगकर्ता आईडी भेजकर, उपयोगकर्ताओं के नाम पर काम कर सकते हैं. हमारा सुझाव है कि आप id_token की पुष्टि करने के लिए, Google API क्लाइंट लाइब्रेरी का इस्तेमाल करें. ज़्यादा जानकारी के लिए, [Google Identity पेज पर 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";

ऐड-ऑन की जांच करना

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

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