透過授權和認證機制,安全地連線至 SQL

Firebase SQL Connect 提供強大的用戶端安全防護,包括:

  • 行動和網路用戶端授權
  • 個別查詢和變動層級授權控制項
  • 使用 Firebase App Check 進行應用程式認證。

SQL Connect 透過以下方式強化這項安全性:

  • 伺服器端授權
  • Firebase 專案和 Cloud SQL 使用者安全性 (使用 IAM)。

授權用戶端查詢和變動

SQL Connect 與 Firebase Authentication 完全整合,因此您可以在設計中使用存取資料的使用者 (驗證) 的豐富資料,決定這些使用者可以存取哪些資料 (授權)。

SQL Connect 為查詢和變異提供 @auth 指令,可讓您設定授權作業所需的驗證層級。本指南介紹 @auth 指令並提供範例。

此外,SQL Connect 支援執行嵌入在異動中的查詢,因此您可以擷取儲存在資料庫中的其他授權條件,並在 SQL Connect 指令中使用這些條件,決定是否授權封閉式異動。@check在這種授權情況下,@redact 指令可讓您控制是否要透過有線通訊協定將查詢結果傳回用戶端,以及是否要在產生的 SDK 中省略嵌入式查詢。請參閱這篇文章,瞭解這些指令的簡介和範例。

瞭解 @auth 指令

您可以將 @auth 指令參數化,以遵循多個預設存取層級之一,這些層級涵蓋許多常見的存取情境。這些層級的範圍從 PUBLIC (允許所有用戶端進行查詢和變更,不需任何驗證) 到 NO_ACCESS (不允許使用 Firebase Admin SDK 的特權伺服器環境以外的查詢和變更)。每個層級都與 Firebase Authentication 提供的驗證流程相關。

等級 定義
PUBLIC 無論是否經過驗證,任何人都能執行這項作業。
USER_ANON 任何已識別的使用者 (包括使用 Firebase Authentication 匿名登入的使用者) 都有權執行查詢或變更。
USER 凡是使用 Firebase Authentication 登入的使用者,都有權執行查詢或變更,但匿名登入的使用者除外。
USER_EMAIL_VERIFIED 任何使用 Firebase Authentication 登入且電子郵件地址已驗證的使用者,都有權執行查詢或變更。
NO_ACCESS 這項作業只能在 Admin SDK 範圍內執行。

您可以將這些預設存取層級做為起點,在 @auth 指令中使用 where 篩選器和在伺服器上評估的一般運算語言 (CEL) 運算式,定義複雜且強大的授權檢查。

使用 @auth 指令實作常見的授權情境

預設存取層級是授權的起點。

USER 存取層級是最廣泛使用的基本層級,適合做為起點。

如要全面保護存取權,請在 USER 層級上,加上篩選器和運算式,檢查使用者屬性、資源屬性、角色和其他項目。USER_ANON 和 USER_EMAIL_VERIFIED 級別是 USER 案例的變化版本。

運算式語法可讓您使用 auth 物件評估資料,該物件代表與作業一起傳遞的驗證資料,包括驗證權杖中的標準資料和權杖中的客戶資料。如需 auth 物件中可用欄位的清單,請參閱參考資料一節。

當然,在某些用途中,PUBLIC 是正確的起始存取層級。同樣地,存取層級一律是起點,您需要額外的篩選器和運算式,才能確保安全性。

本指南現在提供範例,說明如何建構 USER 和 PUBLIC。

激勵人心的範例

以下最佳做法範例參照了網誌平台的結構定義,其中部分內容須付費方案才能存取。

這類平台可能會建立 Users 和 Posts 的模型。

type User @table(key: "uid") {
  uid: String!
  name: String
  birthday: Date
  createdAt: Timestamp! @default(expr: "request.time")
}

type Post @table {
  author: User!
  text: String!
  # "one of 'draft', 'public', or 'pro'"
  visibility: String! @default(value: "draft")
  # "the time at which the post should be considered published. defaults to
  # immediately"
  publishedAt: Timestamp! @default(expr: "request.time")
  createdAt: Timestamp! @default(expr: "request.time")
  updatedAt: Timestamp! @default(expr: "request.time")
}

使用者擁有的資源

Firebase 建議您編寫篩選器和運算式,測試使用者是否擁有資源,在以下情況中,則測試是否擁有 Posts。

在以下範例中,系統會使用運算式讀取及比較驗證權杖中的資料。一般模式是使用 where: {authorUid: {eq_expr: "auth.uid"}} 等運算式,將儲存的 authorUid 與驗證權杖中傳遞的 auth.uid (使用者 ID) 進行比較。

建立

這項授權做法會先將驗證權杖中的 auth.uid 新增至每個新的 Post,做為 authorUid 欄位,以便在後續授權測試中進行比較。

# Create a new post as the current user
mutation CreatePost($text: String!, $visibility: String) @auth(level: USER) {
  post_insert(data: {
    # set the author's uid to the current user uid
    authorUid_expr: "auth.uid"
    text: $text
    visibility: $visibility
  })
}
更新

當用戶端嘗試更新 Post 時,您可以根據儲存的 authorUid 測試傳遞的 auth.uid。

# Update one of the current user's posts
mutation UpdatePost($id: UUID!, $text: String, $visibility: String) @auth(level:USER) {
  post_update(
    # only update posts whose author is the current user
    first: { where: {
      id: {eq: $id}
      authorUid: {eq_expr: "auth.uid"}
    }}
    data: {
      text: $text
      visibility: $visibility
      # insert the current server time for updatedAt
      updatedAt_expr: "request.time"
    }
  )
}
刪除

授權刪除作業時,也採用相同技術。

# Delete one of the current user's posts
mutation DeletePost($id: UUID!) @auth(level: USER) {
  post_delete(
    # only delete posts whose author is the current user
    first: { where: {
      id: {eq: $id}
      authorUid: {eq_expr: "auth.uid"}
    }}
  )
}
# Common display information for a post
fragment DisplayPost on Post {
  id, text, createdAt, updatedAt
  author { uid, name }
}
清單
# List all posts belonging to the current user
query ListMyPosts @auth(level: USER) {
  posts(where: {
    authorUid: {eq_expr: "auth.uid"}
  }) {
    # See the fragment above
    ...DisplayPost
    # also show visibility since it is user-controlled
    visibility
  }
}
GET
# Get a post only if it belongs to the current user
query GetMyPost($id: UUID!) @auth(level: USER) {
  post(
    first: {where: {
      id: {eq: $id}
      authorUid: {eq_expr: "auth.uid"}
    }}
  ) {
    # See the fragment above
    ...DisplayPost
    # also show visibility since it is user-controlled
    visibility
  }
}

篩選資料

SQL Connect 的授權系統可讓您編寫複雜的篩選器,並結合 PUBLIC 等預設存取層級,以及使用驗證權杖中的資料。

授權系統也允許您只使用運算式,不使用基本存取層級,如下列部分範例所示。

依資源屬性篩選

由於基本安全等級設為 PUBLIC,因此授權並非以驗證權杖為依據。不過,我們可以在資料庫中明確將記錄設為適合公開存取;假設資料庫中有 Post 筆記錄,且 visibility 設為「public」。

# List all posts marked as 'public' visibility
query ListPublicPosts @auth(level: PUBLIC) {
  posts(where: {
    # Test that visibility is "public"
    visibility: {eq: "public"}
    # Only display articles that are already published
    publishedAt: {lt_expr: "request.time"}
  }) {
    # see the fragment above
    ...DisplayPost
  }
}
依使用者著作權聲明篩選

假設您已設定自訂使用者聲明,透過傳遞驗證權杖來識別應用程式「專業」方案的使用者,並在驗證權杖中標記 auth.token.plan 欄位。運算式可以測試這個欄位。

# List all public or pro posts, only permitted if user has "pro" plan claim
query ProListPosts @auth(expr: "auth.token.plan == 'pro'") {
  posts(where: {
    # display both public posts and "pro" posts
    visibility: {in: ["public", "pro"]},
    # only display articles that are already published
    publishedAt: {lt_expr: "request.time"},
  }) {
    # see the fragment above
    ...DisplayPost
    # show visibility so pro users can see which posts are pro
    visibility
  }
}
依排序和限制篩選

或者,您可能在 Post 記錄中設定 visibility,以識別這些內容僅供「專業」使用者使用,但對於預覽或預告資料清單,則進一步限制傳回的記錄數量。

