I created a REST API using NestJs with TypeORM. Basically this is my user entity
@Entity('User')
export class User extends BaseEntity {
@PrimaryGeneratedColumn()
public id: number;
@Column({ unique: true })
public username: string;
public passwordHash: string;
}
When fetching users from the database the sensitive password information get returned too. But I only need the password field for the sign in process. So when calling the service for signing in I compare the password hash from the database user with the provided password from the client. I would never want to return the password information back to the client.
As you can image fetching users from the database happens quite often, you would have to delete the password information from the user object quite often.
Let's assume you have a group entity and have a relation between them. When fetching users related to a group you would also have to take care for the sensitive data in the groups domain.
And maybe some users are deeply nested within an object returned by a big SQL query statement. Is there a way I can "hide" some fields? When calling this.usersRepository.find()
I would get a list of users and each user would have an id
and a username
field but not a passwordHash
field. This would make things easier because I only need to fetch the hash field within my signIn
flow.
Just add the select: false
option to the column definition. With it, the column won't be selected unless explicitly added via addSelect
, see the docs.
@Entity()
export class User {
@Column({select: false})
password: string;
}
You can use @Exclude, like:
@Entity('User')
export class User extends BaseEntity {
@PrimaryGeneratedColumn()
public id: number;
@Column({ unique: true })
public username: string;
@Exclude()
@Column()
password: string;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With