Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 956
stewartmcgown Avatar asked Nov 01 '25 16:11

stewartmcgown


1 Answers

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.

like image 125
Kim Kern Avatar answered Nov 03 '25 06:11

Kim Kern



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!