认证与权限
JwtAuthGuard
所有需要登录的接口加 @UseGuards(JwtAuthGuard),它会:
- 从
Authorization: Bearer {token}提取 JWT - 验证 token 有效性
- 设置
req.user(用户信息) - 如果请求头有
x-tenant-id,查询tenant_members验证成员关系,设置req.tenant
请求上下文
// req.user — 用户信息(来自 JWT)
{
user_id: string // 用户 ID
email: string // 邮箱
role: string // 系统角色(users 表)
verified: boolean // 邮箱是否验证
}
// req.tenant — 组织信息(来自 x-tenant-id + 数据库验证)
{
id: string // 组织 ID
role: string // 组织内角色(tenant_members 表)
}
两种角色
| 角色 | 来源 | 字段 | 用途 |
|---|---|---|---|
| 系统角色 | users.role | req.user.role | 区分管理员和普通用户 |
| 组织角色 | tenant_members.role | req.tenant.role | 区分组织内权限 |
权限校验示例
检查是否是组织 Owner
private async requireOwner(tenantId: string, userId: string) {
const member = await this.memberService.isMember(tenantId, userId)
if (!member || member.role !== "owner") {
throw new ForbiddenException("Only owner can perform this action")
}
}
// 使用
@Post(":tenant_id/update")
async update(@Param("tenant_id") tenantId: string, @Req() req: CustomRequest, ...) {
await this.requireOwner(tenantId, req.user.user_id)
// ...
}
检查自定义角色
@Post("admin-action")
async adminAction(@Req() req: CustomRequest, @Res() res: Response) {
const tenantRole = req.tenant?.role
if (tenantRole !== 'admin' && tenantRole !== 'owner') {
throw new ForbiddenException("Requires admin or owner role")
}
// ...
}
检查系统管理员
if (req.user.role !== 'owner') {
throw new ForbiddenException("Requires system admin")
}
不需要登录的接口
不加 @UseGuards(JwtAuthGuard) 即可:
@Controller({ version: "1", path: "public" })
export class PublicController {
@Get("health")
health() {
return { status: "ok" }
}
}