Skip to content
Getting Started

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

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

🌐 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.

Project URL
Publishable key

正在构建应用 #

🌐 Building the app

从零开始构建 Angular 应用吧。

🌐 Start with building the Angular app from scratch.

初始化一个 Angular 应用 #

🌐 Initialize an Angular app

使用 Angular CLI 初始化一个名为 supabase-angular 的应用,并设置一些你可以根据需要更改的默认值:

🌐 Use the Angular CLI to initialize an app called supabase-angular setting some defaults that you can change to suit your needs:

1
npx ng new supabase-angular --routing false --style css --standalone false --ssr false
2
cd supabase-angular

安装 supabase-js:

🌐 Install supabase-js:

1
npm install @supabase/supabase-js

创建一个 src/environments 目录,并将你之前复制的 API URL 和密钥作为环境变量保存到一个新的 src/environments/environment.ts 文件中。

🌐 Create a src/environments directory and save API URL and key that you copied earlier as environment variables in a new src/environments/environment.ts file.

这个应用会在浏览器中暴露这些变量,这没问题,因为 Supabase 默认在所有表上启用了行级安全

🌐 The application exposes these variables in the browser, and that's fine as Supabase enables Row Level Security by default on all tables.

src/environments/environment.ts
1
export const environment = {
2
production: false,
3
supabaseUrl: 'YOUR_SUPABASE_URL',
4
supabasePublishableKey: 'YOUR_SUPABASE_PUBLISHABLE_KEY',
5
}
View source

在配置好 API 凭证后,使用 ng g s supabase 创建一个 SupabaseService,然后添加以下代码来初始化 Supabase 客户端,并实现与 Supabase API 交互的功能。

🌐 With the API credentials in place, create a SupabaseService with ng g s supabase and add the following code to initialize the Supabase client and implement functions to communicate with the Supabase API.

src/app/supabase.service.ts
1
import { Injectable } from '@angular/core'
2
import { AuthChangeEvent, createClient, Session, SupabaseClient, User } from '@supabase/supabase-js'
3
import { environment } from '../environments/environment'
4
5
export interface Profile {
6
id?: string
7
username: string
8
website: string
9
avatar_url: string
10
}
11
12
@Injectable({
13
providedIn: 'root',
14
})
15
export class SupabaseService {
16
private supabase: SupabaseClient
17
18
constructor() {
19
this.supabase = createClient(environment.supabaseUrl, environment.supabasePublishableKey)
20
}
21
22
async getUser(): Promise<User | null> {
23
const { data, error } = await this.supabase.auth.getUser()
24
if (error) {
25
return null
26
}
27
return data.user
28
}
29
30
profile(user: User) {
31
return this.supabase
32
.from('profiles')
33
.select(`username, website, avatar_url`)
34
.eq('id', user.id)
35
.single()
36
}
37
38
authChanges(callback: (event: AuthChangeEvent, session: Session | null) => void) {
39
return this.supabase.auth.onAuthStateChange(callback)
40
}
41
42
signIn(email: string) {
43
return this.supabase.auth.signInWithOtp({ email })
44
}
45
46
signOut() {
47
return this.supabase.auth.signOut()
48
}
49
50
updateProfile(profile: Profile) {
51
const update = {
52
...profile,
53
updated_at: new Date(),
54
}
55
56
return this.supabase.from('profiles').upsert(update)
57
}
58
59
downLoadImage(path: string) {
60
return this.supabase.storage.from('avatars').download(path)
61
}
62
63
uploadAvatar(filePath: string, file: File) {
64
return this.supabase.storage.from('avatars').upload(filePath, file)
65
}
66
}
View source

可选地,更新 src/styles.css 来美化应用。你可以在示例仓库中找到该文件的完整内容。

🌐 Optionally, update src/styles.css to style the app. You can find the full contents of this file in the example repository.

设置一个登录组件 #

🌐 Set up a login component