# Show 2 oldest Pro post as a preview
query ProTeaser @auth(level: USER) {
  posts(
    where: {
      # show only pro posts
      visibility: {eq: "pro"}
      # that have already been published more than 30 days ago
      publishedAt: {lt_time: {now: true, sub: {days: 30}}}
    },
    # order by publish time
    orderBy: [{publishedAt: DESC}],
    # only return two posts
    limit: 2
  ) {
    # See the fragment above
    ...DisplayPost
  }
}
依角色篩選

如果自訂宣告定義了 admin 角色,您可以據此測試及授權作業。

# List all posts unconditionally iff the current user has an admin claim
query AdminListPosts @auth(expr: "auth.token.admin == true") {
  posts { ...DisplayPost }
}

新增 @check 和 @redact 指令,隨手查授權資料

常見的授權用途包括將自訂授權角色儲存在資料庫中 (例如特殊權限資料表),並使用這些角色授權建立、更新或刪除資料的異動。

您可以使用授權資料查詢功能,根據使用者 ID 查詢角色,並使用 CEL 運算式決定是否授權異動。例如,您可能想編寫 UpdateMovieTitle 異動,讓授權用戶端更新電影名稱。

在接下來的討論中,假設電影評論應用程式資料庫將授權角色儲存在 MoviePermission 資料表中。

# MoviePermission
# Suppose a user has an authorization role with respect to records in the Movie table
type MoviePermission @table(key: ["movie", "user"]) {
  movie: Movie! # implies another field: movieId: UUID!
  user: User!
  role: String!
}

在變異中使用

在下列實作範例中,UpdateMovieTitle 異動包含 query 欄位,用於從 MoviePermission 擷取資料,並使用下列指令確保作業安全可靠:

  • @transaction 指令,確保所有授權查詢和檢查都已完成,或以不可分割的方式失敗。
  • @redact 指令會從回應中省略查詢結果,也就是說, 授權檢查會在 SQL Connect 伺服器上執行,但 機密資料不會公開給用戶端。
  • 一組 @check 指令,用於評估查詢結果的授權邏輯,例如測試特定 userID 是否有適當的角色可進行修改。

mutation UpdateMovieTitle($movieId: UUID!, $newTitle: String!) @auth(level: USER) @transaction {
  # Step 1: Query and check
  query @redact {
    moviePermission( # Look up a join table called MoviePermission with a compound key.
      key: {movieId: $movieId, userId_expr: "auth.uid"}
    # Step 1a: Use @check to test if the user has any role associated with the movie
    # Here the `this` binding refers the lookup result, i.e. a MoviePermission object or null
    # The `this != null` expression could be omitted since rejecting on null is default behavior
    ) @check(expr: "this != null", message: "You do not have access to this movie") {
      # Step 1b: Check if the user has the editor role for the movie
      # Next we execute another @check; now `this` refers to the contents of the `role` field
      role @check(expr: "this == 'editor'", message: "You must be an editor of this movie to update title")
    }
  }
  # Step 2: Act
  movie_update(id: $movieId, data: {
    title: $newTitle
  })
}

在查詢中使用

授權資料查詢也可用於根據角色或其他限制來限制查詢。

在以下範例中,同樣使用 MoviePermission 結構定義,查詢會檢查要求者是否具備適當的「管理員」角色,可查看能編輯電影的使用者。

query GetMovieEditors($movieId: UUID!) @auth(level: PUBLIC) {
  moviePermission(key: { movieId: $movieId, userId_expr: "auth.uid" }) @redact {
    role @check(expr: "this == 'admin'", message: "You must be an admin to view all editors of a movie.")
  }
  moviePermissions(where: { movieId: { eq: $movieId }, role: { eq: "editor" } }) {
    user {
      id
      username
    }
  }
}

授權時應避免的反模式

上一節介紹了使用 @auth 指令時應遵循的模式。

您也應瞭解應避免的重要反模式。

避免在查詢和變動引數中傳遞使用者屬性 ID 和驗證權杖參數

Firebase Authentication 是強大的工具,可用於呈現驗證流程,並安全擷取驗證資料,例如已註冊的使用者 ID 和儲存在驗證權杖中的多個欄位。

