[英]NestJS strategy for excluding fields for different user roles?
Let's say I have a base entity, ShopsEntity
, that has a bunch of fields along with a secret property:假设我有一个基本实体
ShopsEntity
,它有一堆字段和一个秘密属性:
@ObjectType()
class ShopsEntity {
@Field()
name: string;
@Field()
rating: string;
@Field()
secret: string;
}
I don't want the secret property to be serialised unless a user has a certain role defined through Nest Access Control (That module only allows for RoleGuards to be placed on the resolvers themselves, meaning I would need different routes per role).我不希望秘密属性被序列化,除非用户具有通过Nest Access Control定义的某个角色(该模块只允许将 RoleGuards 放置在解析器本身上,这意味着我需要每个角色不同的路由)。
So, following a request to the same endpoint with differing levels of authentication, an Admin would get:因此,在向具有不同身份验证级别的同一端点发出请求后,管理员将获得:
{
"name": "name",
"rating": "rating",
"secret": "secret"
}
and a regular querying user would get:一个普通的查询用户会得到:
{
"name": "name",
"rating": "rating"
}
Is there a declarative way in which I can do property-level security here, or is the best solution having separate DTO's for each level of security?是否有一种声明性的方式可以在这里进行属性级安全,或者最好的解决方案是为每个安全级别提供单独的 DTO?
With class-transformer, you can use the groups
property to expose properties only for certain groups/roles:使用 class-transformer,您可以使用
groups
属性仅公开某些组/角色的属性:
import {Exclude, Expose} from "class-transformer";
@Exclude()
export class User {
@Expose({ groups: ["admin"] })
secret: string;
}
On how to use the ClassSerializerInterceptor
with groups, see the following answer .关于如何将
ClassSerializerInterceptor
与组一起使用,请参阅以下答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.