你需要一个 Angular 组件来管理登录和注册。这个组件使用 Magic Links,所以用户可以使用邮箱登录而不需要密码。

🌐 You need an Angular component to manage logins and sign ups. The component uses Magic Links, so users can sign in with their email without using passwords.

使用 ng g c auth Angular CLI 命令创建一个 AuthComponent,然后添加以下代码。

🌐 Create an AuthComponent with the ng g c auth Angular CLI command and add the following code.

1
import { Component } from '@angular/core'
2
import { FormBuilder, FormGroup } from '@angular/forms'
3
import { SupabaseService } from '../supabase.service'
4
5
@Component({
6
selector: 'app-auth',
7
templateUrl: './auth.component.html',
8
styleUrls: ['./auth.component.css'],
9
standalone: false,
10
})
11
export class AuthComponent {
12
loading = false
13
signInForm: FormGroup
14
15
constructor(
16
private readonly supabase: SupabaseService,
17
private readonly formBuilder: FormBuilder
18
) {
19
this.signInForm = this.formBuilder.group({
20
email: '',
21
})
22
}
23
24
async onSubmit(): Promise<void> {
25
try {
26
this.loading = true
27
const email = this.signInForm.value.email as string
28
const { error } = await this.supabase.signIn(email)
29
if (error) throw error
30
alert('Check your email for the login link!')
31
} catch (error) {
32
if (error instanceof Error) {
33
alert(error.message)
34
}
35
} finally {
36
this.signInForm.reset()
37
this.loading = false
38
}
39
}
40
}
View source

账户页面 #

🌐 Account page

用户在登录后还需要一种方式来编辑他们的个人资料信息并管理他们的账户。使用 ng g c account Angular CLI 命令创建一个 AccountComponent,并添加以下代码。

🌐 Users also need a way to edit their profile details and manage their accounts after signing in. Create an AccountComponent with the ng g c account Angular CLI command and add the following code.

1
import { Component, Input, OnInit } from '@angular/core'
2
import { FormBuilder, FormGroup } from '@angular/forms'
3
import { User } from '@supabase/supabase-js'
4
import { Profile, SupabaseService } from '../supabase.service'
5
6
@Component({
7
selector: 'app-account',
8
templateUrl: './account.component.html',
9
styleUrls: ['./account.component.css'],
10
standalone: false,
11
})
12
export class AccountComponent implements OnInit {
13
loading = false
14
profile!: Profile
15
updateProfileForm!: FormGroup
16
17
18
// ...
19
20
21
@Input()
22
user!: User
23
24
constructor(
25
private readonly supabase: SupabaseService,
26
private formBuilder: FormBuilder
27
) {
28
this.updateProfileForm = this.formBuilder.group({
29
username: '',
30
website: '',
31
avatar_url: '',
32
})
33
}
34
35
async ngOnInit(): Promise<void> {
36
await this.getProfile()
37
38
const { username, website, avatar_url } = this.profile
39
this.updateProfileForm.patchValue({
40
username,
41
website,
42
avatar_url,
43
})
44
}
45
46
async getProfile() {
47
try {
48
this.loading = true
49
const { data: profile, error, status } = await this.supabase.profile(this.user)
50
51
if (error && status !== 406) {
52
throw error
53
}
54
55
if (profile) {
56
this.profile = profile
57
}
58
} catch (error) {
59
if (error instanceof Error) {
60
alert(error.message)
61
}
62
} finally {
63
this.loading = false
64
}
65
}
66
67
async updateProfile(): Promise<void> {
68
try {
69
this.loading = true
70
71
const username = this.updateProfileForm.value.username as string
72
const website = this.updateProfileForm.value.website as string
73
const avatar_url = this.updateProfileForm.value.avatar_url as string
74
75
const { error } = await this.supabase.updateProfile({
76
id: this.user.id,
77
username,
78
website,
79
avatar_url,
80
})
81
if (error) throw error
82
} catch (error) {
83
if (error instanceof Error) {
84
alert(error.message)
85
}
86
} finally {
87
this.loading = false
88
}
89
}
90
91
async signOut() {
92
await this.supabase.signOut()
93
}
94
}
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

