【问题标题】:Accessing information of authenticated user in request scope using express使用 express 访问请求范围内经过身份验证的用户的信息
【发布时间】:2018-10-15 23:45:57
【问题描述】:

我正在使用 Express 和 TypeORM,目前我陷入了以下情况:

在插入或更新记录之前,我总是想将用户名设置为当前记录,以持久保存上次更新此记录的信息。

使用 TypeORM,这可以通过订阅者轻松完成:

@EventSubscriber()
export class Subscriber implements EntitySubscriberInterface {
    beforeUpdate(event: UpdateEvent<any>) {
        const entity = event.entity;
        if(entity instanceof Base) {
            entity.lastUpdatedBy = 'username'; // TODO
        }
    }
}

用户通过身份验证后为人所知:

@Put('/entity')
public updateEntity(@CurrentUser({required: true}) user: User, @Body enity: Entity): Promise<Entity> {
    Log.info('User successfully authenticated: ' + user)
    return this.manager.update(entity);
}

我的问题是:在请求范围内存储和访问用户信息的最简单方法是什么?

到目前为止我发现了什么:

  1. 以下 stackoverflow-post 似乎是相关的,但 解决方案对我来说听起来像是开销 (GLOBAL data per HTTP/Session request?)
  2. 我也可以在 updateEntity 方法中附加用户信息,但我必须一直明确地添加。

还有其他选择吗?

【问题讨论】:

    标签: express typeorm


    【解决方案1】:

    您可以使用SaveOptionsany类型的属性data

    @Put('/entity')
    public updateEntity(@CurrentUser({required: true}) user: User, @Body enity: Entity): Promise<Entity> {
        Log.info('User successfully authenticated: ' + user)
        return this.manager.update(entity, {data: user});
    }
    

    然后,您可以将订阅者中的数据用于:

    event.queryRunner.data
    

    【讨论】:

      【解决方案2】:

      我使用以下 npm 包将用户保存在我的请求范围内:https://www.npmjs.com/package/cls-hooked

      这个包对我不起作用,因为似乎不支持 async/await:continuation-local-storage。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-05-16
        • 2016-01-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-28
        • 1970-01-01
        相关资源
        最近更新 更多