Skip to content
Getting Started

用 React 构建一个用户管理应用

本教程演示了如何构建一个基本的用户管理应用。该应用可以进行用户认证和识别,将用户的个人资料信息存储在数据库中,并允许用户登录、更新他们的个人资料信息以及上传头像。该应用使用了:

🌐 This tutorial demonstrates how to build a basic user management app. The app authenticates and identifies the user, stores their profile information in the database, and allows the user to log in, update their profile details, and upload a profile photo. The app uses:

Supabase User Management example

项目设置 #

🌐 Project setup

在你开始构建之前,你需要先设置数据库和 API。你可以通过在 Supabase 中启动一个新项目,然后在数据库中创建一个“架构”来完成这一步。

🌐 Before you start building you need to set up the Database and API. You can do this by starting a new Project in Supabase and then creating a "schema" inside the database.

创建一个项目 #

🌐 Create a project

  1. 在 Supabase 仪表板中创建一个新项目。
  2. 输入你的项目详情。
  3. 等新数据库上线。

设置数据库模式 #

🌐 Set up the database schema

现在设置数据库模式。你可以在 SQL 编辑器中使用“用户管理入门”快速开始,也可以复制粘贴下面的 SQL 并运行。

🌐 Now set up the database schema. You can use the "User Management Starter" quickstart in the SQL Editor, or you can copy/paste the SQL from below and run it.

  1. 在仪表板中转到SQL 编辑器页面。
  2. 在 参考 > 示例 选项卡下点击 用户管理入门。
  3. 点击运行。

获取 API 详情 #

🌐 Get API details

要与数据库表中的数据进行交互,你可以使用封装了自动生成的数据 API 端点的客户端库,并使用来自项目 Connect 对话框的项目 URL 和密钥进行认证。

🌐 To interact with data in database tables, you use the client libraries that wrap the auto-generated Data API endpoints, authenticating using the Project URL and key from the project Connect dialog.

正在构建应用 #

🌐 Building the app

从零开始搭建 React 应用。

🌐 Start building the React app from scratch.

初始化一个 React 应用 #

🌐 Initialize a React app

使用 Vite 初始化一个名为 supabase-react 的应用:

🌐 Use Vite to initialize an app called supabase-react:

npm create vite@latest supabase-react -- --template react
cd supabase-react

安装 supabase-js:

🌐 Install supabase-js:

npm install @supabase/supabase-js

将环境变量保存到 .env.local 文件中,使用你之前复制的项目 URL 和密钥 参考。

🌐 Save the environment variables in a .env.local file, using the Project URL and the key that you copied earlier.

.env
VITE_SUPABASE_URL=
VITE_SUPABASE_PUBLISHABLE_KEY=
View source

在配置好 API 凭证后,创建一个辅助文件来初始化 Supabase 客户端。应用会在浏览器中暴露这些变量,这没问题,因为 Supabase 默认在所有表上启用了 行级安全。

🌐 With the API credentials in place, create a helper file to initialize the Supabase client. The application exposes these variables in the browser, and that's fine as Supabase enables Row Level Security by default on all tables.

创建并编辑 src/supabaseClient.js:

🌐 Create and edit src/supabaseClient.js:

src/supabaseClient.js
/**
* lib/supabaseClient.js
* Helper to initialize the Supabase client.
*/
import { createClient } from '@supabase/supabase-js'
const supabaseUrl = import.meta.env.VITE_SUPABASE_URL
const supabasePublishableKey = import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY
export const supabase = createClient(supabaseUrl, supabasePublishableKey)
View source

应用风格(可选) #

🌐 App styling (optional)

一个可选步骤是更新 CSS 文件 src/index.css,让应用看起来更好。你可以在示例仓库中找到这个文件的完整内容。

🌐 An optional step is to update the CSS file src/index.css to make the app look better. You can find the full contents of this file in the example repository.

设置一个登录组件 #

🌐 Set up a sign-in component

你需要一个 React 组件来管理登录和注册。它使用 Magic Links,所以用户可以通过邮箱登录而无需使用密码。

🌐 You need a React component to manage sign-ins and sign-ups. It uses Magic Links, so users can sign in with their email without using passwords.

创建并编辑 src/Auth.jsx:

🌐 Create and edit src/Auth.jsx:

src/Auth.jsx
import { useState } from 'react'
import { supabase } from './supabaseClient'
export default function Auth() {
const [loading, setLoading] = useState(false)
const [email, setEmail] = useState('')
const handleLogin = async (event) => {
event.preventDefault()
setLoading(true)
const { error } = await supabase.auth.signInWithOtp({ email })
if (error) {
alert(error.error_description || error.message)
} else {
alert('Check your email for the login link!')
}
setLoading(false)
}
return (
<div className="row flex flex-center">
<div className="col-6 form-widget">
<h1 className="header">Supabase + React</h1>
<p className="description">Sign in via magic link with your email below</p>
<form className="form-widget" onSubmit={handleLogin}>
<div>
<input
className="inputField"
type="email"
placeholder="Your email"
value={email}
required={true}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div>
<button className={'button block'} disabled={loading}>
{loading ? <span>Loading</span> : <span>Send magic link</span>}
</button>
</div>
</form>
</div>
</div>
)
}
View source

