Skip to main content

合作伙伴数据库配置和用户声明流程

介绍

¥Introduction

本指南将引导你了解如何使用 Prisma Postgres Management API 来增强类似 npx create-db 命令的体验。

¥This guide walks you through how to use the Prisma Postgres Management API, to power experiences like the npx create-db command.

你将学习如何以合作伙伴身份在你的工作区中配置 Prisma Postgres 数据库,以及如何将其传输到其他用户的工作区,以便他们可以 "claim" 数据库。我们将介绍如何使用 OAuth2 保护该流程,最后,你将了解完整的流程以及如何将其集成到你自己的产品体验中。

¥You'll learn how to provision a Prisma Postgres database on your workspace as a partner, and how to transfer it to another user's workspace so they can "claim" the database. We'll cover how the process is secured using OAuth2, and by the end, you'll understand the full flow and how to integrate it into your own product experience.

本指南引用了 npx create-db CLI 和 Cloudflare Workers 中的实际实现作为真实示例。npx create-db 的仓库是 此处,你可以将其作为如何在你自己的项目中使用 Management API 的参考。

¥This guide references the actual implementation in the npx create-db CLI and Cloudflare Workers as real world examples. The repo for the npx create-db is here, which can be used as a reference for how to use the Management API in your own projects.

这与你的应用如何契合?

本指南中的两个 Cloudflare Workers 仅供参考。你通常会将此逻辑构建到你自己的后端或无服务器函数中。

¥The two Cloudflare Workers in this guide are just reference examples. You would typically build this logic into your own backend or serverless functions.

同样,npx create-db CLI 是一个简单的演示。在你的产品中,你可以从自己的 UI 或入门流程触发相同的 API 调用,从而为用户打造无缝的体验。

¥Similarly, the npx create-db CLI is a simple demo. In your product, you can trigger the same API calls from your own UI or onboarding flows to create a seamless experience for your users.

核心概念

¥Core Concepts

在深入实现之前,让我们先理清一下管理 API 集成中涉及的主要概念:

¥Before diving into implementation, let's clarify the main concepts involved in the Management API integration:

  • 管理 API:一组允许以编程方式配置和管理 Prisma Postgres 数据库的端点。

    ¥Management API: A set of endpoints that allow to programmatically provision and manage Prisma Postgres databases.

  • 项目 vs 数据库:项目是一个可以容纳多个数据库的容器。你可以使用它来组织你创建的数据库,例如按用户。然后可以将项目(包括其中包含的所有数据库)转移给用户。

    ¥Projects vs Databases: A project is a container that can hold multiple databases. You can use this to organize databases you create e.g. by user. Projects can then be transferred to users, including all databases they contain.

  • 验证:所有 API 请求都需要身份验证。作为合作伙伴,你可以使用 OAuth2 获取集成令牌(用于你的应用),并促进向用户的安全传输。

    ¥Authentication: All API requests require authentication. As a partner, you use OAuth2 to obtain integration tokens (for your app) and facilitate secure transfers to your users.

  • 令牌:令牌主要有两种类型:

    ¥Tokens: There are two main types of tokens:

    • 集成令牌:发布到你的合作伙伴集成,用于在你自己的工作区中配置和管理数据库。

      ¥Integration Token: Issued to your partner integration, scoped to provision and manage databases on your own workspace.

    • 用户访问令牌:当用户使用你的应用进行身份验证时,通过 OAuth2 获取,作用域为用户的工作区,可用于将数据库所有权转移到用户的工作区。

      ¥User Access Token: Obtained via OAuth2 when a user authenticates with your app, scoped to the user's workspace and can be used to transfer database ownership to the user's workspace.

如何成为合作伙伴

¥How to become a partner

要使用 Prisma Postgres 管理 API,你首先需要设置为合作伙伴:

¥To use the Prisma Postgres Management API, you first need to set up as a partner:

  1. 请求访问管理 API:联系 Prisma 团队,从 Prisma 合作伙伴页面 请求访问管理 API。你将被引导完成入门流程。

    ¥Request access to the Management API: Contact the Prisma team from the Prisma Partners page to request access to the Management API. You will be guided through the onboarding process.

  2. 获取 OAuth 凭证:获得批准后,你将收到一个 OAuth 客户端 ID 和客户端密钥。这些凭据是验证集成和为用户启用安全数据库传输所必需的。

    ¥Obtain OAuth credentials: Once approved, you will receive an OAuth client ID and client secret. These credentials are required to authenticate your integration and enable secure database transfers for your users.

