@nestjs/jwt#JwtModule TypeScript Examples

The following examples show how to use @nestjs/jwt#JwtModule. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: auth.module.ts    From nestjs-rest-sample with GNU General Public License v3.0 7 votes vote down vote up
@Module({
  imports: [
    ConfigModule.forFeature(jwtConfig),
    UserModule,
    PassportModule.register({ defaultStrategy: 'jwt' }),
    JwtModule.registerAsync({
      imports: [ConfigModule.forFeature(jwtConfig)],
      useFactory: (config: ConfigType<typeof jwtConfig>) => {
        return {
          secret: config.secretKey,
          signOptions: { expiresIn: config.expiresIn },
        } as JwtModuleOptions;
      },
      inject: [jwtConfig.KEY],
    }),
  ],
  providers: [AuthService, LocalStrategy, JwtStrategy],
  exports: [AuthService],
  controllers: [AuthController],
})
export class AuthModule {}
Example #2
Source File: auth.module.ts    From NestJs-youtube with MIT License 6 votes vote down vote up
@Module({
  providers: [AuthService, LocalStrategy, JwtStrategy],
  imports: [
    UserModule,
    PassportModule.register({ defaultStrategy: 'jwt' }),
    JwtModule.register({
      secret: jwtConstants.secret,
      signOptions: { expiresIn: '1d' },
    }),
  ],
  exports: [AuthService],
})
export class AuthModule {}
Example #3
Source File: auth.service.spec.ts    From knests with MIT License 6 votes vote down vote up
describe('AuthService', () => {
  let service: AuthService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [AuthService],
      imports: [
        KnexModule.registerAsync({
          useClass: KnexConfig,
        }),
        JwtModule.register({
          secret: jwtConstants.secret,
          signOptions: { expiresIn: "60s" },
        }),
        UsersModule],
    }).compile();

    service = module.get<AuthService>(AuthService);
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });
});
Example #4
Source File: auth.resolver.spec.ts    From knests with MIT License 6 votes vote down vote up
describe("AuthResolver", () => {
  let resolver: AuthResolver;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [AuthResolver],
      imports: [
        KnexModule.registerAsync({
          useClass: KnexConfig,
        }),
        JwtModule.register({
          secret: jwtConstants.secret,
          signOptions: { expiresIn: "60s" },
        }),
        AuthModule,
        UsersModule,
      ],
    }).compile();

    resolver = module.get<AuthResolver>(AuthResolver);
  });

  it("should be defined", () => {
    expect(resolver).toBeDefined();
  });
});
Example #5
Source File: auth.module.ts    From knests with MIT License 6 votes vote down vote up
@Module({
  imports: [
    UsersModule,
    PassportModule,
    JwtModule.register({
      secret: jwtConstants.secret,
      signOptions: { expiresIn: "60s" },
    }),
  ],
  providers: [AuthService, LocalStrategy, AuthResolver],
  exports: [AuthService],
})
export class AuthModule {}
Example #6
Source File: auth.module.ts    From pknote-backend with GNU General Public License v3.0 6 votes vote down vote up
@Module({
  imports: [
    PassportModule.register({ defaultStrategy: 'jwt' }),
    JwtModule.register({
      secret: process.env.JWT_SECRET || jwtConfig.secret,
      signOptions: {
        expiresIn: jwtConfig.expiresIn,
      },
    }),
    TypeOrmModule.forFeature([UserRepository]),
  ],
  controllers: [AuthController],
  providers: [AuthService, SmsService, JwtStragegy, RedisClientService],
  exports: [JwtStragegy, PassportModule],
})
export class AuthModule {}
Example #7
Source File: auth.module.ts    From nestjs-angular-starter with MIT License 6 votes vote down vote up
/**
 * Responsible of authenticating the user requests using JWT authentication
 * and Passport. It exposes the AuthService which allows managing user authentication,
 * and the UserAuthGuard which allows authenticating each user request.
 */