不建議在查詢和變動引數中傳遞使用者 ID 和驗證權杖資料。

# Antipattern!
# This incorrectly allows any user to view any other user's posts
query AllMyPosts($userId: String!) @auth(level: USER) {
  posts(where: {authorUid: {eq: $userId}}) {
    id, text, createdAt
  }
}

避免使用不含任何篩選條件的 USER 存取層級

如本指南多次提及,USER、USER_ANON、USER_EMAIL_VERIFIED 等核心存取層級是授權檢查的基準和起點,可透過篩選器和運算式強化。如果使用這些層級,但沒有對應的篩選器或運算式來檢查「哪位」使用者正在執行要求,基本上就等同於使用 PUBLIC 層級。

# Antipattern!
# This incorrectly allows any user to view all documents
query ListDocuments @auth(level: USER) {
  documents {
    id
    title
    text
  }
}

避免使用 PUBLIC 或 USER 存取層級進行原型設計

為了加快開發速度,您可能會想將所有作業設為 PUBLIC 存取層級或 USER 存取層級,而不進一步強化授權所有作業,並快速測試程式碼。

以這種方式完成初步原型設計後,請開始從 NO_ACCESS 切換至具有 PUBLIC 和 USER 層級、可用於正式環境的授權。不過,請勿將其部署為 PUBLIC 或 USER,除非您按照本指南所述新增額外邏輯。

# Antipattern!
# This incorrectly allows anyone to delete any post
mutation DeletePost($id: UUID!) @auth(level: PUBLIC) {
  post: post_delete(
    id: $id,
  )
}

避免根據未經驗證的電子郵件地址進行授權

授予特定網域使用者存取權,是限制存取權的好方法。不過,任何人都可以在登入時聲稱自己擁有某個電子郵件地址。請務必只將存取權授予已透過 Firebase 驗證的電子郵件地址。

# Antipattern!
# Anyone can claim an email address during sign-in
mutation CreatePost($text: String!, $visibility: String) @auth(expr: "auth.token.email.endsWith('@example.com')") {
  post_insert(data: {
    # set the author's uid to the current user uid
    authorUid_expr: "auth.uid"
    text: $text
    visibility: $visibility
  })
}

另請查看 auth.token.email_verified

mutation CreatePost($text: String!, $visibility: String) @auth(expr: "auth.token.email_verified && auth.token.email.endsWith('@example.com')") {
  post_insert(data: {
    # set the author's uid to the current user uid
    authorUid_expr: "auth.uid"
    text: $text
    visibility: $visibility
  })
}

使用 Firebase CLI 稽核授權

如前所述,PUBLIC 和 USER 等預設存取層級是建立穩健授權機制的起點,應搭配其他篩選器和以運算式為基礎的授權檢查。在未仔細考量用途的情況下,不應單獨使用。

當您使用 Firebase CLI 的 firebase deploy 部署至伺服器時,SQL Connect 會分析連接器程式碼,協助您稽核授權策略。您可以使用這項稽核功能來檢查程式碼集。

部署連接器時,CLI 會輸出連接器中現有、修改和新作業程式碼的評估結果。

對於修改和新增的作業,如果您在新作業中使用特定存取層級,或修改現有作業以使用這些存取層級,CLI 會發出警告並提示您確認。

系統一律會針對下列情況顯示警告和提示:

  • PUBLIC

此外,如果您未使用 auth.uid 篩選器擴充下列存取層級,系統會顯示警告和提示:

  • USER
  • USER_ANON
  • USER_EMAIL_VERIFIED

使用 @auth(insecureReason:) 引數隱藏不安全作業警告

在許多情況下,您會發現使用 PUBLIC 和 USER* 存取層級非常合適。

如果連接器包含許多作業,您可能需要更清楚、更相關的安全性稽核輸出內容,省略通常會觸發警告,但您知道具有正確存取層級的作業。

您可以使用 @auth(insecureReason:) 隱藏這類作業的警告。例如:

query listItem @auth(level: PUBLIC, insecureReason: "This operation is safe to expose to the public.")
  {
    items {
      id name
    }
  }

使用 Firebase App Check 進行應用程式認證