有关可用端点的完整列表以及请求/响应格式的详细信息,请参阅 Prisma 管理 API 文档

¥For a complete list of available endpoints and details on request/response formats, see the Prisma Management API documentation.

以合作伙伴身份配置数据库

¥Provisioning a Database as a Partner

要为你的合作伙伴用户配置新的 Prisma Postgres 数据库,请按照以下步骤操作:

¥To provision a new Prisma Postgres database for your users as a partner, follow these steps:

  1. 收集所需信息:准备配置所需的详细信息,例如区域、数据库名称以及应用所需的任何其他选项。此信息可能来自用户输入,也可能由你的应用逻辑决定。

    ¥Gather required information: Prepare the necessary details for provisioning, such as region, database name, and any other options your application requires. This information may come from user input or be determined by your application logic.

  2. 验证你的集成:使用你的集成令牌(通过 OAuth2 获取)对 API 请求进行身份验证。此令牌将你的应用验证为已批准的合作伙伴。

    ¥Authenticate your integration: Use your integration token (obtained via OAuth2) to authenticate API requests. This token authenticates your app as an approved partner.

  3. 发送数据库配置请求:向 Management API 端点发出 POST 请求,以创建一个具有默认数据库的新项目。例如:

    ¥Send a database provisioning request: Make a POST request to the Management API endpoint to create a new project with a default database. For example:

const prismaResponse = await fetch('https://api.prisma.io/v1/projects', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer <YOUR_INTEGRATION_TOKEN>`,
},
body: JSON.stringify({ region, name }),
});
  1. 处理响应:如果成功,API 将返回新项目的详细信息,包括数据库连接字符串和 project_id。安全地存储这些内容并根据需要显示给用户。

    ¥Handle the response: If successful, the API will return the new project's details, including database connection strings and a project_id. Store these securely and display them to your user as needed.

  2. (可选的)存储项目元数据:你可能希望在你自己的数据库中将 project_id 与你的用户关联,以便将来参考。

    ¥(Optional) Store project metadata: You may want to associate the project_id with your user in your own database for future reference.

数据库声明流程

¥Database Claim Flow

配置数据库后,你可能希望稍后将所有权转移给你的用户,以便他们可以在自己的 Prisma 工作区中管理数据库,并超越免费数据库的使用限制。此操作通过声明流程完成,该流程包含三个主要步骤:

¥Once a database is provisioned, you may want to transfer ownership to your user at a later point so they can manage it in their own Prisma workspace and go beyond the free database usage limits. This is done via the claim flow, which consists of three main steps:

概述:声明流程的工作原理

¥Overview: How the Claim Flow Works

当用户想要认领数据库时,你的应用将:

¥When a user wants to claim a database, your app will:

  1. 触发 OAuth2 流程,将用户重定向到 Prisma Auth。此操作是必需的,这样你的应用才有权将数据库传输到用户的工作区。

    ¥Trigger the OAuth2 flow, redirecting the user to Prisma Auth. This is necessary, so your app will have the permissions to transfer the database into the user's workspace.

  2. 用户进行身份验证并选择工作区。

    ¥The user authenticates and selects a workspace.

  3. 你的后端将收到授权码,将其交换为用户访问令牌,并使用你的集成令牌和用户令牌调用 Management API 传输端点。

    ¥Your backend receives an authorization code, exchanges it for a user access token, and calls the Management API transfer endpoint with both your integration token and the user's token.

这确保了传输的安全性,并且只有目标用户才能认领数据库。

¥This ensures the transfer is secure and only the intended user can claim the database.

1. 触发声明流程

¥ Triggering the Claim Flow

当你的用户想要拥有你为他们配置的数据库的所有权时,他们需要将其转移到他们自己的 Prisma Postgres 工作区。这使用户能够完全控制它。

¥When your user wants to take ownership of a database you provisioned for them, they need to transfer it to their own Prisma Postgres workspace. This gives them full control over it.

要启动此过程,请在你的应用中提供一个按钮或链接(例如,"声明数据库" 或 "转移到我的工作区")。点击后,你的后端应该:

¥To initiate this process, provide a button or link in your app (e.g., "Claim Database" or "Transfer to My Workspace"). When clicked, your backend should:

  • 生成安全的 state 值以跟踪会话并防止 CSRF 攻击。

    ¥Generate a secure state value to track the session and prevent CSRF attacks.

  • 使用你的客户端 ID、重定向 URI 和所需范围构建 OAuth2 授权 URL。

    ¥Construct an OAuth2 authorization URL with your client ID, redirect URI, and required scopes.

  • 将用户重定向到此 URL 以开始身份验证流程。

    ¥Redirect the user to this URL to begin the authentication flow.

示例:

¥Example:

const authParams = new URLSearchParams({
client_id: YOUR_CLIENT_ID,
redirect_uri: 'https://your-app.com/auth/callback', // Your callback endpoint
response_type: 'code',
scope: 'workspace:admin', // The scope of the OAuth2 authorization
state: generateState(), // Securely track the session
});
const authUrl = `https://auth.prisma.io/authorize?${authParams.toString()}`;
// Redirect the user to authUrl

2. 用户身份验证

¥ Authenticating the User

系统将提示用户登录(如果尚未进行身份验证)并选择他们想要认领数据库的工作区。成功完成身份验证和选择工作区后,Prisma Auth 将重定向回你的回调端点,并带有 codestate(在某些情况下,还会带有 project_id)。

¥The user will be prompted to log in (if not already authenticated) and select the workspace where they want to claim the database. After successful authentication and workspace selection, Prisma Auth will redirect back to your callback endpoint with a code and state (and, in some cases, a project_id).

3. 完成声明流程

¥ Finishing the Claim Flow

你的后端现在应该:

¥Your backend should now:

  1. 将授权码交换为用户访问令牌:

    ¥Exchange the authorization code for a user access token:

const tokenResponse = await fetch('https://auth.prisma.io/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'authorization_code',
code: code, // The code received from the callback
redirect_uri: 'https://your-app.com/auth/callback', // Must match the redirect_uri used in step 1
client_id: YOUR_CLIENT_ID,
client_secret: YOUR_CLIENT_SECRET,
}).toString(),
});
const tokenData = await tokenResponse.json();
  1. 调用 Management API 传输端点将项目移动到选定的工作区。你需要 project_id 和用户的访问令牌:

    ¥Call the Management API transfer endpoint to move the project to the selected workspace. You will need the project_id and the user's access token:

const transferResponse = await fetch(`https://api.prisma.io/v1/projects/${project_id}/transfer`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${YOUR_INTEGRATION_TOKEN}`,
},
body: JSON.stringify({ recipientAccessToken: tokenData.access_token }),
});

如果转移成功,数据库现在归用户的工作区所有。

¥If the transfer is successful, the database is now owned by the user's workspace.

结论

¥Conclusion

通过遵循本指南,你将学习如何:

¥By following this guide, you have learned how to:

  • 设置为 Prisma Postgres 合作伙伴并获取必要的凭据

    ¥Set up as a Prisma Postgres Partner and obtain the necessary credentials

  • 使用 Management API 为你的用户配置新的数据库

    ¥Provision a new database for your users using the Management API

  • 实现安全的声明流程,允许用户使用 OAuth2 在自己的工作区中声明数据库的所有权。

    ¥Implement a secure claim flow that allows users to claim ownership of a database in their own workspace using OAuth2

此流程使你能够将 Prisma Postgres 配置和传输无缝集成到你自己的产品中,为你的用户提供流畅的入门体验。

¥This flow enables you to integrate Prisma Postgres provisioning and transfer seamlessly into your own product, providing a smooth onboarding experience for your users.

有关更多详细信息,请参阅 create-db 代码库以获取参考实现,或查阅 Prisma 管理 API 文档

¥For further details, see the create-db repo for a reference implementation, or consult the Prisma Management API documentation.


Stay connected with Prisma

Continue your Prisma journey by connecting with our active community. Stay informed, get involved, and collaborate with other developers:

We genuinely value your involvement and look forward to having you as part of our community!