Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Nestjs 巢罐';t解决JWT策略的依赖关系_Nestjs_Typeorm - Fatal编程技术网

Nestjs 巢罐';t解决JWT策略的依赖关系

Nestjs 巢罐';t解决JWT策略的依赖关系,nestjs,typeorm,Nestjs,Typeorm,我是NestJs世界的新手。据我所知,我导入了JWT战略中所需的一切。我不知道哪里出了问题。有人能帮我吗 就我所提到的documentation而言,每当我们想要在模块中使用任何实体时,我们都应该在@module()decorator的imports字段中导入该实体。我做到了 jwt.strategy.ts import { Injectable, UnauthorizedException } from "@nestjs/common"; import { Passport

我是NestJs世界的新手。据我所知,我导入了JWT战略中所需的一切。我不知道哪里出了问题。有人能帮我吗

就我所提到的documentation而言,每当我们想要在模块中使用任何实体时,我们都应该在@module()decorator的imports字段中导入该实体。我做到了

jwt.strategy.ts

import { Injectable, UnauthorizedException } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { Strategy, ExtractJwt } from "passport-jwt";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { UserEntity } from "src/entities/user.entity";
import { AuthPayload } from "src/common/dtos/user.dto";

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
    constructor(
        @InjectRepository(UserEntity)
        private userRepo: Repository<UserEntity>
    ) {
        super({
            jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
            secretOrKey: process.env.SECRETKEY
        });
    }

    async validate(payload: AuthPayload): Promise<UserEntity> {
        const { username } = payload;
        const user = this.userRepo.findOne({ where: { username: username } });
        if(!user) {
            throw new UnauthorizedException();
        }
        return user;
    }
}
import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserEntity } from 'src/entities/user.entity';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { JwtStrategy } from './jwt.strategy';

@Module({
  imports: [
    TypeOrmModule.forFeature([UserEntity]),
    JwtModule.register({
      secret: process.env.SECRETKEY,
    }),
    PassportModule.register({
      defaultStrategy: 'jwt'
    })
  ],
  providers: [AuthService, JwtStrategy],
  controllers: [AuthController],
  exports: [PassportModule, JwtStrategy]
})
export class AuthModule {}
import { Entity, Column, OneToMany, JoinTable, BeforeInsert } from "typeorm";
import { AbstractEntity } from "./abstract-entity.abstract";
import { IsEmail } from "class-validator";
import { Exclude, classToPlain } from "class-transformer";
import * as bcrypt from "bcryptjs";
import { CategoryEntity } from "./category.entity";
import { ArticleEntity } from "./article.entity";

@Entity('User')
export class UserEntity extends AbstractEntity {
    @Column({
        type: "varchar",
        length: 80
    })
    fullName: string;

    @Column({
        type: "varchar",
        unique: true
    })
    @IsEmail()
    email: string;

    @Column({
        type: "varchar",
        unique: true
    })
    username: string;

    @Column({
        type: "varchar"
    })
    @Exclude()
    password: string;

    @Column({
        default: null,
        nullable: true
    })
    avatar: string | null;

    @Column({
        type: "varchar",
        unique: true
    })
    phoneNumber: string;

    @Column({
        type: "boolean",
        default: false
    })
    isAdmin: boolean;

    @Column({
        type: "boolean",
        default: false
    })
    isStaff: boolean;

    @Column({
        type: "boolean",
        default: false
    })
    isEmailVerified: boolean;

    @OneToMany(type => CategoryEntity, category => category.createdBy)
    @JoinTable()
    categories: CategoryEntity[];

    @OneToMany(type => ArticleEntity, article => article.createdBy)
    @JoinTable()
    articles: ArticleEntity[];

    @BeforeInsert()
    async hashPassword() {
        this.password = await bcrypt.hash(this.password, 10);
    }

    async comparePassword(attempt: string): Promise<boolean> {
        return await bcrypt.compare(attempt, this.password);
    }

    toJSON(): any {
        return classToPlain(this);
    }
}
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from "@nestjs/typeorm";
import { APP_FILTER, APP_INTERCEPTOR } from '@nestjs/core';
import { 
  DatabaseConnectionService
 } from "./utils/database-connection.service";