驗證和授權是 SQL Connect 安全性的重要環節。驗證和授權搭配應用程式認證,可形成非常強大的安全解決方案。

透過 Firebase App Check 進行認證時,執行應用程式的裝置會使用應用程式或裝置認證供應商,證明 SQL Connect 作業源自正版應用程式,且要求源自未經竄改的正版裝置。應用程式向 SQL Connect 發出的每項要求都會附加這項認證。

如要瞭解如何為 SQL Connect 啟用 App Check,並在應用程式中加入其用戶端 SDK,請參閱 App Check 總覽。

@auth(level) 指令的驗證層級

下表列出所有標準存取層級及其對應的 CEL。驗證層級會從廣泛到狹窄列出,每個層級都包含符合下列層級的所有使用者。

等級 定義
PUBLIC 無論是否經過驗證,任何人都能執行這項作業。

注意事項:任何使用者都能讀取或修改資料。 Firebase 建議對可公開瀏覽的資料 (例如產品或媒體清單) 採用這個授權層級。請參閱最佳做法範例和替代方案。

等同於 @auth(expr: "true")

@auth 篩選器和運算式無法與這個存取層級搭配使用。任何這類運算式都會失敗,並傳回 400 錯誤要求。
USER_ANON 任何已識別的使用者 (包括使用 Firebase Authentication 匿名登入的使用者) 都有權執行查詢或變更。

注意:USER_ANON 是 USER 的超集。

注意事項:請務必謹慎設計查詢和異動,以符合這個授權層級。這個層級允許使用者透過 Authentication 匿名登入 (自動登入僅與使用者裝置綁定),且不會自行執行其他檢查,例如資料是否屬於使用者。請參閱最佳做法範例和替代方案。

由於 Authentication 匿名登入流程會發出 uid,因此 USER_ANON 層級相當於
@auth(expr: "auth != null")
USER 凡是使用 Firebase Authentication 登入的使用者,都有權執行查詢或變更,但匿名登入的使用者除外。

注意事項:請務必謹慎設計查詢和異動,以符合這個授權層級。這個層級只會檢查使用者是否已使用 Authentication 登入,不會自行執行其他檢查,例如資料是否屬於使用者。請參閱最佳做法範例和替代方案。

等同於 @auth(expr: "auth != null && auth.token.firebase.sign_in_provider != 'anonymous'")
USER_EMAIL_VERIFIED 任何使用 Firebase Authentication 登入且電子郵件地址已驗證的使用者,都有權執行查詢或變更。

注意事項:由於電子郵件驗證是使用 Authentication 執行,因此是以更強大的 Authentication 方法為基礎,因此與 USER 或 USER_ANON 相比,這個層級可提供額外的安全性。這個層級只會檢查使用者是否已使用 Authentication 登入,且電子郵件地址已通過驗證,不會自行執行其他檢查,例如資料是否屬於使用者。請參閱最佳做法範例和替代方案。

等同於 @auth(expr: "auth != null && auth.token.email_verified")
NO_ACCESS 這項作業只能在 Admin SDK 範圍內執行。

等同於 @auth(expr: "false")

@auth(expr) 的 CEL 參考資料

如本指南其他範例所示,您可以使用一般運算語言 (CEL) 定義的運算式,透過 @auth(expr:) 和 @check 指令控制 SQL Connect 的授權。

本節將介紹與建立這些指令運算式相關的 CEL 語法。

如需 CEL 的完整參考資訊,請參閱 CEL 規格。

測試在查詢和變異中傳遞的變數

@auth(expr) 語法可讓您存取及測試查詢和變異中的變數。

舉例來說,您可以使用 vars.status 加入作業變數,例如 $status。

mutation Update($id: UUID!, $status: Any) @auth(expr: "has(vars.status)")

運算式可用的資料:request、response、this

資料的用途包括:

  • 在 @auth(expr:) 和 @check(expr:) 指令中使用 CEL 運算式進行評估
  • 使用伺服器運算式 <field>_expr 進行指派。

@auth(expr:)、@check(expr:)、@refresh(onMutationExecuted:) CEL 運算式可評估下列項目:

  • request.operationName
  • vars (request.variables 的別名)
  • auth (request.auth 的別名)

在變異中,您可以存取及指派下列項目的內容:

  • response (用於檢查多步驟邏輯中的部分結果)

