TypeORM - never return the password from the database when fetching a user

旧街凉风 提交于 2020-01-30 08:18:08

问题


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.


回答1:


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;
}


来源:https://stackoverflow.com/questions/59696814/typeorm-never-return-the-password-from-the-database-when-fetching-a-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!