【问题标题】:How to access authenticated user out of controller context如何在控制器上下文之外访问经过身份验证的用户
【发布时间】:2019-12-21 07:27:51
【问题描述】:

在遵循 Nest.js 身份验证指南 (https://docs.nestjs.com/techniques/authentication) 时,我有一个关于访问已登录用户的问题。我使用 mongoose 作为我的数据库驱动程序,并且我的所有数据都保存到 MongoDB(用户数据也是如此)。我想在数据库中保存或更新的每个文档上都有“createdBy”和“updatedBy”字段。

这可以通过在定义架构时在 schema.pre('save', function() {}) 回调期间添加这些来完成。但我无法访问执行保存操作的当前用户。请求通过 jwt auth 保护后,当前登录的用户保存在请求中。

如何在 schema.pre('save') 回调时获取该用户?

【问题讨论】:

    标签: node.js nestjs


    【解决方案1】:

    你可以创建一个新的用户装饰器来做你需要的事情。

    import { createParamDecorator } from '@nestjs/common';
    
    export const User = createParamDecorator((data, req) => req.user);
    

    然后在你的控制器中你可以像下面的参数一样使用它

    @Get()
      async getAll(@User() user: UserModel): Promise<Client[]> {
        return this.clientService.getAll(user._id);
      }
    

    【讨论】:

    猜你喜欢
    • 2016-03-14
    • 2020-05-01
    • 2016-01-15
    • 1970-01-01
    • 2014-03-26
    • 2013-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多