此外,@check(expr:) 運算式可以評估:

  • this (目前欄位的值)
  • response (用於檢查多步驟邏輯中的部分結果)

@refresh(onMutationExecuted:) 運算式則有下列繫結:

  • mutation.variables
  • mutation.auth

request.operationName 繫結

request.operationName 繫結會儲存執行中的 GraphQL 作業名稱,例如 ListMyPosts 或 CreatePost。

vars 繫結 (request.variables)

vars 繫結可讓運算式存取查詢或變動中傳遞的所有變數。

您可以在運算式中使用 vars.<variablename> 做為完整 request.variables.<variablename> 的別名:

# The following are equivalent
mutation StringType($v: String!) @auth(expr: "vars.v == 'hello'")
mutation StringType($v: String!) @auth(expr: "request.variables.v == 'hello'")

auth 繫結 (request.auth)

Authentication 會識別要求存取資料的使用者,並以繫結形式提供該資訊,供您在運算式中使用。

在篩選器和運算式中,您可以使用 auth 做為 request.auth 的別名。

授權繫結包含下列資訊:

  • uid:指派給要求使用者的專屬使用者 ID。
  • token:Authentication 收集的值對應。

如要進一步瞭解 auth.token 的內容,請參閱「驗證權杖中的資料」

response 繫結

response 繫結包含伺服器在回應查詢或變更時組合的資料,在組合資料時。

隨著作業進行,每當步驟順利完成,response 就會包含成功完成步驟的回應資料。

response 繫結的結構取決於相關聯作業的形狀,包括 (多個) 巢狀欄位和 (如適用) 內嵌查詢。

請注意,存取嵌入查詢回應資料時,欄位可能包含任何資料類型,具體取決於嵌入查詢中要求的資料;存取變動欄位 (例如 _insert 和 _delete) 傳回的資料時,這些資料可能包含 UUID 鍵、刪除次數、空值 (請參閱變動參考資料)。

例如:

  • 在包含嵌入查詢的異動中,response 繫結包含 response.query.<fieldName>.<fieldName>.... 的查詢資料,在本例中為 response.query.todoList 和 response.query.todoList.priority。
mutation CheckTodoPriority(
  $uniqueListName: String!
) {
  # This query is identified as `response.query`
  query @check(expr: "response.query.todoList.priority == 'high'", message: "This list is not for high priority items!") {
    # This field is identified as `response.query.todoList`
    todoList(first: { where: { name: { eq: $uniqueListName } } }) {
      # This field is identified as `response.query.todoList.priority`
      priority
    }
  }
}
  • 在多步驟變異中 (例如有多個 _insert 欄位),response 繫結會在 response.<fieldName>.<fieldName>.... 包含部分資料,在本例中為 response.todoList_insert.id。
mutation CreateTodoListWithFirstItem(
  $listName: String!,
  $itemContent: String!
) @transaction {
  # Step 1
  todoList_insert(data: {
    id_expr: "uuidV4()",
    name: $listName,
  })
  # Step 2:
  todo_insert(data: {
    listId_expr: "response.todoList_insert.id" # <-- Grab the newly generated ID from the partial response so far.
    content: $itemContent,
  })
}

this 繫結

繫結 this 會評估 @check 指令附加的欄位。在基本情況下,您可能會評估單一值的查詢結果。

mutation UpdateMovieTitle (
  $movieId: UUID!,
  $newTitle: String!)
  @auth(level: USER)
  @transaction {
  # Step 1: Query and check
  query @redact {
    moviePermission( # Look up a join table called MoviePermission with a compound key.
      key: {movieId: $movieId, userId_expr: "auth.uid"}
    ) {
      # Check if the user has the editor role for the movie. `this` is the string value of `role`.
      # If the parent moviePermission is null, the @check will also fail automatically.
      role @check(expr: "this == 'editor'", message: "You must be an editor of this movie to update title")
    }
  }
  # Step 2: Act
  movie_update(id: $movieId, data: {
    title: $newTitle
  })
}

如果傳回的欄位因任何上層欄位為清單而多次出現,系統會測試每次出現的情況,並將 this 繫結至每個值。

