Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 637
Question3r Avatar asked Jan 11 '20 17:01

Question3r


2 Answers

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;
}
like image 110
Kim Kern Avatar answered Oct 06 '22 00:10

Kim Kern


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;
}
like image 42
Renato Ferreira Ordonho Avatar answered Oct 06 '22 02:10

Renato Ferreira Ordonho