mongoose NestJS -避免返回用户密码

baubqpgj  于 2023-11-19  发布在  Go
关注(0)|答案(3)|浏览(145)

我在使用GraphQL和Mongoose(代码优先方法)的项目中遇到了一个小问题。我在用户的解析器中有一个findCurrentUser查询,它返回了关于当前已验证用户的信息,但我不想返回用户的密码,我如何避免这种情况?
用户解析器:

@Query(() => User)
@UseGuards(GqlAuthGuard)
async findCurrentUser(@CurrentUser() user: JwtPayload): Promise<User> {
  return await this.usersService.findCurrent(user.id);
}

字符串
用户服务:

async findCurrent(id: string): Promise<User> {
    try {
      // find the user
      const user = await this.userModel.findOne({ _id: id });

      // if the user does not exists throw an error
      if (!user) {
        throw new BadRequestException('User not found');
      }

      // we should not return the user's password
      // TODO: this is a temporary solution, needs to be improved
      user.password = '';

      return user;
    } catch (error) {
      throw new InternalServerErrorException(error.message);
    }
  }


用户实体:

import { ObjectType, Field, ID } from '@nestjs/graphql';
import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose';
import { Document, Schema as MongooseSchema } from 'mongoose';
import { nanoid } from 'nanoid';

@Schema()
@ObjectType()
export class User {
  @Field(() => ID)
  _id: MongooseSchema.Types.ObjectId;

  @Field(() => String, { nullable: false })
  @Prop({ type: String, required: true, trim: true })
  firstName: string;

  @Field(() => String, { nullable: true })
  @Prop({ type: String, required: false, trim: true })
  lastName?: string;

  @Field(() => String, { nullable: true })
  @Prop({ type: String, required: false, default: nanoid(10) })
  username: string;

  @Field(() => String, { nullable: false })
  @Prop({
    type: String,
    unique: true,
    required: true,
    lowercase: true,
    trim: true
  })
  email: string;

  @Field(() => String, { nullable: false })
  @Prop({ type: String, required: true, trim: true, minlength: 6 })
  password: string;

  @Field(() => Boolean, { defaultValue: true })
  @Prop({ type: Boolean, default: true })
  isActive: boolean;

  @Field(() => Date, { defaultValue: Date.now() })
  @Prop({ type: Date, default: Date.now() })
  createdAt: Date;
}

export type UserDocument = User & Document;

export const UserSchema = SchemaFactory.createForClass(User);


在文档中,NestJS团队提到了“序列化“,但我已经尝试过了,没有工作。我在GraphQL Playground上得到了以下错误:
“message”:“无法为不可为空的字段User._id返回null。”

tgabmvqs

tgabmvqs1#

您应该简单地从password属性中删除@Field装饰器。

// @Field(() => String, { nullable: false })
@Prop({ type: String, required: true, trim: true, minlength: 6 })
password: string;

字符串

vulvrdjw

vulvrdjw2#

您可以通过将select Prop选项设置为false来避免返回密码。

@Prop({ ..., select: false })
password: string;

字符串
如果你不想在除了简单的select(API create/update/login等)之外的操作中返回密码,你可以按照下面的方式更改文档的toJSON转换方法:

//
UserSchema.set('toJSON', {
    transform: (doc, ret, opt) => {
        delete ret.password;
        return ret;
    }
});

bjp0bcyl

bjp0bcyl3#

在前端定义查询时,您可以像下面这样删除密码字段
之前(当你得到密码时)。

const user = gql`
query getUserDetails($email: String!, $name: String!, ...any other thing that you want to send to server[backend] ) {

 getUserDetails(email: $email, password: $password, ...any other thing that you 
 want to send to server[backend] ) {
  id
  name
  email
  password
 }

}
`;

字符串
之后(如果您不希望密码被返回)。

const user = gql`
query getUserDetails($email: String!, $name: String!, ...any other thing that you want to send to server[backend] ) {

 getUserDetails(email: $email, password: $password, ...any other thing that you 
 want to send to server[backend] ) {
  id
  name
  email
 }

}
`;


您可以删除任何不希望从查询返回的内容

相关问题