简体   繁体   中英

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:

@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).

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?

With class-transformer, you can use the groups property to expose properties only for certain groups/roles:

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM