How to read user from request in a Mongoose midddleware hook or a service in NestJS

Viewed 67

Assume a user is logged in and there is a Post document, I want to save the user who created and updated the post.

export interface Post extends Document {
  readonly title: string;
  readonly content: string;
  readonly createdAt?: Date;
  readonly updatedAt?: Date;
  readonly createdBy?: User;
  readonly updatedBy?: User;
}

export const PostSchema = new Schema({
  title: SchemaTypes.String,
  content: SchemaTypes.String,
  createdAt: { type: SchemaTypes.Date, required: false },
  updatedAt: { type: SchemaTypes.Date, required: false },
  createdBy: { type: SchemaTypes.ObjectId, ref: 'User', required: false },
  updatedBy: { type: SchemaTypes.ObjectId, ref: 'User', required: false },
});

But I have no idea how to read the user from the request in a service component or Mongoose document schema.

1 Answers

It really depends on how you authenticate your users, but you should be able to intercept whichever access token, cookies (...) that the frontend uses to authentifies itself. You can intercept it in the controller and get the corresponding user (or userId) which you can then pass to your service.

In case you're using nestjs passport, your example could look like this:

import { Injectable, Request, Body } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}
import { Controller, Bind, Request, Post, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { JwtAuthGuard } from './auth/jwt-auth.guard';

@Controller()
export class PostController {
  @UseGuards(JwtAuthGuard)
  @Put('post')
  addPost(@Request() request, @Body() body) {
    const user = request.user._id;
    // We only need the id to add it to mongo but you could also pass the whole user
    return this.createPost(body, user._id)
  }
}
@Injectable()
class PostService
//...
async createPost(body, userId) {
  this.postModel.create({
    ...body,
    createdBy: userId
  })
}
//...

If you want more information about how to use nestjs passport and implement auth guards, see here nestjs docs

Related