จัดการการเข้าสู่ระบบซ้ำ

นี่คือคำแนะนำที่ 3 ในชุดคำแนะนำเกี่ยวกับส่วนเสริมของ Classroom

ในคำแนะนำแบบทีละขั้นนี้ คุณจะจัดการการเข้าชมซ้ำในส่วนเสริมของเราโดยการดึงข้อมูลเข้าสู่ระบบที่ผู้ใช้ให้สิทธิ์ไว้ก่อนหน้านี้โดยอัตโนมัติ จากนั้นคุณจะกำหนดเส้นทางให้ผู้ใช้ไปยัง หน้าเว็บที่ผู้ใช้สามารถส่งคำขอ API ได้ทันที ซึ่งเป็นลักษณะการทำงานที่จำเป็น สำหรับส่วนเสริมของ Classroom

ในวิดีโอแนะนำนี้ คุณจะทำสิ่งต่อไปนี้

  • ใช้พื้นที่เก็บข้อมูลถาวรสำหรับข้อมูลเข้าสู่ระบบของผู้ใช้
  • เรียกข้อมูลและประเมินพารามิเตอร์การค้นหาของส่วนเสริม login_hint นี่คือ หมายเลขรหัส Google ที่ไม่ซ้ำกันของผู้ใช้ที่ลงชื่อเข้าใช้

เมื่อเสร็จแล้ว คุณจะให้สิทธิ์ผู้ใช้ในเว็บแอปได้อย่างเต็มที่และเรียกใช้ Google API ได้

ทําความเข้าใจพารามิเตอร์การค้นหา iframe

Classroom จะโหลด URI การตั้งค่าไฟล์แนบของส่วนเสริมเมื่อเปิด Classroom จะต่อท้ายGETพารามิเตอร์การค้นหาหลายรายการใน URI ซึ่งมีข้อมูลบริบทที่เป็นประโยชน์ เช่น หาก URI การค้นพบไฟล์แนบคือ https://example.com/addon Classroom จะสร้าง iframe โดยตั้งค่า URL แหล่งที่มาเป็น https://example.com/addon?courseId=XXX&itemId=YYY&itemType=courseWork&addOnToken=ZZZ โดยที่ XXX, YYY และ ZZZ คือรหัสสตริง ดูคำอธิบายโดยละเอียดของสถานการณ์นี้ได้ในคำแนะนำเกี่ยวกับ iframe

พารามิเตอร์การค้นหาที่เป็นไปได้สำหรับ URL การค้นพบมี 5 รายการดังนี้

  • courseId: รหัสของหลักสูตร Classroom ปัจจุบัน
  • itemId: รหัสของรายการสตรีมที่ผู้ใช้กำลังแก้ไขหรือสร้าง
  • itemType: ประเภทของรายการสตรีมที่ผู้ใช้สร้างหรือแก้ไข ซึ่งอาจเป็น courseWork, courseWorkMaterial หรือ announcement
  • addOnToken: โทเค็นที่ใช้เพื่อให้สิทธิ์การดำเนินการบางอย่างของส่วนเสริม Classroom
  • login_hint: รหัส Google ของผู้ใช้ปัจจุบัน

คำแนะนำแบบทีละขั้นนี้จะอธิบายเกี่ยวกับ login_hint ระบบจะกำหนดเส้นทางผู้ใช้ตามว่ามีการระบุพารามิเตอร์การค้นหานี้หรือไม่ โดยจะกำหนดเส้นทางไปยังขั้นตอนการให้สิทธิ์หากไม่มี หรือไปยังหน้าการค้นหาส่วนเสริมหากมี

เข้าถึงพารามิเตอร์การค้นหา

ระบบจะส่งพารามิเตอร์การค้นหาไปยังเว็บแอปพลิเคชันในสตริง URI จัดเก็บ ค่าเหล่านี้ในเซสชันของคุณ โดยค่าเหล่านี้จะใช้ในขั้นตอนการให้สิทธิ์ รวมถึงใช้เพื่อ จัดเก็บและเรียกข้อมูลเกี่ยวกับผู้ใช้ ระบบจะส่งพารามิเตอร์การค้นหาเหล่านี้เมื่อเปิดส่วนเสริมเป็นครั้งแรกเท่านั้น

