Files
medical-mall/docs/ops/2026-02-04__db-trigger__fix-handle-new-user-sync.md
2026-02-05 10:11:09 +08:00

57 lines
3.1 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 操作文档:修复 `handle_new_user` 触发器函数
- **日期**: 2026-02-04
- **范围**: 数据库触发器函数 (`public.handle_new_user`)
- **标题**: 修复 `auth.users` -> `public.ak_users` 的自动用户同步逻辑
## 摘要
本操作通过更新 `public.handle_new_user()` 触发器函数的定义,解决了新用户在 Supabase Auth 注册后,无法在核心业务表 `public.ak_users` 中自动创建对应记录的根本问题。
## 动机
经过排查,发现 `on_auth_user_created` 触发器调用的 `handle_new_user()` 函数并未向 `public.ak_users` 表执行任何 `INSERT` 操作,而是错误地将数据写入了 `public.user_roles``auth.users.raw_user_meta_data`。这导致 `auth.users``public.ak_users` 之间的数据完全脱节,使得所有依赖 `ak_users.role` 的权限校验(如 RPC 鉴权)全部失败。
## 影响范围
- **数据库函数**: `public.handle_new_user()`
- **数据库触发器**: `on_auth_user_created` (在 `auth.users` 表上)
- **数据库表**: `public.ak_users` (现在可以被自动写入), `public.user_roles` (保持兼容写入)
- **业务流程**: 新用户注册的数据同步流程。
## 变更清单
- **新增文件**:
- `docs/sql/30_rpc/auth/handle_new_user_v2.sql`: 包含了修正后的 `handle_new_user` 函数的权威 SQL 脚本。
- `docs/ops/2026-02-04__db-trigger__fix-handle-new-user-sync.md`: 本操作文档。
- **修改内容**: `public.handle_new_user()` 函数的定义
- **新增**: 向 `public.ak_users``INSERT` 新用户记录的逻辑,包含 `auth_id`, `email`, `username`, 和 `role`
- **新增**: 使用 `ON CONFLICT` 确保操作的幂等性。
- **保留**: 保留了向 `public.user_roles``auth.users.raw_user_meta_data` 的写入,以兼容现有逻辑。
- **安全**: 函数已遵循 `SECURITY DEFINER``SET search_path = public` 的安全规范。
## 兼容性与风险
- **数据兼容性**: 此变更为向前兼容。它修复了新用户的数据同步问题,不会影响现有的 `ak_users` 记录。
- **风险**: 无明显风险。函数现在会正确地执行其预期的核心任务。
## 回滚方案
如果需要撤销此变更可以从版本控制Git中找回旧的 `handle_new_user()` 函数定义,或者从数据库备份中恢复,然后重新执行 `CREATE OR REPLACE FUNCTION` 即可。
## 验证方式
1. **执行变更**: 在数据库中执行 `docs/sql/30_rpc/auth/handle_new_user_v2.sql` 的内容,以更新函数定义。
2. **注册新用户**: 在 App 中注册一个全新的用户(例如 `final_test@example.com`)。
3. **验证 `ak_users` 表**: 在 SQL Editor 中查询,确认 `ak_users` 表中已自动创建了与新用户 `auth_id` 对应的记录,并且 `role` 已根据邮箱规则(或默认为 `customer`)被正确设置。
```sql
SELECT auth_id, email, username, role FROM public.ak_users WHERE email = 'final_test@example.com';
```
4. **验证一致性**: 再次执行一致性检查 SQL确认新用户的 `consistency_status` 为 `CONSISTENT`。
## 关联文档
- `docs/AGENT_PROJECT_SPEC.md`
- `docs/sql/30_rpc/auth/handle_new_user_v2.sql`