對於任何指定路徑,如果上層是 null 或 [],系統就不會到達該欄位,並會略過該路徑的 CEL 評估。換句話說,只有在 this 為 null 或非 null 時,才會進行評估,但絕不會是 undefined。

如果欄位本身是清單或物件,this 會遵循相同的結構 (包括為物件選取的所有子項),如以下範例所示。

mutation UpdateMovieTitle2($movieId: UUID!, $newTitle: String!) @auth(level: USER) @transaction {
  # Step 1: Query and check
  query {
    moviePermissions( # Now we query for a list of all matching MoviePermissions.
      where: {movieId: {eq: $movieId}, userId: {eq_expr: "auth.uid"}}
    # This time we execute the @check on the list, so `this` is the list of objects.
    # We can use the `.exists` macro to check if there is at least one matching entry.
    ) @check(expr: "this.exists(p, p.role == 'editor')", message: "You must be an editor of this movie to update title") {
      role
    }
  }
  # Step 2: Act
  movie_update(id: $movieId, data: {
    title: $newTitle
  })
}

複雜運算式語法

您可以結合 && 和 || 運算子,編寫更複雜的運算式。

mutation UpsertUser($username: String!) @auth(expr: "(auth != null) && (vars.username == 'joe')")

以下各節說明所有可用的運算子。

運算子和運算子優先順序

請參考下表,瞭解運算子及其對應的優先順序。

假設有任意運算式 a 和 b、欄位 f 和索引 i。

運算子 說明 結合律
a[i] a() a.f 索引、呼叫、欄位存取 由左至右
!a -a 一元否定 從右到左
a/b a%b a*b 乘法運算子 由左至右
a+b a-b 加法運算子 由左至右
a>b a>=b a<b a<=b 關係運算子 由左至右
a in b 清單或地圖中是否存在 由左至右
type(a) == t 類型比較,其中 t 可以是 bool、int、float、number、string、list、map、timestamp 或 duration 由左至右
a==b a!=b 比較運算子 由左至右
a && b 條件式 AND 由左至右
a || b 條件式 OR 由左至右
a ? true_value : false_value 三元運算式 由左至右

驗證權杖中的資料

auth.token 物件可能包含下列值:

欄位 說明
email 與帳戶相關聯的電子郵件地址 (如有)。
email_verified 如果使用者已驗證自己有權存取 email 地址,則為 true。部分供應商會自動驗證其擁有的電子郵件地址。
phone_number 與帳戶相關聯的電話號碼 (如有)。
name 使用者的顯示名稱 (如有設定)。
sub 使用者的 Firebase UID。在專案中不得重複。
firebase.identities 與這位使用者帳戶相關聯的所有身分字典。字典的鍵可以是下列任一項:email、phone、google.com、facebook.com、github.com、twitter.com。字典的值是與帳戶相關聯的每個識別資訊提供者的專屬 ID 陣列。舉例來說,auth.token.firebase.identities["google.com"][0] 包含與帳戶相關聯的第一個 Google 使用者 ID。
firebase.sign_in_provider 用於取得這個權杖的登入服務供應商。可以是下列其中一個字串:custom、password、phone、anonymous、google.com、facebook.com、github.com、twitter.com。
firebase.tenant 與帳戶相關聯的 tenantId (如有)。例如 tenant2-m6tyz。

JWT ID 權杖中的其他欄位

您也可以存取下列 auth.token 欄位:

自訂權杖附加資訊
alg 演算法 "RS256"
iss 核發單位 專案服務帳戶的電子郵件地址
sub 主旨 專案服務帳戶的電子郵件地址
aud 目標對象 "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit"
iat 核發時間 目前時間,以 Unix 紀元起算,單位為秒
exp 到期時間 權杖到期時間,以 UNIX 紀元時間為始 (單位為秒)。最多可比 iat 晚 3600 秒。
注意:這只會控制自訂權杖本身的到期時間。不過,一旦您使用 signInWithCustomToken() 讓使用者登入,他們就會保持登入裝置的狀態,直到工作階段失效或使用者登出為止。
<claims> (選用) 要加入權杖的選用自訂宣告,可透過運算式中的 auth.token (或 request.auth.token) 存取。舉例來說,如果您建立自訂要求 adminClaim,可以使用 auth.token.adminClaim 存取。

後續步驟