使用 ng g c avatar Angular CLI 命令创建一个 AvatarComponent,然后添加以下代码。

🌐 Create an AvatarComponent with the ng g c avatar Angular CLI command and add the following code.

1
import { Component, EventEmitter, Input, Output } from '@angular/core'
2
import { SafeResourceUrl, DomSanitizer } from '@angular/platform-browser'
3
import { SupabaseService } from '../supabase.service'
4
5
@Component({
6
selector: 'app-avatar',
7
templateUrl: './avatar.component.html',
8
styleUrls: ['./avatar.component.css'],
9
standalone: false,
10
})
11
export class AvatarComponent {
12
_avatarUrl: SafeResourceUrl | undefined
13
uploading = false
14
15
@Input()
16
set avatarUrl(url: string | null) {
17
if (url) {
18
this.downloadImage(url)
19
}
20
}
21
22
@Output() upload = new EventEmitter<string>()
23
24
constructor(
25
private readonly supabase: SupabaseService,
26
private readonly dom: DomSanitizer
27
) {}
28
29
async downloadImage(path: string) {
30
try {
31
const { data } = await this.supabase.downLoadImage(path)
32
if (data instanceof Blob) {
33
this._avatarUrl = this.dom.bypassSecurityTrustResourceUrl(URL.createObjectURL(data))
34
}
35
} catch (error) {
36
if (error instanceof Error) {
37
console.error('Error downloading image: ', error.message)
38
}
39
}
40
}
41
42
async uploadAvatar(event: any) {
43
try {
44
this.uploading = true
45
if (!event.target.files || event.target.files.length === 0) {
46
throw new Error('You must select an image to upload.')
47
}
48
49
const file = event.target.files[0]
50
const fileExt = file.name.split('.').pop()
51
const filePath = `${Math.random()}.${fileExt}`
52
53
await this.supabase.uploadAvatar(filePath, file)
54
this.upload.emit(filePath)
55
} catch (error) {
56
if (error instanceof Error) {
57
alert(error.message)
58
}
59
} finally {
60
this.uploading = false
61
}
62
}
63
}
View source

更新账户组件 #

🌐 Update the Account component

创建了 Avatar 组件后,更新 AccountComponent 来包含它:

🌐 With the Avatar component created, update AccountComponent to include it:

1
import { Component, Input, OnInit } from '@angular/core'
2
import { FormBuilder, FormGroup } from '@angular/forms'
3
import { User } from '@supabase/supabase-js'
4
import { Profile, SupabaseService } from '../supabase.service'
5
6
@Component({
7
selector: 'app-account',
8
templateUrl: './account.component.html',
9
styleUrls: ['./account.component.css'],
10
standalone: false,
11
})
12
export class AccountComponent implements OnInit {
13
loading = false
14
profile!: Profile
15
updateProfileForm!: FormGroup
16
17
get avatarUrl() {
18
return this.updateProfileForm.value.avatar_url as string
19
}
20
21
async updateAvatar(event: string): Promise<void> {
22
this.updateProfileForm.patchValue({
23
avatar_url: event,
24
})
25
await this.updateProfile()
26
}
27
28
@Input()
29
user!: User
30
31
constructor(
32
private readonly supabase: SupabaseService,
33
private formBuilder: FormBuilder
34
) {
35
this.updateProfileForm = this.formBuilder.group({
36
username: '',
37
website: '',
38
avatar_url: '',
39
})
40
}
41
42
async ngOnInit(): Promise<void> {
43
await this.getProfile()
44
45
const { username, website, avatar_url } = this.profile
46
this.updateProfileForm.patchValue({
47
username,
48
website,
49
avatar_url,
50
})
51
}
52
53
async getProfile() {
54
try {
55
this.loading = true
56
const { data: profile, error, status } = await this.supabase.profile(this.user)
57
58
if (error && status !== 406) {
59
throw error
60
}
61
62
if (profile) {
63
this.profile = profile
64
}
65
} catch (error) {
66
if (error instanceof Error) {
67
alert(error.message)
68
}
69
} finally {
70
this.loading = false
71
}
72
}
73
74
async updateProfile(): Promise<void> {
75
try {
76
this.loading = true
77
78
const username = this.updateProfileForm.value.username as string
79
const website = this.updateProfileForm.value.website as string
80
const avatar_url = this.updateProfileForm.value.avatar_url as string
81
82
const { error } = await this.supabase.updateProfile({
83
id: this.user.id,
84
username,
85
website,
86
avatar_url,
87
})
88
if (error) throw error
89
} catch (error) {
90
if (error instanceof Error) {
91
alert(error.message)
92
}
93
} finally {
94
this.loading = false
95
}
96
}
97
98
async signOut() {
99
await this.supabase.signOut()
100
}
101
}
View source