Python

ไปที่คำจำกัดความของเส้นทาง Flask (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 ในตัวอย่างที่เราให้ไว้) เพิ่มอาร์กิวเมนต์ 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

ไปที่เมธอด authorize() ในคลาส AuthService.java เพิ่ม login_hint เป็นพารามิเตอร์ในเมธอด และเพิ่ม login_hint และอาร์กิวเมนต์ลงในตัวสร้าง URL การให้สิทธิ์

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

เพิ่มพื้นที่เก็บข้อมูลแบบถาวรสำหรับข้อมูลเข้าสู่ระบบของผู้ใช้

หากคุณได้รับ login_hint เป็นพารามิเตอร์การค้นหาเมื่อส่วนเสริมโหลด นั่นหมายความว่าผู้ใช้ได้ทำขั้นตอนการให้สิทธิ์สำหรับแอปพลิเคชันของเราเสร็จสมบูรณ์แล้ว คุณควรดึงข้อมูลเข้าสู่ระบบก่อนหน้าแทนที่จะบังคับให้ ผู้ใช้ลงชื่อเข้าใช้อีกครั้ง

โปรดทราบว่าคุณได้รับโทเค็นการรีเฟรชเมื่อขั้นตอนการให้สิทธิ์เสร็จสมบูรณ์ บันทึกโทเค็นนี้ไว้เพื่อนำไปใช้ซ้ำในการขอโทเค็นเพื่อการเข้าถึง ซึ่งมีอายุสั้นและจำเป็นต่อการใช้ Google APIs ก่อนหน้านี้คุณได้บันทึกข้อมูลเข้าสู่ระบบเหล่านี้ไว้ในเซสชัน แต่คุณต้องจัดเก็บข้อมูลเข้าสู่ระบบเพื่อจัดการการเข้าชมซ้ำ

กำหนดสคีมาผู้ใช้และตั้งค่าฐานข้อมูล

ตั้งค่าสคีมาฐานข้อมูลสำหรับ User

Python

กำหนดสคีมาผู้ใช้

User มีแอตทริบิวต์ต่อไปนี้

  • id: รหัส Google ของผู้ใช้ ซึ่งควรตรงกับค่าที่ระบุไว้ในพารามิเตอร์การค้นหา login_hint
  • display_name: ชื่อและนามสกุลของผู้ใช้ เช่น "Alex Smith"
  • email: อีเมลของผู้ใช้
  • portrait_url: 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

ซึ่งจะชี้ให้ 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: อีเมลของผู้ใช้

สร้างไฟล์ schema.sql ในไดเรกทอรี resources ของโมดูล 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
);

สร้างคลาส Java เพื่อกําหนดUserโมเดลสําหรับฐานข้อมูล ซึ่งก็คือ User.java ในตัวอย่างที่ให้ไว้

เพิ่มคำอธิบายประกอบ @Entity เพื่อระบุว่านี่คือ POJO ที่บันทึกลงในฐานข้อมูลได้ เพิ่มคำอธิบายประกอบ @Table พร้อมชื่อตารางที่เกี่ยวข้องซึ่งคุณกำหนดค่าไว้ใน schema.sql

โปรดทราบว่าตัวอย่างโค้ดมีตัวสร้างและตัวตั้งค่าสำหรับแอตทริบิวต์ 2 รายการ โดยจะใช้ตัวสร้างและตัวตั้งค่าใน 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 เพื่อจัดการการดำเนินการ CRUD ในฐานข้อมูล อินเทอร์เฟซนี้ขยายอินเทอร์เฟซ CrudRepository

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