@Module({
  imports: [
    PassportModule,
    JwtModule.register({
      secret: config.JWT.SECRET,
      signOptions: config.JWT.OPTIONS,
    }),
  ],
  providers: [AuthService, JwtStrategy],
  exports: [AuthService],
  controllers: [AuthController],
})
export class AuthModule {}
Example #8
Source File: login.module.ts    From office-hours with GNU General Public License v3.0 6 votes vote down vote up
@Module({
  imports: [
    JwtModule.registerAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: async (configService: ConfigService) => ({
        secret: configService.get('JWT_SECRET'),
      }),
    }),
  ],
  controllers: [LoginController],
  providers: [JwtStrategy, LoginCourseService],
})
export class LoginModule {}
Example #9
Source File: auth.module.ts    From nestjs-starter with MIT License 6 votes vote down vote up
@Module({
  imports: [
    UsersModule,
    PassportModule.registerAsync({
      useFactory: async (configService: ConfigService) => configService.get<IAuthModuleOptions>(CONFIG_SERVER_PASSPORT),
      inject: [ConfigService],
    }),
    JwtModule.registerAsync({
      useFactory: async (configService: ConfigService) => configService.get(CONFIG_SERVER_JWT),
      inject: [ConfigService],
    }),
  ],
  providers: [AuthService, LocalStrategy, JwtStrategy],
  exports: [AuthService],
})
export class AuthModule {}
Example #10
Source File: AuthModule.ts    From typescript-clean-architecture with MIT License 6 votes vote down vote up
@Module({
  controllers: [
    AuthController
  ],
  imports: [
    PassportModule,
    JwtModule.register({
      secret: ApiServerConfig.ACCESS_TOKEN_SECRET,
      signOptions: {expiresIn: `${ApiServerConfig.ACCESS_TOKEN_TTL_IN_MINUTES}m`},
    }),
    UserModule,
  ],
  providers: [
    HttpAuthService,
    HttpLocalStrategy,
    HttpJwtStrategy
  ],
})
export class AuthModule {}
Example #11
Source File: auth.module.ts    From MyAPI with MIT License 6 votes vote down vote up
@Module({
  imports: [
    UserModule,
    RoleModule,
    passportModule,
    JwtModule.registerAsync({
      useFactory: () => ({
        // TODO: LOAD THIS INFO FROM A CLOUD SERVICE FOR SECRETS MANAGEMENT
        secret: AUTH_SECRET_TOKEN,
        signOptions: AUTH_JWT_OPTIONS
      })
    }),
  ],
  providers: [AuthService, LocalStrategy, JwtStrategy, RolesGuard],
  exports: [AuthService, passportModule]
})
export class AuthModule {}
Example #12
Source File: auth.module.ts    From nestjs-starter-rest-api with MIT License 6 votes vote down vote up
@Module({
  imports: [
    SharedModule,
    PassportModule.register({ defaultStrategy: STRATEGY_JWT_AUTH }),
    JwtModule.registerAsync({
      imports: [SharedModule],
      useFactory: async (configService: ConfigService) => ({
        publicKey: configService.get<string>('jwt.publicKey'),
        privateKey: configService.get<string>('jwt.privateKey'),
        signOptions: {
          algorithm: 'RS256',
        },
      }),
      inject: [ConfigService],
    }),
    UserModule,
  ],
  controllers: [AuthController],
  providers: [AuthService, LocalStrategy, JwtAuthStrategy, JwtRefreshStrategy],
})
export class AuthModule {}
Example #13
Source File: auth.module.ts    From pandaid with MIT License 6 votes vote down vote up
@Module({
  imports: [
    UsersModule,
    PassportModule,
    JwtModule.register({
      secret: 'secret',
      signOptions: { expiresIn: '60m' }
    })
  ],
  controllers: [AuthController],
  providers: [AuthService, LocalStrategy, JwtStrategy]
})
export class AuthModule {}
Example #14
Source File: auth.module.ts    From svvs with MIT License 6 votes vote down vote up
/**
 * Auth module contain logic of authentication
 */