你还需要把 app.module.ts 改成包含 @angular/forms 包里的 ReactiveFormsModule

🌐 You also need to change app.module.ts to include the ReactiveFormsModule from the @angular/forms package.

src/app/app.module.ts
1
import { NgModule } from '@angular/core'
2
import { BrowserModule } from '@angular/platform-browser'
3
import { ReactiveFormsModule } from '@angular/forms'
4
5
import { AppComponent } from './app.component'
6
import { AuthComponent } from './auth/auth.component'
7
import { AccountComponent } from './account/account.component'
8
import { AvatarComponent } from './avatar/avatar.component'
9
10
@NgModule({
11
declarations: [AppComponent, AuthComponent, AccountComponent, AvatarComponent],
12
imports: [BrowserModule, ReactiveFormsModule],
13
providers: [],
14
bootstrap: [AppComponent],
15
})
16
export class AppModule {}
View source

触发! #

🌐 Launch!

在所有组件就位后,修改 AppComponent 的内容以包含新的组件和认证逻辑:

🌐 With all the components in place, change the contents of AppComponent 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,而不是通过用户查询获得。
  • [getUser](/docs/reference/javascript/auth-getuser) 会向项目的 Auth 实例发起网络请求以获取用户记录,这样可以获得用户的最新信息,但需要进行一次网络请求。
  • getSession 当你需要原始会话(访问令牌、刷新令牌和过期时间)时使用。例如,将访问令牌转发到另一个服务。会话是直接从本地存储加载的,并不会重新向认证服务器验证,因此当存储与客户端共享(如 cookies、请求头)时,嵌入的用户对象不应单独信任。要验证身份,请使用 getClaims 验证访问令牌,或调用 getUser 获取一个新的、服务器确认的用户记录。

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

1
import { Component, OnInit } from '@angular/core'
2
import { User } from '@supabase/supabase-js'
3
import { SupabaseService } from './supabase.service'
4
5
@Component({
6
selector: 'app-root',
7
templateUrl: './app.component.html',
8
styleUrls: ['./app.component.css'],
9
standalone: false,
10
})
11
export class AppComponent implements OnInit {
12
constructor(private readonly supabase: SupabaseService) {}
13
14
title = 'angular-user-management'
15
user: User | null = null
16
17
async ngOnInit() {
18
this.user = await this.supabase.getUser()
19
this.supabase.authChanges(async () => {
20
this.user = await this.supabase.getUser()
21
})
22
}
23
}
View source

现在在终端中运行这个应用吧:

🌐 Now run the application in a terminal:

1
npm run start

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

🌐 Open the browser to localhost:4200 and you should see the completed app.

Screenshot of the Supabase Angular application running in a browser

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

🌐 At this stage you have a fully functional application!