คลาส Controller ช่วยอำนวยความสะดวกในการสื่อสารระหว่างไคลเอ็นต์กับ ที่เก็บ ดังนั้น ให้อัปเดตตัวสร้างคลาสของตัวควบคุมเพื่อแทรกคลาส 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 config จะสร้างไดเรกทอรีชื่อ h2 โดยมี ไฟล์ userdb อยู่ภายใน เพิ่มเส้นทางไปยังฐานข้อมูล H2 ลงใน .gitignore คุณต้องอัปเดต spring.datasource.username และ spring.datasource.password ก่อนเรียกใช้แอปพลิเคชันเพื่อตั้งค่า ฐานข้อมูลด้วยชื่อผู้ใช้และรหัสผ่านที่คุณเลือก หากต้องการอัปเดต ชื่อผู้ใช้และรหัสผ่านสำหรับฐานข้อมูลหลังจากเรียกใช้แอปพลิเคชัน ให้ลบไดเรกทอรี h2 ที่สร้างขึ้น อัปเดตการกำหนดค่า และ เรียกใช้แอปพลิเคชันอีกครั้ง

การตั้งค่าคอนฟิก spring.jpa.hibernate.ddl-auto เป็น update จะช่วยให้มั่นใจได้ว่า ระบบจะเก็บรักษาข้อมูลที่จัดเก็บไว้ในฐานข้อมูลเมื่อรีสตาร์ทแอปพลิเคชัน หากต้องการล้างฐานข้อมูลทุกครั้งที่รีสตาร์ทแอปพลิเคชัน ให้ตั้งค่า config นี้เป็น create

ตั้งค่า spring.jpa.open-in-view เป็น false การกำหนดค่านี้จะเปิดใช้โดยค่าเริ่มต้น และอาจทำให้เกิดปัญหาด้านประสิทธิภาพที่วิเคราะห์ได้ยากในเวอร์ชันที่ใช้งานจริง

ดังที่อธิบายไว้ก่อนหน้านี้ คุณต้องสามารถดึงข้อมูลเข้าสู่ระบบของ ผู้ใช้ที่กลับมาใช้ซ้ำได้ ซึ่งทำได้ด้วยการรองรับที่เก็บข้อมูลเข้าสู่ระบบในตัว ที่ GoogleAuthorizationCodeFlow มีให้

ในAuthService.java คลาส ให้กำหนดเส้นทางไปยังไฟล์ที่เก็บคลาสข้อมูลเข้าสู่ระบบ ในตัวอย่างนี้ ระบบจะสร้างไฟล์ในไดเรกทอรี /credentialStore เพิ่มเส้นทางไปยังที่เก็บข้อมูลเข้าสู่ระบบลงใน .gitignore ระบบจะสร้างไดเรกทอรีนี้เมื่อผู้ใช้เริ่ม โฟลว์การให้สิทธิ์

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

จากนั้นสร้างเมธอดในไฟล์ AuthService.java ที่สร้างและ แสดงผลออบเจ็กต์ FileDataStoreFactory นี่คือ Datastore ที่ จัดเก็บข้อมูลเข้าสู่ระบบ

