TypeORM-提取用户时从不从数据库返回密码 [英] TypeORM - never return the password from the database when fetching a user

查看:664
本文介绍了TypeORM-提取用户时从不从数据库返回密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用带有TypeORM的NestJs创建了REST API.基本上这是我的用户实体

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.

也许某些用户深深地嵌套在一个大型SQL查询语句返回的对象中.有什么办法可以隐藏"某些字段吗?调用this.usersRepository.find()时,我会得到一个用户列表,每个用户都有一个id和一个username字段,但没有一个passwordHash字段.这将使事情变得容易,因为我只需要获取signIn流中的哈希字段.

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.

推荐答案

只需将select: false选项添加到列定义中.有了它,除非通过addSelect明确添加,否则将不会选择该列,请参见文档.

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

这篇关于TypeORM-提取用户时从不从数据库返回密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