账户页面 #

🌐 Account page

用户登录后,需要一种方式来编辑他们的个人资料信息并管理他们的账户。

🌐 After a user signs in, they need a way to edit their profile details and manage their accounts.

创建一个名为 src/Account.jsx 的新组件,并添加以下代码:

🌐 Create a new component called src/Account.jsx and add the following code:

src/Account.jsx
import { useState, useEffect } from 'react'
import { supabase } from './supabaseClient'
// ...
export default function Account({ user }) {
const [loading, setLoading] = useState(true)
const [username, setUsername] = useState(null)
const [website, setWebsite] = useState(null)
const [avatar_url, setAvatarUrl] = useState(null)
useEffect(() => {
let ignore = false
async function getProfile() {
setLoading(true)
const { data, error } = await supabase
.from('profiles')
.select(`username, website, avatar_url`)
.eq('id', user.id)
.single()
if (!ignore) {
if (error) {
console.warn(error)
} else if (data) {
setUsername(data.username)
setWebsite(data.website)
setAvatarUrl(data.avatar_url)
}
}
setLoading(false)
}
getProfile()
return () => {
ignore = true
}
}, [user])
async function updateProfile(event, avatarUrl) {
event.preventDefault()
setLoading(true)
const updates = {
id: user.id,
username,
website,
avatar_url: avatarUrl,
updated_at: new Date(),
}
const { error } = await supabase.from('profiles').upsert(updates)
if (error) {
alert(error.message)
} else {
setAvatarUrl(avatarUrl)
}
setLoading(false)
}
return (
<form onSubmit={updateProfile} className="form-widget">
{/* ... */}
<div>
<label htmlFor="email">Email</label>
<input id="email" type="text" value={user.email} disabled />
</div>
<div>
<label htmlFor="username">Name</label>
<input
id="username"
type="text"
required
value={username || ''}
onChange={(e) => setUsername(e.target.value)}
/>
</div>
<div>
<label htmlFor="website">Website</label>
<input
id="website"
type="url"
value={website || ''}
onChange={(e) => setWebsite(e.target.value)}
/>
</div>
<div>
<button className="button block primary" type="submit" disabled={loading}>
{loading ? 'Loading ...' : 'Update'}
</button>
</div>
<div>
<button className="button block" type="button" onClick={() => supabase.auth.signOut()}>
Sign Out
</button>
</div>
</form>
)
}
View source

头像照片 #

🌐 Profile photos

添加一个让用户上传个人资料照片的方式。Supabase 为每个项目配置了 Storage,用于管理照片和视频等大文件。

🌐 Add a way for users to upload a profile photo. Supabase configures every project with Storage for managing large files like photos and videos.

创建一个上传小工具 #

🌐 Create an upload widget

创建 src/Avatar.jsx 并添加以下代码:

🌐 Create src/Avatar.jsx and add the following code:

src/Avatar.jsx
import { useEffect, useState } from 'react'
import { supabase } from './supabaseClient'
export default function Avatar({ url, size, onUpload }) {
const [avatarUrl, setAvatarUrl] = useState(null)
const [uploading, setUploading] = useState(false)
useEffect(() => {
if (url) downloadImage(url)
}, [url])
async function downloadImage(path) {
try {
const { data, error } = await supabase.storage.from('avatars').download(path)
if (error) {
throw error
}
const url = URL.createObjectURL(data)
setAvatarUrl(url)
} catch (error) {
console.log('Error downloading image: ', error.message)
}
}
async function uploadAvatar(event) {
try {
setUploading(true)
if (!event.target.files || event.target.files.length === 0) {
throw new Error('You must select an image to upload.')
}
const file = event.target.files[0]
const fileExt = file.name.split('.').pop()
const fileName = `${Math.random()}.${fileExt}`
const filePath = `${fileName}`
let { error: uploadError } = await supabase.storage.from('avatars').upload(filePath, file)
if (uploadError) {
throw uploadError
}
onUpload(event, filePath)
} catch (error) {
alert(error.message)
} finally {
setUploading(false)
}
}
return (
<div>
{avatarUrl ? (
<img
src={avatarUrl}
alt="Avatar"
className="avatar image"
style={{ height: size, width: size }}
/>
) : (
<div className="avatar no-image" style={{ height: size, width: size }} />
)}
<div style={{ width: size }}>
<label className="button primary block" htmlFor="single">
{uploading ? 'Uploading ...' : 'Upload'}
</label>
<input
style={{
visibility: 'hidden',
position: 'absolute',
}}
type="file"
id="single"
accept="image/*"
onChange={uploadAvatar}
disabled={uploading}
/>
</div>
</div>
)
}
View source

更新账户组件 #

🌐 Update the Account component

创建了 Avatar 组件后,更新 src/Account.jsx 来包含它:

🌐 With the Avatar component created, update src/Account.jsx to include it:

src/Account.jsx
import { useState, useEffect } from 'react'
import { supabase } from './supabaseClient'
import Avatar from './Avatar'
export default function Account({ user }) {
const [loading, setLoading] = useState(true)
const [username, setUsername] = useState(null)
const [website, setWebsite] = useState(null)
const [avatar_url, setAvatarUrl] = useState(null)
useEffect(() => {
let ignore = false
async function getProfile() {
setLoading(true)
const { data, error } = await supabase
.from('profiles')
.select(`username, website, avatar_url`)
.eq('id', user.id)
.single()
if (!ignore) {
if (error) {
console.warn(error)
} else if (data) {
setUsername(data.username)
setWebsite(data.website)
setAvatarUrl(data.avatar_url)
}
}
setLoading(false)
}
getProfile()
return () => {
ignore = true
}
}, [user])
async function updateProfile(event, avatarUrl) {
event.preventDefault()
setLoading(true)
const updates = {
id: user.id,
username,
website,
avatar_url: avatarUrl,
updated_at: new Date(),
}
const { error } = await supabase.from('profiles').upsert(updates)
if (error) {
alert(error.message)
} else {
setAvatarUrl(avatarUrl)
}
setLoading(false)
}
return (
<form onSubmit={updateProfile} className="form-widget">
<Avatar
url={avatar_url}
size={150}
onUpload={(event, url) => {
updateProfile(event, url)
}}
/>
<div>
<label htmlFor="email">Email</label>
<input id="email" type="text" value={user.email} disabled />
</div>
<div>
<label htmlFor="username">Name</label>
<input
id="username"
type="text"
required
value={username || ''}
onChange={(e) => setUsername(e.target.value)}
/>
</div>
<div>
<label htmlFor="website">Website</label>
<input
id="website"
type="url"
value={website || ''}
onChange={(e) => setWebsite(e.target.value)}
/>
</div>
<div>
<button className="button block primary" type="submit" disabled={loading}>
{loading ? 'Loading ...' : 'Update'}
</button>
</div>
<div>
<button className="button block" type="button" onClick={() => supabase.auth.signOut()}>
Sign Out
</button>
</div>
</form>
)
}
View source

触发! #

🌐 Launch!

在所有组件就位后,修改 src/App.jsx 的内容,将新组件和身份验证逻辑加入进去。

🌐 With all the components in place, change the contents of src/App.jsx to include the new components and Auth logic.

Supabase Auth SDK 包含三种不同的函数,用于验证用户对应用的访问权限:

🌐 The Supabase Auth SDK contains three different functions for authenticating user access to applications:

方法总结 #

🌐 Summary of the methods

  • 使用 getClaims 来保护页面和用户数据。它会从存储中读取访问令牌并进行验证。本地通过 WebCrypto API 和缓存的 JWKS 端点进行处理,当项目使用非对称签名密钥(新项目的默认设置)时,或者在使用对称密钥时仅通过调用 getUser 来验证。返回的声明始终来自 JWT 解码,而不是用户查找。当访问令牌快到期时,getClaims 会在验证前刷新会话,这就是服务器渲染会话保持活跃的方式。
  • [getUser](/docs/reference/javascript/auth-getuser) 会向项目的 Auth 实例发起网络请求以获取用户记录,这样可以获得用户的最新信息,但需要进行一次网络请求。
  • getSession 当你需要原始会话(访问令牌、刷新令牌和过期时间)时使用。例如,将访问令牌转发到另一个服务。会话是直接从本地存储加载的,并不会重新向认证服务器验证,因此当存储与客户端共享(如 cookies、请求头)时,嵌入的用户对象不应单独信任。要验证身份,请使用 getClaims 验证访问令牌,或调用 getUser 获取一个新的、服务器确认的用户记录。

总结:使用 getClaims 来验证身份(通常用于保护页面和数据),当你需要从认证服务器获取最新的用户记录时用 getUser,而当你直接需要访问或刷新令牌时用 getSession,但不要依赖它返回的用户对象来做授权决策。

src/App.jsx
function App() {
const [claims, setClaims] = useState(null)
useEffect(() => {
const loadClaims = async () => {
const {
data: { claims },
} = await supabase.auth.getClaims()
setClaims(claims)
}
loadClaims()
const {
data: { subscription },
} = supabase.auth.onAuthStateChange(() => {
loadClaims()
})
return () => subscription.unsubscribe()
}, [])
return (
<div className="container" style={{ padding: '50px 0 100px 0' }}>
{!claims ? <Auth /> : <Account key={claims.sub} claims={claims} />}
</div>
)
}
View source

完成后,在终端窗口运行这个:

🌐 Once that's done, run this in a terminal window:

npm run dev

然后打开浏览器访问 localhost:5173,你应该能看到完成的应用。

🌐 And then open the browser to localhost:5173 and you should see the completed app.

Screenshot of the Supabase React application running in a browser

在这个阶段,你已经有了一个完全可用的应用!

🌐 At this stage you have a fully functional application!