import { AuthModule } from './auth/auth.module';
import { UsersModule } from './users/users.module';
import { ArticlesModule } from './articles/articles.module';
import { HttpExceptionFilter } from './common/exception-filters/http-exception.filter';
import { ResponseInterceptor } from './common/interceptors/response.interceptor';
import { CategoryModule } from './category/category.module';

@Module({
  imports: [
    TypeOrmModule.forRootAsync({
      useClass: DatabaseConnectionService
    }),
    AuthModule,
    UsersModule,
    ArticlesModule,
    CategoryModule,
  ],
  controllers: [AppController],
  providers: [
    // {
    //   provide: APP_INTERCEPTOR,
    //   useClass: ResponseInterceptor
    // },
    {
      provide: APP_FILTER,
      useClass: HttpExceptionFilter
    },
    AppService
  ],
})
export class AppModule {}

import { Injectable } from "@nestjs/common";
import { TypeOrmOptionsFactory, TypeOrmModuleOptions } from "@nestjs/typeorm";
import { truncate } from "fs";

@Injectable()
export class DatabaseConnectionService implements TypeOrmOptionsFactory {
    createTypeOrmOptions(): TypeOrmModuleOptions {
        return {
            type: "mysql",
            host: process.env.HOST,
            port: parseInt(process.env.PORT),
            username: process.env.DB_USERNAME,
            password: process.env.DB_PASSWORD,
            database: process.env.DATABASE, 
            entities: [__dirname + '/**/*.entity{.ts,.js}'],
            synchronize: true,
            dropSchema: true,
            autoLoadEntities: true,
            logger: "simple-console"
        };
    }
}

user.entity.ts

import { Injectable, UnauthorizedException } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { Strategy, ExtractJwt } from "passport-jwt";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { UserEntity } from "src/entities/user.entity";
import { AuthPayload } from "src/common/dtos/user.dto";

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
    constructor(
        @InjectRepository(UserEntity)
        private userRepo: Repository<UserEntity>
    ) {
        super({
            jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
            secretOrKey: process.env.SECRETKEY
        });
    }

    async validate(payload: AuthPayload): Promise<UserEntity> {
        const { username } = payload;
        const user = this.userRepo.findOne({ where: { username: username } });
        if(!user) {
            throw new UnauthorizedException();
        }
        return user;
    }
}
import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserEntity } from 'src/entities/user.entity';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { JwtStrategy } from './jwt.strategy';

@Module({
  imports: [
    TypeOrmModule.forFeature([UserEntity]),
    JwtModule.register({
      secret: process.env.SECRETKEY,
    }),
    PassportModule.register({
      defaultStrategy: 'jwt'
    })
  ],
  providers: [AuthService, JwtStrategy],
  controllers: [AuthController],
  exports: [PassportModule, JwtStrategy]
})
export class AuthModule {}
import { Entity, Column, OneToMany, JoinTable, BeforeInsert } from "typeorm";
import { AbstractEntity } from "./abstract-entity.abstract";
import { IsEmail } from "class-validator";
import { Exclude, classToPlain } from "class-transformer";
import * as bcrypt from "bcryptjs";
import { CategoryEntity } from "./category.entity";
import { ArticleEntity } from "./article.entity";

@Entity('User')
export class UserEntity extends AbstractEntity {
    @Column({
        type: "varchar",
        length: 80
    })
    fullName: string;

    @Column({
        type: "varchar",
        unique: true
    })
    @IsEmail()
    email: string;

    @Column({
        type: "varchar",
        unique: true
    })
    username: string;

    @Column({
        type: "varchar"
    })
    @Exclude()
    password: string;

    @Column({
        default: null,
        nullable: true
    })
    avatar: string | null;

    @Column({
        type: "varchar",
        unique: true
    })
    phoneNumber: string;

    @Column({
        type: "boolean",
        default: false
    })
    isAdmin: boolean;

    @Column({
        type: "boolean",
        default: false
    })
    isStaff: boolean;

    @Column({
        type: "boolean",
        default: false
    })
    isEmailVerified: boolean;

    @OneToMany(type => CategoryEntity, category => category.createdBy)
    @JoinTable()
    categories: CategoryEntity[];

    @OneToMany(type => ArticleEntity, article => article.createdBy)
    @JoinTable()
    articles: ArticleEntity[];

    @BeforeInsert()
    async hashPassword() {
        this.password = await bcrypt.hash(this.password, 10);
    }

    async comparePassword(attempt: string): Promise<boolean> {
        return await bcrypt.compare(attempt, this.password);
    }

    toJSON(): any {
        return classToPlain(this);
    }
}
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from "@nestjs/typeorm";
import { APP_FILTER, APP_INTERCEPTOR } from '@nestjs/core';
import { 
  DatabaseConnectionService
 } from "./utils/database-connection.service";
import { AuthModule } from './auth/auth.module';
import { UsersModule } from './users/users.module';
import { ArticlesModule } from './articles/articles.module';
import { HttpExceptionFilter } from './common/exception-filters/http-exception.filter';
import { ResponseInterceptor } from './common/interceptors/response.interceptor';
import { CategoryModule } from './category/category.module';

@Module({
  imports: [
    TypeOrmModule.forRootAsync({
      useClass: DatabaseConnectionService
    }),
    AuthModule,
    UsersModule,
    ArticlesModule,
    CategoryModule,
  ],
  controllers: [AppController],
  providers: [
    // {
    //   provide: APP_INTERCEPTOR,
    //   useClass: ResponseInterceptor
    // },
    {
      provide: APP_FILTER,
      useClass: HttpExceptionFilter
    },
    AppService
  ],
})
export class AppModule {}

import { Injectable } from "@nestjs/common";
import { TypeOrmOptionsFactory, TypeOrmModuleOptions } from "@nestjs/typeorm";
import { truncate } from "fs";

@Injectable()
export class DatabaseConnectionService implements TypeOrmOptionsFactory {
    createTypeOrmOptions(): TypeOrmModuleOptions {
        return {
            type: "mysql",
            host: process.env.HOST,
            port: parseInt(process.env.PORT),
            username: process.env.DB_USERNAME,
            password: process.env.DB_PASSWORD,
            database: process.env.DATABASE, 
            entities: [__dirname + '/**/*.entity{.ts,.js}'],
            synchronize: true,
            dropSchema: true,
            autoLoadEntities: true,
            logger: "simple-console"
        };
    }
}

数据库连接.service.ts

import { Injectable, UnauthorizedException } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { Strategy, ExtractJwt } from "passport-jwt";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { UserEntity } from "src/entities/user.entity";
import { AuthPayload } from "src/common/dtos/user.dto";

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
    constructor(
        @InjectRepository(UserEntity)
        private userRepo: Repository<UserEntity>
    ) {
        super({
            jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
            secretOrKey: process.env.SECRETKEY
        });
    }

    async validate(payload: AuthPayload): Promise<UserEntity> {
        const { username } = payload;
        const user = this.userRepo.findOne({ where: { username: username } });
        if(!user) {
            throw new UnauthorizedException();
        }
        return user;
    }
}
import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserEntity } from 'src/entities/user.entity';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { JwtStrategy } from './jwt.strategy';

@Module({
  imports: [
    TypeOrmModule.forFeature([UserEntity]),
    JwtModule.register({
      secret: process.env.SECRETKEY,
    }),
    PassportModule.register({
      defaultStrategy: 'jwt'
    })
  ],
  providers: [AuthService, JwtStrategy],
  controllers: [AuthController],
  exports: [PassportModule, JwtStrategy]
})
export class AuthModule {}
import { Entity, Column, OneToMany, JoinTable, BeforeInsert } from "typeorm";
import { AbstractEntity } from "./abstract-entity.abstract";
import { IsEmail } from "class-validator";
import { Exclude, classToPlain } from "class-transformer";
import * as bcrypt from "bcryptjs";
import { CategoryEntity } from "./category.entity";
import { ArticleEntity } from "./article.entity";

@Entity('User')
export class UserEntity extends AbstractEntity {
    @Column({
        type: "varchar",
        length: 80
    })
    fullName: string;

