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

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

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

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

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

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

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

Classroom, आपके ऐड-ऑन के अटैचमेंट सेटअप यूआरआई को लोड होने पर लोड करता है खोलें. क्लासरूम यूआरआई में कई GET क्वेरी पैरामीटर जोड़ता है; तो ये उपयोगी हैं काम की जानकारी. उदाहरण के लिए, अगर आपका अटैचमेंट डिस्कवरी यूआरआई https://example.com/addon, Classroom इनका इस्तेमाल करके iframe बनाता है सोर्स यूआरएल इस पर सेट हो https://example.com/addon?courseId=XXX&itemId=YYY&itemType=courseWork&addOnToken=ZZZ, जहां 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 जैसा). इस कॉल में login_hint आर्ग्युमेंट जोड़ें: flow.authorization_url.

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

सीआरयूडी से जुड़ी कार्रवाइयां मैनेज करने के लिए, 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 बूट में काम करता है. इस डेटाबेस का इस्तेमाल बाद के चरण में भी किया जाता है 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;
}

शामिल करने के लिए, 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, लेकिन पहले इसकी पुष्टि ज़रूरी है. अगर ऐसा नहीं है, तो क्लाइंट ऐप्लिकेशन, संशोधित उपयोगकर्ता को भेजकर उपयोगकर्ताओं के नाम पर काम कर सकते हैं आईडी डालें. तो Google API क्लाइंट का इस्तेमाल करने की सलाह दी जाती है लाइब्रेरी, ताकि id_token की पुष्टि की जा सके. [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 को फ़ेच करने का तरीका तय करें. आपको इसमें id दिया गया है: login_hint क्वेरी पैरामीटर, जिसका इस्तेमाल किसी खास उपयोगकर्ता को वापस लाने के लिए किया जा सकता है रिकॉर्ड करने के लिए.

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 टूल का ऐप्लिकेशन कॉन्फ़िगरेशन पेज.

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