@Module({
  imports: [
    UsersModule,
    PassportModule.register({
      defaultStrategy: 'jwt',
    }),
    JwtModule.register({
      privateKey: environment.jwt.secret,
      signOptions: {
        expiresIn: environment.jwt.expiresIn,
      },
    }),
  ],
  providers: [AuthService, PasswordService, JwtStrategy, AuthResolver],
  exports: [AuthService, PassportModule],
})
export class AuthModule {
}
Example #15
Source File: auth.module.ts    From 42_checkIn with GNU General Public License v3.0 6 votes vote down vote up
@Module({
  imports: [
    HttpModule,
    PassportModule,
    JwtModule.registerAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => ({
        secret: configService.get('jwt.secret'),
        signOptions: { expiresIn: '7d' },
      }),
    }),
    LoggerModule,
  ],
  providers: [AuthService, JwtStrategy, FtStrategy],
  exports: [AuthService],
})
export class AuthModule {}
Example #16
Source File: auth.module.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
@Module({
  imports: [
    UsersModule,
    PassportModule,
    JwtModule.register({
      secret: authConstants.jwt.secret,
    }),
  ],
  providers: [
    AuthService,
    LocalStrategy,
    JwtAccessStrategy,
    JwtRefreshStrategy,
    AuthRepository,
  ],
  controllers: [AuthController],
  exports: [AuthService],
})
export default class AuthModule {}
Example #17
Source File: auth.module.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
@Module({
  imports: [
    UsersModule,
    PassportModule,
    JwtModule.register({
      secret: authConstants.jwt.secret,
    }),
  ],
  providers: [
    AuthService,
    LocalStrategy,
    JwtAccessStrategy,
    JwtRefreshStrategy,
    AuthRepository,
    JwtWSAccessStrategy,
  ],
  controllers: [AuthController],
  exports: [AuthService],
})
export default class AuthModule {}
Example #18
Source File: mailer.module.ts    From uniauth-backend with MIT License 6 votes vote down vote up
@Module({
  imports: [
    MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]),
    JwtModule.register({
      secret: confirmEmailTokenConstants.secret,
      signOptions: { expiresIn: confirmEmailTokenConstants.expiresIn },
    }),
    UserModule,
    WinstonModule.forRoot(logger.console()),
  ],
  controllers: [MailerController],
  providers: [MailerService],
  exports: [MailerService],
})
export class MailerModule {}
Example #19
Source File: auth.module.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
@Module({
  imports: [
    UsersModule,
    PassportModule,
    JwtModule.register({
      secret: authConstants.jwt.secret,
    }),
  ],
  providers: [
    AuthService,
    LocalStrategy,
    JwtAccessStrategy,
    JwtRefreshStrategy,
    JwtWSAccessStrategy,
    AuthRepository,
  ],
  controllers: [AuthController],
  exports: [AuthService],
})
export default class AuthModule {}
Example #20
Source File: auth.module.ts    From uniauth-backend with MIT License 6 votes vote down vote up
@Module({
  imports: [
    UserModule,
    PassportModule,
    JwtModule.register({
      secret: newJWTConstants.secret,
      signOptions: { expiresIn: newJWTConstants.expiresIn },
    }),
    WinstonModule.forRoot(logger.console()),
  ],
  controllers: [AuthController],
  providers: [AuthService, LocalStrategy, JwtStrategy],
  exports: [AuthService],
})
export class AuthModule {}
Example #21
Source File: services.module.ts    From barista with Apache License 2.0 6 votes vote down vote up
@Module({
  imports: [
    forwardRef(() => AppOrmModule),
    AppQueueModule,
    PassportModule,
    CqrsModule,
    JwtModule.register({
      secret: jwtConstants.secret,
      signOptions: { expiresIn: '28800s' },
    }),
  ],
  exports: services,
  providers: [...services, ...CommandHandlers],
  controllers: [],
})
export class ServicesModule {}
Example #22
Source File: user.service.spec.ts    From barista with Apache License 2.0 6 votes vote down vote up
describe('UserService', () => {
  let service: UserService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      imports: [
        PassportModule,
        JwtModule.register({
          secret: jwtConstants.secret,
          signOptions: { expiresIn: '3600s' },
        }),
      ],
      providers: [
        LocalStrategy,
        JwtStrategy,
        UserService,
        LdapService,
        { provide: getRepositoryToken(User), useClass: mockRepository },
      ],
    }).compile();

    service = module.get<UserService>(UserService);
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });
});
Example #23
Source File: account.module.ts    From uniauth-backend with MIT License 6 votes vote down vote up
@Module({
  imports: [
    JwtModule.register({
      secret: accessTokenJwtConstants.secret,
      signOptions: { expiresIn: accessTokenJwtConstants.expiresIn },
    }),
    ApplicationModule,
    UserModule,
    AuthModule,
    MailerModule,
  ],
  controllers: [AccountController],
  providers: [AccountService],
})
export class AccountModule {}
Example #24
Source File: auth.module.ts    From whispr with MIT License 6 votes vote down vote up
@Module({
  imports: [
    PassportModule,
    ConfigModule,
    JwtModule.register({
      secret: 'some_secret_thing',
      signOptions: { expiresIn: '60s' },
    }),
  ],
  providers: [JwtStrategy],
})
export class AuthModule {}
Example #25
Source File: account.service.spec.ts    From uniauth-backend with MIT License 5 votes vote down vote up
describe('AccountService', () => {
  let testingModule: TestingModule;
  let service: AccountService;

  beforeEach(async () => {
    testingModule = await Test.createTestingModule({
      imports: [
        rootMongooseTestModule(),
        JwtModule.register({
          secret: accessTokenJwtConstants.secret,
          signOptions: { expiresIn: accessTokenJwtConstants.expiresIn },
        }),
        AccountModule,
        WinstonModule.forRoot(logger.console()),
      ],
      providers: [
        AccountService,
        {
          provide: AccountService,
          useFactory: () => ({
            generateAccessToken: jest.fn(() => true),
          }),
        },
        {
          provide: ApplicationService,
          useFactory: () => ({
            findOneById: jest.fn(() => true),
            findOneByIdAndSecret: jest.fn(() => true),
          }),
        },
        {
          provide: UserService,
          useFactory: () => ({
            login: jest.fn(() => true),
            findOneById: jest.fn(() => true),
          }),
        },
      ],
    }).compile();

    service = testingModule.get<AccountService>(AccountService);
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });

  describe('.validateAccessRequest()', () => {
    it('should be defined', () => {
      expect(service.validateAccessRequest).toBeDefined();
    });
  });

  describe('.generateAccessToken()', () => {
    it('should be defined', () => {
      expect(service.generateAccessToken).toBeDefined();
    });
  });

  describe('.authenticateAndGenerateToken()', () => {
    it('should be defined', () => {
      expect(service.authenticateAndGenerateToken).toBeDefined();
    });
  });

  describe('.provideUserDetailOnAccess()', () => {
    it('should be defined', () => {
      expect(service.provideUserDetailOnAccess).toBeDefined();
    });
  });
});
Example #26
Source File: mailer.service.spec.ts    From uniauth-backend with MIT License 5 votes vote down vote up
describe('MailerService', () => {
  let testingModule: TestingModule;
  let service: MailerService;
  //   let model: Model<UserDocument>;

  beforeEach(async () => {
    testingModule = await Test.createTestingModule({
      imports: [
        rootMongooseTestModule(),
        MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]),
        JwtModule.register({
          secret: confirmEmailTokenConstants.secret,
          signOptions: { expiresIn: confirmEmailTokenConstants.expiresIn },
        }),
        WinstonModule.forRoot(logger.console()),
      ],
      providers: [
        MailerService,
        UserService,
        {
          provide: getModelToken(User.name),
          useValue: {
            findByIdAndUpdate: jest.fn().mockResolvedValue(mockUser()),
          },
        },
      ],
    }).compile();

    service = testingModule.get<MailerService>(MailerService);
    // model = testingModule.get<Model<UserDocument>>(getModelToken(User.name));
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });

  describe('.generateJwt()', () => {
    it('should be defined', () => {
      expect(service.generateJwt).toBeDefined();
    });
  });

  describe('.checkVerificationToken()', () => {
    it('should be defined', () => {
      expect(service.checkVerificationToken).toBeDefined();
    });
  });

  describe('.checkPasswordResetToken()', () => {
    it('should be defined', () => {
      expect(service.checkPasswordResetToken).toBeDefined();
    });
  });

  describe('.sendEmail()', () => {
    it('should be defined', () => {
      expect(service.sendEmail).toBeDefined();
    });
  });

  describe('.sendPasswordResetLink()', () => {
    it('should be defined', () => {
      expect(service.sendPasswordResetLink).toBeDefined();
    });
  });
});
Example #27
Source File: app.imports.ts    From api with GNU Affero General Public License v3.0 5 votes vote down vote up
imports = [
  ConsoleModule,
  HttpModule.register({
    timeout: 5000,
    maxRedirects: 10,
  }),
  ServeStaticModule.forRoot({
    rootPath: join(__dirname, '..', 'public'),
    exclude: ['/graphql'],
  }),
  ConfigModule.forRoot({
    load: [
      () => {
        return {
          LOCALES_PATH: join(process.cwd(), 'locales'),
          SECRET_KEY: process.env.SECRET_KEY || crypto.randomBytes(20).toString('hex'),
        }
      },
    ],
  }),
  JwtModule.registerAsync({
    imports: [ConfigModule],
    inject: [ConfigService],
    useFactory: (configService: ConfigService): JwtModuleOptions => ({
      secret: configService.get<string>('SECRET_KEY'),
      signOptions: {
        expiresIn: '4h',
      },
    }),
  }),
  LoggerModule.forRoot(LoggerConfig),
  GraphQLModule.forRoot<ApolloDriverConfig>({
    debug: process.env.NODE_ENV !== 'production',
    definitions: {
      outputAs: 'class',
    },
    driver: ApolloDriver,
    sortSchema: true,
    introspection: process.env.NODE_ENV !== 'production',
    playground: process.env.NODE_ENV !== 'production',
    installSubscriptionHandlers: true,
    autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
    // to allow guards on resolver props https://github.com/nestjs/graphql/issues/295
    fieldResolverEnhancers: [
      'guards',
      'interceptors',
    ],
    resolverValidationOptions: {

    },
    context: ({ req, connection }) => {
      if (!req && connection) {
        const headers: IncomingHttpHeaders = {}

        Object.keys(connection.context).forEach(key => {
          headers[key.toLowerCase()] = connection.context[key]
        })

        return {
          req: {
            headers,
          } as Request,
        }
      }

      return { req }
    },
  }),
  TypeOrmModule.forRootAsync({
    imports: [ConfigModule],
    inject: [ConfigService],
    useFactory: (configService: ConfigService): TypeOrmModuleOptions => {
      const type: any = configService.get<string>('DATABASE_DRIVER', 'sqlite')
      let migrationFolder: string
      let migrationsTransactionMode: 'each' | 'none' | 'all' = 'each'

      switch (type) {
        case 'cockroachdb':
        case 'postgres':
          migrationFolder = 'postgres'
          break

        case 'mysql':
        case 'mariadb':
          migrationFolder = 'mariadb'
          break

        case 'sqlite':
          migrationFolder = 'sqlite'
          migrationsTransactionMode = 'none'
          break

        default:
          throw new Error('unsupported driver')
      }

      return ({
        name: 'ohmyform',
        synchronize: false,
        type,
        url: configService.get<string>('DATABASE_URL'),
        database: type === 'sqlite' ? configService.get<string>('DATABASE_URL', 'data.sqlite').replace('sqlite://', '') : undefined,
        ssl: configService.get<string>('DATABASE_SSL', 'false') === 'true' ? { rejectUnauthorized: false } : false,
        entityPrefix: configService.get<string>('DATABASE_TABLE_PREFIX', ''),
        logging: configService.get<string>('DATABASE_LOGGING', 'false') === 'true',
        entities,
        migrations: [`${__dirname}/**/migrations/${migrationFolder}/**/*{.ts,.js}`],
        migrationsRun: configService.get<boolean>('DATABASE_MIGRATE', true),
        migrationsTransactionMode,
      })
    },
  }),
  TypeOrmModule.forFeature(entities),
  MailerModule.forRootAsync({
    imports: [ConfigModule],
    inject: [ConfigService],
    useFactory: (configService: ConfigService) => ({
      transport: configService.get<string>('MAILER_URI', 'smtp://localhost:1025'),
      defaults: {
        from: configService.get<string>('MAILER_FROM', 'OhMyForm <no-reply@localhost>'),
      },
    }),
  }),
]
Example #28
Source File: auth.service.spec.ts    From uniauth-backend with MIT License 5 votes vote down vote up
/** mocking definitions */
describe('Auth Service', () => {
  let testingModule: TestingModule;
  let service: AuthService;

  beforeEach(async () => {
    testingModule = await Test.createTestingModule({
      imports: [
        rootMongooseTestModule(),
        UserModule,
        JwtModule.register({
          secret: newJWTConstants.secret,
          signOptions: { expiresIn: newJWTConstants.expiresIn },
        }),
        WinstonModule.forRoot(logger.console()),
      ],
      providers: [
        AuthService,
        {
          provide: UserService,
          useFactory: () => ({
            login: jest.fn(() => true),
          }),
        },
      ],
    }).compile();

    service = testingModule.get<AuthService>(AuthService);
    // model = testingModule.get<Model<UserDocument>>(getModelToken(User.name));
  });

  afterEach(() => {
    jest.clearAllMocks();
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });

  describe('.validateUser()', () => {
    it('should be defined', () => {
      expect(service.validateUser).toBeDefined();
    });
  });

  describe('.checkLogin()', () => {
    it('should be defined', () => {
      expect(service.checkLogin).toBeDefined();
    });
  });

  describe('.generateJwt()', () => {
    it('should be defined', () => {
      expect(service.generateJwt).toBeDefined();
    });
  });
});
Example #29
Source File: auth.module.ts    From amplication with Apache License 2.0 5 votes vote down vote up
@Module({
  imports: [
    ConfigModule,
    PassportModule.register({ defaultStrategy: 'jwt' }),
    JwtModule.registerAsync({
      imports: [ConfigModule],
      useFactory: async (configService: ConfigService) => ({
        secret: configService.get('JWT_SECRET')
      }),
      inject: [ConfigService]
    }),
    AccountModule, // (AccountService, PasswordService)
    PrismaModule, // (PrismaService)
    PermissionsModule,
    ExceptionFiltersModule,
    WorkspaceModule,
    UserModule,
    GoogleSecretsManagerModule
  ],
  providers: [
    AuthService,
    JwtStrategy,
    {
      provide: 'GitHubStrategy',
      useFactory: async (
        authService: AuthService,
        configService: ConfigService,
        googleSecretsManagerService: GoogleSecretsManagerService
      ) => {
        const githubConfigService = new GitHubStrategyConfigService(
          configService,
          googleSecretsManagerService
        );
        const options = await githubConfigService.getOptions();
        if (options === null) {
          return;
        }
        return new GitHubStrategy(authService, options);
      },
      inject: [AuthService, ConfigService, GoogleSecretsManagerService]
    },
    GqlAuthGuard,
    AuthResolver,
    GitHubStrategyConfigService
  ],
  controllers: [AuthController],
  exports: [GqlAuthGuard, AuthService, AuthResolver]
})
export class AuthModule {}