简体   繁体   English

NestJS 为不同用户角色排除字段的策略?

[英]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.

相关问题 Nestjs Roles Decorator:让用户脱离有效负载数据的疯狂行为 - Nestjs Roles Decorator: Crazy behaviour with getting user out of payload data 有没有办法在 NestJS 中使用不同名称的 map 字段? - Is there a way to map fields with different names in NestJS? 针对不同用户角色的不同菜单项 - Different Menu items for different user roles in angular 用于用户角色的不同React Webpack JS捆绑包 - Different React Webpack JS Bundles for User Roles 如何为不同的用户角色指定功能? - How to specify functionalities to different user roles? App(…):路由用户的不同角色时,渲染未返回任何内容 - App(…): Nothing was returned from render, when routing different roles of user 密码类型输入,但显示不同用户角色的一些文本 - password type input but show some of the text for different user roles 使用 mat-table 在不同行中显示用户的多个角色 - Display multiple roles of a user in different rows using mat-table 编程语言以根据用户角色显示不同的菜单项 - Programming language to display different menu item based on user roles 如何使用 Nestjs 测试使用通行证策略实现的 Auth 0 - How to test Auth 0 implemented with passport strategy with Nestjs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM