nestjs / nest

A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript 🚀
https://nestjs.com
MIT License
67.44k stars 7.6k forks source link

AuthService can't resolve dependencies #809

Closed JamesCoonce closed 6 years ago

JamesCoonce commented 6 years ago

I'm trying to add a JWT Authentication to NestJS but I'mhaving issues with the AuthService and it's dependencies

I'm submitting a...


[ ] Regression 
[ ] Bug report
[ ] Feature request
[ x] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

Nest can't resolve dependencies of the AuthService (?, +). Please verify whether [0] argument is available in the current context.


import {
  Module,
  NestModule,
  MiddlewareConsumer,
  RequestMethod,
} from '@nestjs/common';

import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { bodyValidatorMiddleware } from './middlewares/body-validator.middleware';
import { UsersModule } from '../users/users.module';
// Strategies
import { JwtStrategy } from './passport/jwt.strategy';
import { LocalStrategy } from './passport/local.strategy';

import { authenticate } from 'passport';

@Module({
  imports: [UsersModule],
  controllers: [AuthController],
  providers: [AuthService, JwtStrategy, LocalStrategy],
  exports: [AuthService],
})
export class AuthModule {}

import * as jwt from 'jsonwebtoken';
import { Inject, Injectable, UnauthorizedException } from '@nestjs/common';
import { UsersService } from '../users/users.service';
import { JwtPayload } from './interfaces/jwt-payload.interface';
import { Model, PassportLocalModel } from 'mongoose';
import { IUser } from '../users/interfaces/user.interface';
import { InjectModel } from '@nestjs/mongoose';
import { debug } from 'console';
import { RegistrationStatus } from './interfaces/registrationStatus.interface';

@Injectable()
export class AuthService {
    constructor(private readonly usersService: UsersService,
                @InjectModel('User') private readonly userModel: PassportLocalModel) { }

    async register(user: IUser) {
        await this.userModel.register(new this.userModel({username: user.email,
            firstName: user.firstName,
            lastName: user.lastName}), user.password, (err) => {
            let status: RegistrationStatus;
            if (err) {
                debug(err);
                status = { success: false, message: err };
                return status;
            }

            status = { success: false, message: 'user register' };
            debug(status.message);
            return status;
        });
    }

    async createToken(user) {
        const expiresIn = 3600;
        const accessToken = jwt.sign({ id: user.id, email: user.email }, 'ILovePokemon', { expiresIn });
        return {
            expiresIn,
            accessToken,
        };
    }
    async validateUser(payload: JwtPayload): Promise {
        return await this.usersService.findById(payload.id);
    }
}

Expected behavior

nest should be able to see which dependencies are being used for the AuthService

Minimal reproduction of the problem with instructions

https://github.com/JamesCoonce/angular-nest-todo

What is the motivation / use case for changing the behavior?

Environment


Nest version: 5.0.0

For Tooling issues:
- Node version: 9.8
- Platform:  Mac

Others:

kamilmysliwiec commented 6 years ago

You have to export UsersService and model from the UsersModule.

JamesCoonce commented 6 years ago

I was able to figure the UsersService out what how do I export the model?

JamesCoonce commented 6 years ago

I got it working


import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
import { UserSchema} from './schemas/user.schema';

@Module({
    imports: [MongooseModule.forFeature([{ name: 'User', schema: UserSchema }])],
    controllers: [UsersController],
    providers: [UsersService],
    exports: [UsersService, MongooseModule.forFeature([{ name: 'User', schema: UserSchema }])],
})
export class UsersModule {}
kamilmysliwiec commented 6 years ago

The following code shall work fine as well:

exports: [UsersService, getModelToken('User')],

getModelToken() comes from @nestjs/mongoose

lock[bot] commented 5 years ago

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.