    @Column({
        type: "varchar",
        unique: true
    })
    @IsEmail()
    email: string;

    @Column({
        type: "varchar",
        unique: true
    })
    username: string;

    @Column({
        type: "varchar"
    })
    @Exclude()
    password: string;

    @Column({
        default: null,
        nullable: true
    })
    avatar: string | null;

    @Column({
        type: "varchar",
        unique: true
    })
    phoneNumber: string;

    @Column({
        type: "boolean",
        default: false
    })
    isAdmin: boolean;

    @Column({
        type: "boolean",
        default: false
    })
    isStaff: boolean;

    @Column({
        type: "boolean",
        default: false
    })
    isEmailVerified: boolean;

    @OneToMany(type => CategoryEntity, category => category.createdBy)
    @JoinTable()
    categories: CategoryEntity[];

    @OneToMany(type => ArticleEntity, article => article.createdBy)
    @JoinTable()
    articles: ArticleEntity[];

    @BeforeInsert()
    async hashPassword() {
        this.password = await bcrypt.hash(this.password, 10);
    }

    async comparePassword(attempt: string): Promise<boolean> {
        return await bcrypt.compare(attempt, this.password);
    }

    toJSON(): any {
        return classToPlain(this);
    }
}
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from "@nestjs/typeorm";
import { APP_FILTER, APP_INTERCEPTOR } from '@nestjs/core';
import { 
  DatabaseConnectionService
 } from "./utils/database-connection.service";
import { AuthModule } from './auth/auth.module';
import { UsersModule } from './users/users.module';
import { ArticlesModule } from './articles/articles.module';
import { HttpExceptionFilter } from './common/exception-filters/http-exception.filter';
import { ResponseInterceptor } from './common/interceptors/response.interceptor';
import { CategoryModule } from './category/category.module';

@Module({
  imports: [
    TypeOrmModule.forRootAsync({
      useClass: DatabaseConnectionService
    }),
    AuthModule,
    UsersModule,
    ArticlesModule,
    CategoryModule,
  ],
  controllers: [AppController],
  providers: [
    // {
    //   provide: APP_INTERCEPTOR,
    //   useClass: ResponseInterceptor
    // },
    {
      provide: APP_FILTER,
      useClass: HttpExceptionFilter
    },
    AppService
  ],
})
export class AppModule {}

import { Injectable } from "@nestjs/common";
import { TypeOrmOptionsFactory, TypeOrmModuleOptions } from "@nestjs/typeorm";
import { truncate } from "fs";

@Injectable()
export class DatabaseConnectionService implements TypeOrmOptionsFactory {
    createTypeOrmOptions(): TypeOrmModuleOptions {
        return {
            type: "mysql",
            host: process.env.HOST,
            port: parseInt(process.env.PORT),
            username: process.env.DB_USERNAME,
            password: process.env.DB_PASSWORD,
            database: process.env.DATABASE, 
            entities: [__dirname + '/**/*.entity{.ts,.js}'],
            synchronize: true,
            dropSchema: true,
            autoLoadEntities: true,
            logger: "simple-console"
        };
    }
}

错误如下:
考虑转到活动记录模式。您需要做的只是让您的
AbstractEntity
扩展类型化的
BaseEntity

您可以删除所有TypeForm功能导入,如:

TypeOrmModule.forFeature([UserEntity])
以及存储库的所有依赖项注入,如:

@InjectRepository(UserEntity)
私有userRepo:存储库
只需使用实体类进行查询:

const user=await UserEntity.findOne({where:{username:username}});

根据您的错误,您的
导入
数组中有
JwtStrategy
。如果需要
JwtStrategy
,则应导入
AuthModule
,因为提供程序应仅位于
providers
数组中,而不应位于
imports

您在哪里定义了
TypeOrmModule.forRoot
用户
实体功能应导入到您的typeorm模块根目录中,并导入到app.module.ts中。它以前是有用的。但现在没有了?我将更新app.module.ts。好的,我可以看到您的问题谢谢@yash。我会等你的回答。好的,谢谢你。我会努力实现它。我一定会试试@yash。谢谢你的回答。