/** 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;
}

อัปเดตgetFlow()เมธอดใน AuthService.java เพื่อรวม setDataStoreFactory ในเมธอด GoogleAuthorizationCodeFlow Builder() และเรียกใช้ getCredentialDataStore() เพื่อตั้งค่า Datastore

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

จากนั้นอัปเดตgetAndSaveCredentials(String authorizationCode) ก่อนหน้านี้ วิธีนี้จะรับข้อมูลเข้าสู่ระบบโดยไม่จัดเก็บไว้ที่ใด เลย อัปเดตวิธีการจัดเก็บข้อมูลเข้าสู่ระบบใน Datastore ที่จัดทำดัชนีตามรหัสผู้ใช้

คุณขอรับรหัสผู้ใช้ได้จากออบเจ็กต์ TokenResponse โดยใช้ id_token แต่ต้องยืนยันก่อน มิฉะนั้น แอปพลิเคชันไคลเอ็นต์ อาจแอบอ้างเป็นผู้ใช้ได้โดยการส่งรหัสผู้ใช้ที่แก้ไขแล้ว ไปยังเซิร์ฟเวอร์ เราขอแนะนำให้คุณใช้ไลบรารีของไคลเอ็นต์ Google API เพื่อตรวจสอบ id_token ดูข้อมูลเพิ่มเติมได้ที่ [หน้าข้อมูลประจำตัวของ 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();

อัปเดตการเรียกใช้ flow.createAndStoreCredential เพื่อรวม userId

// 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;
}

จัดเก็บข้อมูลเข้าสู่ระบบ

มี 2 สถานการณ์เมื่อจัดเก็บข้อมูลเข้าสู่ระบบ หาก 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()

คุณอาจบันทึกข้อมูลเข้าสู่ระบบลงในฐานข้อมูลใน 2 กรณี ได้แก่ เมื่อผู้ใช้กลับมาที่แอปพลิเคชันของคุณในตอนท้ายของขั้นตอนการให้สิทธิ์ และเมื่อออกการเรียก API ซึ่งเป็นตำแหน่งที่เรา ตั้งค่าคีย์ credentials ของเซสชันไว้ก่อนหน้านี้

โทรหา save_user_credentials เมื่อสิ้นสุดเส้นทาง callback เก็บออบเจ็กต์ 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)

นอกจากนี้ คุณควรอัปเดตข้อมูลเข้าสู่ระบบหลังจากการเรียก API ด้วย ในกรณีนี้ คุณสามารถระบุข้อมูลเข้าสู่ระบบที่อัปเดตเป็นอาร์กิวเมนต์ให้กับเมธอด save_user_credentials ได้

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

Java

ก่อนอื่น ให้กำหนดเมธอดที่จัดเก็บหรืออัปเดตออบเจ็กต์ User ในฐานข้อมูล H2

/** 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);
    }
}

คุณอาจบันทึกข้อมูลเข้าสู่ระบบลงในฐานข้อมูลใน 2 กรณี ได้แก่ เมื่อผู้ใช้กลับมาที่แอปพลิเคชันของคุณในตอนท้ายของขั้นตอนการให้สิทธิ์ และเมื่อออกการเรียก API ซึ่งเป็นตำแหน่งที่เรา ตั้งค่าคีย์ credentials ของเซสชันไว้ก่อนหน้านี้

โทรหา saveUser ที่จุดสิ้นสุดของเส้นทาง /callback คุณควรเก็บออบเจ็กต์ 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);

นอกจากนี้ คุณควรอัปเดตข้อมูลเข้าสู่ระบบหลังจากการเรียก API ด้วย ในกรณีนี้ คุณสามารถระบุข้อมูลเข้าสู่ระบบที่อัปเดตเป็นอาร์กิวเมนต์ให้กับเมธอด saveUser ได้

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

ข้อมูลเข้าสู่ระบบที่หมดอายุ

โปรดทราบว่าโทเค็นการรีเฟรชอาจใช้ไม่ได้ด้วยเหตุผลบางประการ ซึ่งได้แก่

  • ไม่มีการใช้โทเค็นการรีเฟรชมาเป็นเวลา 6 เดือนแล้ว
  • ผู้ใช้เพิกถอนสิทธิ์การเข้าถึงของแอป
  • ผู้ใช้เปลี่ยนรหัสผ่าน
  • ผู้ใช้เป็นสมาชิกขององค์กร 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);
    }
}

สุดท้าย ให้กำหนดเส้นทางผู้ใช้ไปยังหน้า Landing Page ของส่วนเสริม

/** 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 จะเปิดขึ้นและส่วนเสริมจะโหลด URI การตั้งค่าไฟล์แนบที่คุณระบุในหน้าการกำหนดค่าแอปของ SDK ของ Google Workspace Marketplace

ยินดีด้วย คุณพร้อมที่จะไปยังขั้นตอนถัดไปแล้ว นั่นคือการสร้างไฟล์แนบ และการระบุบทบาทของผู้ใช้