├── .dockerignore ├── Procfile ├── .prettierrc ├── nest-cli.json ├── src ├── modules │ ├── common │ │ ├── enum │ │ │ └── roles.enum.ts │ │ ├── decorator │ │ │ ├── public.decorator.ts │ │ │ └── roles.decorator.ts │ │ ├── validator │ │ │ ├── FindOneUUID.validator.ts │ │ │ ├── same-as.validator.ts │ │ │ ├── unique.validator.ts │ │ │ └── exists.validator.ts │ │ ├── common.module.ts │ │ ├── interceptor │ │ │ ├── logging.interceptor.ts │ │ │ ├── transform.interceptor.ts │ │ │ └── timeout.interceptor.ts │ │ └── guard │ │ │ └── roles.guard.ts │ ├── user │ │ ├── index.ts │ │ ├── password.transformer.ts │ │ ├── payloads │ │ │ └── update.payload.ts │ │ ├── user.module.ts │ │ ├── entity │ │ │ └── user.entity.ts │ │ ├── user.controller.ts │ │ └── user.service.ts │ └── auth │ │ ├── payloads │ │ ├── login.payload.ts │ │ ├── verify.payload.ts │ │ ├── reset.payload.ts │ │ └── register.payload.ts │ │ ├── jwt-guard.ts │ │ ├── jwt.strategy.ts │ │ ├── auth.service.ts │ │ ├── auth.module.ts │ │ └── auth.controller.ts ├── swagger │ ├── configs.ts │ └── index.ts ├── app │ ├── app.service.ts │ ├── app.controller.ts │ └── app.module.ts ├── utils │ └── Hash.ts ├── fixtures │ └── user.yml └── main.ts ├── tsconfig.build.json ├── nodemon.json ├── nodemon-debug.json ├── .eslintignore ├── Dockerfile ├── docker ├── entrypoint-nginx.sh └── vhost.template ├── test └── jest-e2e.json ├── Dockerfile-nginx ├── tsconfig.json ├── .env.example ├── .gitignore ├── ormconfig.js ├── .eslintrc.js ├── docker-compose.yml ├── package.json ├── README.md └── LICENSE /.dockerignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | web: yarn start:prod 2 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all" 4 | } -------------------------------------------------------------------------------- /nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "collection": "@nestjs/schematics", 3 | "sourceRoot": "src" 4 | } 5 | -------------------------------------------------------------------------------- /src/modules/common/enum/roles.enum.ts: -------------------------------------------------------------------------------- 1 | export enum AppRoles { 2 | DEFAULT = 'DEFAULT', 3 | ADMINS = 'ADMIN', 4 | } 5 | -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "exclude": ["node_modules", "test", "dist", "**/*spec.ts"] 4 | } 5 | -------------------------------------------------------------------------------- /nodemon.json: -------------------------------------------------------------------------------- 1 | { 2 | "watch": ["src"], 3 | "ext": "ts", 4 | "ignore": ["src/**/*.spec.ts"], 5 | "exec": "ts-node -r tsconfig-paths/register src/main.ts" 6 | } 7 | -------------------------------------------------------------------------------- /nodemon-debug.json: -------------------------------------------------------------------------------- 1 | { 2 | "watch": ["src/"], 3 | "ext": "ts", 4 | "ignore": ["src/**/*.spec.ts"], 5 | "exec": "node --inspect-brk -r ts-node/register src/main.ts" 6 | } -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | # don't ever lint node_modules 2 | node_modules 3 | # don't lint build output (make sure it's set to your correct build folder name) 4 | dist 5 | # don't lint nyc coverage output 6 | coverage -------------------------------------------------------------------------------- /src/modules/common/decorator/public.decorator.ts: -------------------------------------------------------------------------------- 1 | import { SetMetadata } from '@nestjs/common'; 2 | 3 | export const IS_PUBLIC_KEY = 'isPublic'; 4 | export const Public = () => SetMetadata(IS_PUBLIC_KEY, true); 5 | -------------------------------------------------------------------------------- /src/modules/user/index.ts: -------------------------------------------------------------------------------- 1 | export * from './password.transformer'; 2 | export * from './entity/user.entity'; 3 | export * from './user.controller'; 4 | export * from './user.service'; 5 | export * from './user.module'; 6 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:15.14.0 2 | 3 | WORKDIR /app 4 | ENV NODE_ENV development 5 | COPY package.json yarn.lock ./ 6 | RUN yarn install 7 | 8 | COPY . . 9 | 10 | EXPOSE 3000 11 | 12 | CMD [ "yarn", "start:dev" ] 13 | -------------------------------------------------------------------------------- /docker/entrypoint-nginx.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | vars=$(compgen -A variable) 4 | subst=$(printf '${%s} ' $vars) 5 | envsubst "$subst" < /etc/nginx/conf.d/vhost.template > /etc/nginx/conf.d/default.conf 6 | nginx -g 'daemon off;' 7 | 8 | -------------------------------------------------------------------------------- /test/jest-e2e.json: -------------------------------------------------------------------------------- 1 | { 2 | "moduleFileExtensions": ["js", "json", "ts"], 3 | "rootDir": ".", 4 | "testEnvironment": "node", 5 | "testRegex": ".e2e-spec.ts$", 6 | "transform": { 7 | "^.+\\.(t|j)s$": "ts-jest" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/modules/common/decorator/roles.decorator.ts: -------------------------------------------------------------------------------- 1 | import { SetMetadata } from '@nestjs/common'; 2 | import { AppRoles } from '../enum/roles.enum'; 3 | 4 | export const ROLES_KEY = 'roles'; 5 | export const Roles = (...roles: AppRoles[]) => SetMetadata(ROLES_KEY, roles); 6 | -------------------------------------------------------------------------------- /src/swagger/configs.ts: -------------------------------------------------------------------------------- 1 | export const SITE_TITLE = 'TFD API'; 2 | export const API_NAME = 'Scalable NestJS v8 Boilerplate'; 3 | export const API_ROOT = 'api/docs'; 4 | export const API_DESCRIPTION = 'Nest template with preconfigured libraries'; 5 | export const API_CURRENT_VERSION = '1.0'; 6 | -------------------------------------------------------------------------------- /Dockerfile-nginx: -------------------------------------------------------------------------------- 1 | FROM nginx:1.20.0-alpine 2 | 3 | COPY ./docker/entrypoint-nginx.sh / 4 | 5 | RUN set -ex && \ 6 | apk add --no-cache bash && \ 7 | chmod +x /entrypoint-nginx.sh 8 | 9 | COPY ./docker/vhost.template /etc/nginx/conf.d/vhost.template 10 | 11 | CMD ["/entrypoint-nginx.sh"] 12 | -------------------------------------------------------------------------------- /src/modules/common/validator/FindOneUUID.validator.ts: -------------------------------------------------------------------------------- 1 | import { IsNotEmpty, IsUUID } from 'class-validator'; 2 | import { ApiProperty } from '@nestjs/swagger'; 3 | 4 | export class UUIDType { 5 | @ApiProperty({ 6 | required: true, 7 | }) 8 | @IsNotEmpty() 9 | @IsUUID() 10 | id: string; 11 | } 12 | -------------------------------------------------------------------------------- /src/app/app.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { ConfigService } from '@nestjs/config'; 3 | 4 | @Injectable() 5 | export class AppService { 6 | constructor(private configService: ConfigService) {} 7 | root(): string { 8 | return this.configService.get('APP_URL'); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/utils/Hash.ts: -------------------------------------------------------------------------------- 1 | import * as bcrypt from 'bcrypt'; 2 | 3 | export class Hash { 4 | static make(plainText) { 5 | const salt = bcrypt.genSaltSync(); 6 | return bcrypt.hashSync(plainText, salt); 7 | } 8 | 9 | static compare(plainText, hash) { 10 | return bcrypt.compareSync(plainText, hash); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/modules/common/common.module.ts: -------------------------------------------------------------------------------- 1 | import { Global, Module } from '@nestjs/common'; 2 | import { ExistsValidator } from './validator/exists.validator'; 3 | import { UniqueValidator } from './validator/unique.validator'; 4 | 5 | @Global() 6 | @Module({ 7 | providers: [UniqueValidator, ExistsValidator], 8 | }) 9 | export class CommonModule {} 10 | -------------------------------------------------------------------------------- /src/modules/auth/payloads/login.payload.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | import { IsNotEmpty, MinLength } from 'class-validator'; 3 | 4 | export class LoginPayload { 5 | @ApiProperty({ 6 | required: true, 7 | }) 8 | @IsNotEmpty() 9 | username: string; 10 | @ApiProperty({ 11 | required: true, 12 | }) 13 | @IsNotEmpty() 14 | @MinLength(5) 15 | password: string; 16 | } 17 | -------------------------------------------------------------------------------- /src/fixtures/user.yml: -------------------------------------------------------------------------------- 1 | entity: UserEntity 2 | items: 3 | user1: 4 | username: user 5 | name: '{{name.firstName}} {{name.lastName}}' 6 | password: admin 7 | roles: 8 | - ADMIN 9 | email: '{{internet.email}}' 10 | user2: 11 | username: user2 12 | name: '{{name.firstName}} {{name.lastName}}' 13 | password: admin2 14 | roles: 15 | - DEFAULT 16 | email: '{{internet.email}}' 17 | 18 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "declaration": true, 5 | "removeComments": true, 6 | "emitDecoratorMetadata": true, 7 | "experimentalDecorators": true, 8 | "allowSyntheticDefaultImports": true, 9 | "target": "es2017", 10 | "sourceMap": true, 11 | "outDir": "./dist", 12 | "baseUrl": "./", 13 | "incremental": true, 14 | "skipLibCheck": true 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/modules/auth/payloads/verify.payload.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | import { IsNotEmpty } from 'class-validator'; 3 | 4 | export class VerifyPayload { 5 | @ApiProperty({ 6 | required: true, 7 | }) 8 | @IsNotEmpty() 9 | username: string; 10 | 11 | @ApiProperty({ 12 | required: true, 13 | }) 14 | @IsNotEmpty() 15 | securityQuestion: string; 16 | 17 | @ApiProperty({ 18 | required: true, 19 | }) 20 | @IsNotEmpty() 21 | answer: string; 22 | } 23 | -------------------------------------------------------------------------------- /src/modules/user/password.transformer.ts: -------------------------------------------------------------------------------- 1 | import { ValueTransformer } from 'typeorm'; 2 | import { Hash } from '../../utils/Hash'; 3 | 4 | export class PasswordTransformer implements ValueTransformer { 5 | /** 6 | * Transform to custom value 7 | * @param value value to transform 8 | */ 9 | to(value) { 10 | return Hash.make(value); 11 | } 12 | 13 | /** 14 | * Original value 15 | * @param value to be transformed 16 | */ 17 | from(value) { 18 | return value; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/modules/user/payloads/update.payload.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | import { IsEmail, IsNotEmpty, IsOptional } from "class-validator"; 3 | 4 | export class UpdatePayload { 5 | @ApiProperty({ 6 | required: false, 7 | }) 8 | @IsNotEmpty() 9 | username: string; 10 | 11 | @ApiProperty({ 12 | required: false, 13 | }) 14 | @IsNotEmpty() 15 | name: string; 16 | 17 | @ApiProperty({ 18 | required: false, 19 | }) 20 | @IsEmail() 21 | email: string; 22 | } 23 | -------------------------------------------------------------------------------- /src/app/app.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Get, UseGuards } from '@nestjs/common'; 2 | import { ApiBearerAuth } from '@nestjs/swagger'; 3 | import { AppService } from './app.service'; 4 | import { AuthGuard } from '@nestjs/passport'; 5 | 6 | @ApiBearerAuth() 7 | @Controller() 8 | export class AppController { 9 | constructor(private readonly appService: AppService) {} 10 | 11 | // @Get() 12 | // @UseGuards(AuthGuard()) 13 | // root(): string { 14 | // return this.appService.root(); 15 | // } 16 | } 17 | -------------------------------------------------------------------------------- /docker/vhost.template: -------------------------------------------------------------------------------- 1 | # vim: ft=nginx 2 | 3 | server { 4 | listen 80; 5 | server_name ${NGINX_SERVER_NAME}; 6 | root /app/public; 7 | client_max_body_size ${NGINX_MAX_BODY}; 8 | 9 | location / { 10 | # try_files $uri =404; 11 | proxy_pass http://${NEST_HOST}:${NEST_PORT}; 12 | proxy_set_header Host $host; 13 | proxy_set_header X-Real-IP $remote_addr; 14 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 15 | proxy_set_header X-Forwarded-Host $server_name; 16 | proxy_set_header X-Forwarded-Proto https; 17 | } 18 | } 19 | 20 | -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- 1 | # APP 2 | APP_ENV=dev 3 | APP_URL=http://localhost 4 | 5 | # JWT AUTH 6 | JWT_SECRET_KEY=eyJhbGciOiJIUzI1NiJ9 7 | JWT_EXPIRATION_TIME=3600 8 | 9 | # DATABASE 10 | DB_TYPE=postgres 11 | DB_USERNAME=nest 12 | DB_PASSWORD=nest 13 | DB_HOST=db 14 | DB_PORT=5432 15 | DB_DATABASE=nest 16 | DB_SYNC=true 17 | # For production 18 | DATABASE_URL=your-db-url-in-production 19 | 20 | # REDIS CACHE INFO 21 | CACHE_TTL=5 22 | CACHE_MAX=10 23 | CACHE_STORE=redisStore 24 | CACHE_HOST=redis 25 | CACHE_PORT=6379 26 | # For production 27 | REDIS_URL=your-redis-url-in-production 28 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # compiled output 2 | /dist 3 | /node_modules 4 | 5 | # Logs 6 | logs 7 | *.log 8 | npm-debug.log* 9 | pnpm-debug.log* 10 | yarn-debug.log* 11 | yarn-error.log* 12 | lerna-debug.log* 13 | 14 | # OS 15 | .DS_Store 16 | 17 | # Tests 18 | /coverage 19 | /.nyc_output 20 | 21 | # IDEs and editors 22 | /.idea 23 | .project 24 | .classpath 25 | .c9/ 26 | *.launch 27 | .settings/ 28 | *.sublime-workspace 29 | 30 | # IDE - VSCode 31 | .vscode/* 32 | !.vscode/settings.json 33 | !.vscode/tasks.json 34 | !.vscode/launch.json 35 | !.vscode/extensions.json 36 | upload 37 | # environment 38 | .env 39 | .idea/ -------------------------------------------------------------------------------- /src/modules/common/interceptor/logging.interceptor.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Injectable, 3 | NestInterceptor, 4 | ExecutionContext, 5 | CallHandler, 6 | } from '@nestjs/common'; 7 | import { Observable } from 'rxjs'; 8 | import { tap } from 'rxjs/operators'; 9 | 10 | @Injectable() 11 | export class LoggingInterceptor implements NestInterceptor { 12 | intercept(context: ExecutionContext, next: CallHandler): Observable { 13 | console.log('Before...'); 14 | 15 | const now = Date.now(); 16 | return next 17 | .handle() 18 | .pipe(tap(() => console.log(`After... ${Date.now() - now}ms`))); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /ormconfig.js: -------------------------------------------------------------------------------- 1 | const dotenv = require('dotenv'); 2 | 3 | dotenv.config(); 4 | 5 | const { 6 | DB_TYPE, 7 | DB_HOST, 8 | DB_USERNAME, 9 | DB_PASSWORD, 10 | DB_PORT, 11 | DB_DATABASE, 12 | DB_SYNC, 13 | } = process.env; 14 | 15 | module.exports = { 16 | type: DB_TYPE, 17 | host: DB_HOST, 18 | port: DB_PORT, 19 | username: DB_USERNAME, 20 | password: DB_PASSWORD, 21 | database: DB_DATABASE, 22 | migrations: [__dirname + '/src/migrations/*{.ts,.js}'], 23 | entities: [__dirname + '/src/**/*.entity.{ts,js}'], 24 | subscribers: [__dirname + '/src/**/*.subscriber.{ts,js}'], 25 | synchronize: DB_SYNC, 26 | }; 27 | -------------------------------------------------------------------------------- /src/modules/common/interceptor/transform.interceptor.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Injectable, 3 | NestInterceptor, 4 | ExecutionContext, 5 | CallHandler, 6 | } from '@nestjs/common'; 7 | import { Observable } from 'rxjs'; 8 | import { map } from 'rxjs/operators'; 9 | 10 | export interface Response { 11 | data: T; 12 | } 13 | 14 | @Injectable() 15 | export class TransformInterceptor 16 | implements NestInterceptor> 17 | { 18 | intercept( 19 | context: ExecutionContext, 20 | next: CallHandler, 21 | ): Observable> { 22 | return next.handle().pipe(map((data) => ({ data }))); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/modules/user/user.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { TypeOrmModule } from '@nestjs/typeorm'; 3 | import { UserEntity } from './entity/user.entity'; 4 | import { UserController } from './user.controller'; 5 | import { PassportModule } from '@nestjs/passport'; 6 | import { UsersService } from './user.service'; 7 | 8 | @Module({ 9 | imports: [ 10 | TypeOrmModule.forFeature([UserEntity]), 11 | PassportModule.register({ defaultStrategy: 'jwt' }), 12 | ], 13 | exports: [UsersService], 14 | controllers: [UserController], 15 | providers: [UsersService], 16 | }) 17 | export class UserModule {} 18 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parser: '@typescript-eslint/parser', 3 | parserOptions: { 4 | project: 'tsconfig.json', 5 | sourceType: 'module', 6 | }, 7 | plugins: ['@typescript-eslint/eslint-plugin'], 8 | extends: [ 9 | 'plugin:@typescript-eslint/recommended', 10 | 'plugin:prettier/recommended', 11 | ], 12 | root: true, 13 | env: { 14 | node: true, 15 | jest: true, 16 | }, 17 | ignorePatterns: ['.eslintrc.js'], 18 | rules: { 19 | '@typescript-eslint/explicit-function-return-type': 'off', 20 | '@typescript-eslint/explicit-module-boundary-types': 'off', 21 | '@typescript-eslint/no-explicit-any': 'off', 22 | }, 23 | }; 24 | -------------------------------------------------------------------------------- /src/modules/auth/payloads/reset.payload.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | import { IsNotEmpty, MinLength } from 'class-validator'; 3 | import { SameAs } from '../../common/validator/same-as.validator'; 4 | 5 | export class ResetPayload { 6 | @ApiProperty({ 7 | required: true, 8 | }) 9 | @IsNotEmpty() 10 | username: string; 11 | 12 | @ApiProperty({ 13 | required: true, 14 | }) 15 | @IsNotEmpty() 16 | @MinLength(5) 17 | currentPassword: string; 18 | 19 | @ApiProperty({ 20 | required: true, 21 | }) 22 | @IsNotEmpty() 23 | @MinLength(5) 24 | newPassword: string; 25 | 26 | @ApiProperty({ 27 | required: true, 28 | }) 29 | @IsNotEmpty() 30 | @SameAs('newPassword') 31 | confirmPassword: string; 32 | } 33 | -------------------------------------------------------------------------------- /src/modules/common/interceptor/timeout.interceptor.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Injectable, 3 | NestInterceptor, 4 | ExecutionContext, 5 | CallHandler, 6 | RequestTimeoutException, 7 | } from '@nestjs/common'; 8 | import { Observable, throwError, TimeoutError } from 'rxjs'; 9 | import { catchError, timeout } from 'rxjs/operators'; 10 | 11 | @Injectable() 12 | export class TimeoutInterceptor implements NestInterceptor { 13 | intercept(context: ExecutionContext, next: CallHandler): Observable { 14 | return next.handle().pipe( 15 | timeout(20000), 16 | catchError((err) => { 17 | if (err instanceof TimeoutError) { 18 | return throwError(new RequestTimeoutException()); 19 | } 20 | return throwError(err); 21 | }), 22 | ); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/modules/common/guard/roles.guard.ts: -------------------------------------------------------------------------------- 1 | import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common'; 2 | import { Reflector } from '@nestjs/core'; 3 | import { ROLES_KEY } from '../decorator/roles.decorator'; 4 | import { AppRoles } from '../enum/roles.enum'; 5 | 6 | @Injectable() 7 | export class RolesGuard implements CanActivate { 8 | constructor(private reflector: Reflector) {} 9 | 10 | canActivate(context: ExecutionContext): boolean { 11 | const requiredRoles = this.reflector.getAllAndOverride( 12 | ROLES_KEY, 13 | [context.getHandler(), context.getClass()], 14 | ); 15 | if (!requiredRoles) { 16 | return true; 17 | } 18 | const { user } = context.switchToHttp().getRequest(); 19 | return requiredRoles.some((role) => user.roles?.includes(role)); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/modules/common/validator/same-as.validator.ts: -------------------------------------------------------------------------------- 1 | import { registerDecorator, ValidationOptions } from 'class-validator'; 2 | 3 | export function SameAs( 4 | property: string, 5 | validationOptions?: ValidationOptions, 6 | ) { 7 | return function (object: Object, propertyName: string) { 8 | registerDecorator({ 9 | name: 'sameAs', 10 | target: object.constructor, 11 | propertyName: propertyName, 12 | options: validationOptions, 13 | constraints: [property], 14 | validator: { 15 | validate(value: any, args: any) { 16 | const [relatedPropertyName] = args.constraints; 17 | return args.object[relatedPropertyName] === value; 18 | }, 19 | defaultMessage() { 20 | return '$property must match $constraint1'; 21 | }, 22 | }, 23 | }); 24 | }; 25 | } 26 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { NestFactory } from '@nestjs/core'; 2 | import { setupSwagger } from './swagger'; 3 | import { useContainer } from 'class-validator'; 4 | import { ValidationPipe } from '@nestjs/common'; 5 | import { AppModule } from './app/app.module'; 6 | 7 | async function bootstrap() { 8 | const app = await NestFactory.create(AppModule); 9 | setupSwagger(app); 10 | // Enable Cors for development 11 | app.enableCors(); 12 | // Global Pipe to intercept request and format data accordingly 13 | app.useGlobalPipes(new ValidationPipe({ transform: true })); 14 | useContainer(app.select(AppModule), { fallbackOnErrors: true }); 15 | // Listen to port given by environment on production server (Heroku, DigitalOcean App,..), otherwise 3000 16 | // Specify '0.0.0.0' in the listen() to accept connections on other hosts. 17 | await app.listen(process.env.PORT || 3000); 18 | } 19 | bootstrap(); 20 | -------------------------------------------------------------------------------- /src/modules/auth/jwt-guard.ts: -------------------------------------------------------------------------------- 1 | import { 2 | ExecutionContext, 3 | Injectable, 4 | UnauthorizedException, 5 | } from '@nestjs/common'; 6 | import { AuthGuard } from '@nestjs/passport'; 7 | import { Reflector } from '@nestjs/core'; 8 | import { IS_PUBLIC_KEY } from '../common/decorator/public.decorator'; 9 | 10 | @Injectable() 11 | export class JwtAuthGuard extends AuthGuard('jwt') { 12 | constructor(private reflector: Reflector) { 13 | super(); 14 | } 15 | canActivate(context: ExecutionContext) { 16 | const isPublic = this.reflector.getAllAndOverride(IS_PUBLIC_KEY, [ 17 | context.getHandler(), 18 | context.getClass(), 19 | ]); 20 | if (isPublic) { 21 | return true; 22 | } 23 | return super.canActivate(context); 24 | } 25 | 26 | handleRequest(err, user, info) { 27 | if (err || !user) { 28 | throw err || new UnauthorizedException(); 29 | } 30 | return user; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/swagger/index.ts: -------------------------------------------------------------------------------- 1 | import { INestApplication } from '@nestjs/common'; 2 | import { 3 | SwaggerModule, 4 | DocumentBuilder, 5 | SwaggerCustomOptions, 6 | } from '@nestjs/swagger'; 7 | import { 8 | API_CURRENT_VERSION, 9 | API_DESCRIPTION, 10 | API_NAME, 11 | API_ROOT, 12 | SITE_TITLE, 13 | } from './configs'; 14 | 15 | export const setupSwagger = (app: INestApplication) => { 16 | const customOptions: SwaggerCustomOptions = { 17 | customSiteTitle: SITE_TITLE, 18 | /** 19 | * Persist authorization after page refresh 20 | */ 21 | swaggerOptions: { 22 | persistAuthorization: true, 23 | }, 24 | }; 25 | const options = new DocumentBuilder() 26 | .setTitle(API_NAME) 27 | .setDescription(API_DESCRIPTION) 28 | .setVersion(API_CURRENT_VERSION) 29 | .addBearerAuth() 30 | .build(); 31 | const document = SwaggerModule.createDocument(app, options); 32 | SwaggerModule.setup(API_ROOT, app, document, customOptions); 33 | }; 34 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "2" 2 | services: 3 | nest: 4 | build: . 5 | container_name: tfd-nest 6 | depends_on: 7 | - db 8 | - redis 9 | volumes: 10 | - ./src:/app/src 11 | - ./test:/app/test 12 | - .env:/app/.env 13 | - ./upload:/app/upload 14 | nginx: 15 | build: 16 | context: . 17 | dockerfile: Dockerfile-nginx 18 | container_name: tfd-nest-nginx 19 | depends_on: 20 | - nest 21 | environment: 22 | - NGINX_SERVER_NAME=localhost 23 | - NEST_HOST=nest 24 | - NEST_PORT=3000 25 | - NGINX_MAX_BODY=100M 26 | ports: 27 | - 80:80 28 | db: 29 | image: postgres:12 30 | container_name: tfd-nest-db 31 | environment: 32 | POSTGRES_DB: nest 33 | POSTGRES_USER: nest 34 | POSTGRES_PASSWORD: nest 35 | ports: 36 | - 5432:5432 37 | volumes: 38 | - postgresdata:/var/lib/postgresql 39 | redis: 40 | image: redis:5 41 | container_name: tfd-redis 42 | ports: 43 | - 6379:6379 44 | volumes: 45 | postgresdata: 46 | -------------------------------------------------------------------------------- /src/modules/auth/jwt.strategy.ts: -------------------------------------------------------------------------------- 1 | import { ExtractJwt, Strategy, JwtPayload } from 'passport-jwt'; 2 | import { PassportStrategy } from '@nestjs/passport'; 3 | import { Injectable, UnauthorizedException } from '@nestjs/common'; 4 | import { UsersService } from '../user'; 5 | import { ConfigService } from '@nestjs/config'; 6 | 7 | @Injectable() 8 | export class JwtStrategy extends PassportStrategy(Strategy) { 9 | constructor( 10 | readonly configService: ConfigService, 11 | private readonly usersService: UsersService, 12 | ) { 13 | super({ 14 | jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), 15 | secretOrKey: configService.get('JWT_SECRET_KEY'), 16 | }); 17 | } 18 | 19 | async validate({ iat, exp, id }: JwtPayload, done) { 20 | const timeDiff = exp - iat; 21 | if (timeDiff <= 0) { 22 | throw new UnauthorizedException(); 23 | } 24 | 25 | const user = await this.usersService.get(id); 26 | if (!user) { 27 | throw new UnauthorizedException(); 28 | } 29 | 30 | delete user.password; 31 | done(null, user); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/modules/auth/payloads/register.payload.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | import { 3 | IsAlphanumeric, 4 | IsEmail, 5 | IsNotEmpty, 6 | Matches, 7 | MinLength, 8 | } from 'class-validator'; 9 | import { UserEntity } from '../../user'; 10 | import { SameAs } from '../../common/validator/same-as.validator'; 11 | import { Unique } from '../../common/validator/unique.validator'; 12 | 13 | export class RegisterPayload { 14 | @ApiProperty({ 15 | required: true, 16 | }) 17 | @IsAlphanumeric() 18 | @IsNotEmpty() 19 | @Unique([UserEntity]) 20 | username: string; 21 | 22 | @ApiProperty({ 23 | required: true, 24 | }) 25 | @IsEmail() 26 | @IsNotEmpty() 27 | @Unique([UserEntity]) 28 | email: string; 29 | 30 | @ApiProperty({ 31 | required: true, 32 | }) 33 | @Matches(/^[a-zA-Z ]+$/) 34 | @IsNotEmpty() 35 | name: string; 36 | 37 | @ApiProperty({ 38 | required: true, 39 | }) 40 | @IsNotEmpty() 41 | @MinLength(5) 42 | password: string; 43 | 44 | @ApiProperty({ required: true }) 45 | @SameAs('password') 46 | passwordConfirmation: string; 47 | } 48 | -------------------------------------------------------------------------------- /src/modules/auth/auth.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable, UnauthorizedException } from '@nestjs/common'; 2 | import { JwtService } from '@nestjs/jwt'; 3 | import { Hash } from '../../utils/Hash'; 4 | import { UserEntity, UsersService } from '../user'; 5 | import { LoginPayload } from './payloads/login.payload'; 6 | import { ConfigService } from '@nestjs/config'; 7 | 8 | @Injectable() 9 | export class AuthService { 10 | constructor( 11 | private readonly jwtService: JwtService, 12 | private readonly configService: ConfigService, 13 | private readonly userService: UsersService, 14 | ) {} 15 | 16 | async createToken(user: UserEntity) { 17 | return { 18 | expiresIn: this.configService.get('JWT_EXPIRATION_TIME'), 19 | accessToken: this.jwtService.sign({ id: user.id }), 20 | user, 21 | }; 22 | } 23 | 24 | async validateUser(payload: LoginPayload): Promise { 25 | const user = await this.userService.getByUsername(payload.username); 26 | if (!user || !Hash.compare(payload.password, user.password)) { 27 | throw new UnauthorizedException('Username or Password is not correct!'); 28 | } 29 | return user; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/modules/auth/auth.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { JwtModule } from '@nestjs/jwt'; 3 | import { PassportModule } from '@nestjs/passport'; 4 | import { ConfigModule, ConfigService } from '@nestjs/config'; 5 | import { UserModule } from '../user'; 6 | import { AuthService } from './auth.service'; 7 | import { JwtStrategy } from './jwt.strategy'; 8 | import { AuthController } from './auth.controller'; 9 | 10 | @Module({ 11 | imports: [ 12 | UserModule, 13 | ConfigModule, 14 | PassportModule.register({ defaultStrategy: 'jwt' }), 15 | JwtModule.registerAsync({ 16 | imports: [ConfigModule], 17 | useFactory: async (configService: ConfigService) => { 18 | return { 19 | secret: configService.get('JWT_SECRET_KEY'), 20 | signOptions: { 21 | ...(configService.get('JWT_EXPIRATION_TIME') 22 | ? { 23 | expiresIn: Number(configService.get('JWT_EXPIRATION_TIME')), 24 | } 25 | : {}), 26 | }, 27 | }; 28 | }, 29 | inject: [ConfigService], 30 | }), 31 | ], 32 | controllers: [AuthController], 33 | providers: [AuthService, JwtStrategy], 34 | exports: [PassportModule.register({ defaultStrategy: 'jwt' })], 35 | }) 36 | export class AuthModule {} 37 | -------------------------------------------------------------------------------- /src/modules/user/entity/user.entity.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Entity, 3 | Column, 4 | PrimaryGeneratedColumn, 5 | CreateDateColumn, 6 | UpdateDateColumn, 7 | DeleteDateColumn, 8 | } from 'typeorm'; 9 | import { PasswordTransformer } from '../password.transformer'; 10 | import { AppRoles } from '../../common/enum/roles.enum'; 11 | 12 | @Entity({ 13 | name: 'users', 14 | }) 15 | export class UserEntity { 16 | /** 17 | * UUID column 18 | */ 19 | @PrimaryGeneratedColumn('uuid') 20 | id: string; 21 | 22 | /** 23 | * Unique username column 24 | */ 25 | @Column({ length: 255, unique: true }) 26 | username: string; 27 | 28 | /** 29 | * Name column 30 | */ 31 | @Column({ type: 'text' }) 32 | name: string; 33 | 34 | /** 35 | * Email colum 36 | */ 37 | @Column({ type: 'text', unique: true }) 38 | email: string; 39 | 40 | @Column({ 41 | type: 'simple-array', 42 | enum: AppRoles, 43 | default: AppRoles.DEFAULT, 44 | }) 45 | roles: AppRoles[]; 46 | 47 | /** 48 | * created date column 49 | */ 50 | @CreateDateColumn() 51 | createdDate: Date; 52 | 53 | /** 54 | * updated date column 55 | */ 56 | @UpdateDateColumn() 57 | updatedDate: Date; 58 | 59 | /** 60 | * delete date column 61 | */ 62 | @DeleteDateColumn() 63 | deletedDate: Date; 64 | 65 | /** 66 | * Password column 67 | */ 68 | @Column({ 69 | name: 'password', 70 | length: 255, 71 | transformer: new PasswordTransformer(), 72 | }) 73 | password: string; 74 | 75 | /** 76 | * Omit password from query selection 77 | */ 78 | toJSON() { 79 | const { password, ...self } = this; 80 | return self; 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/modules/common/validator/unique.validator.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { InjectConnection } from '@nestjs/typeorm'; 3 | import { Connection, EntitySchema, FindConditions, ObjectType } from 'typeorm'; 4 | import { 5 | ValidatorConstraint, 6 | ValidatorConstraintInterface, 7 | ValidationArguments, 8 | ValidationOptions, 9 | registerDecorator, 10 | } from 'class-validator'; 11 | 12 | @Injectable() 13 | @ValidatorConstraint({ name: 'unique', async: true }) 14 | export class UniqueValidator implements ValidatorConstraintInterface { 15 | constructor(@InjectConnection() private readonly connection: Connection) {} 16 | 17 | public async validate(value: string, args: UniqueValidationArguments) { 18 | const [EntityClass, findCondition = args.property] = args.constraints; 19 | return ( 20 | (await this.connection.getRepository(EntityClass).count({ 21 | where: 22 | typeof findCondition === 'function' 23 | ? findCondition(args) 24 | : { 25 | [findCondition || args.property]: value, 26 | }, 27 | })) <= 0 28 | ); 29 | } 30 | 31 | defaultMessage(args: ValidationArguments) { 32 | const [EntityClass] = args.constraints; 33 | const entity = EntityClass.name || 'Entity'; 34 | return `${entity} with the same ${args.property} already exists`; 35 | } 36 | } 37 | 38 | type UniqueValidationConstraints = [ 39 | ObjectType | EntitySchema | string, 40 | ((validationArguments: ValidationArguments) => FindConditions) | keyof E, 41 | ]; 42 | interface UniqueValidationArguments extends ValidationArguments { 43 | constraints: UniqueValidationConstraints; 44 | } 45 | 46 | export function Unique( 47 | constraints: Partial>, 48 | validationOptions?: ValidationOptions, 49 | ) { 50 | return function (object: Object, propertyName: string) { 51 | registerDecorator({ 52 | target: object.constructor, 53 | propertyName: propertyName, 54 | options: validationOptions, 55 | constraints, 56 | validator: UniqueValidator, 57 | }); 58 | }; 59 | } 60 | -------------------------------------------------------------------------------- /src/modules/common/validator/exists.validator.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { InjectConnection } from '@nestjs/typeorm'; 3 | import { Connection, EntitySchema, FindConditions, ObjectType } from 'typeorm'; 4 | import { 5 | ValidatorConstraint, 6 | ValidatorConstraintInterface, 7 | ValidationArguments, 8 | ValidationOptions, 9 | registerDecorator, 10 | } from 'class-validator'; 11 | 12 | @Injectable() 13 | @ValidatorConstraint({ name: 'exists', async: true }) 14 | export class ExistsValidator implements ValidatorConstraintInterface { 15 | constructor(@InjectConnection() private readonly connection: Connection) {} 16 | 17 | public async validate(value: string, args: ExistsValidationArguments) { 18 | const [EntityClass, findCondition = args.property] = args.constraints; 19 | return ( 20 | (await this.connection.getRepository(EntityClass).count({ 21 | where: 22 | typeof findCondition === 'function' 23 | ? findCondition(args) 24 | : { 25 | [findCondition || args.property]: value, 26 | }, 27 | })) > 0 28 | ); 29 | } 30 | 31 | defaultMessage(args: ValidationArguments) { 32 | const [EntityClass] = args.constraints; 33 | const entity = EntityClass.name || 'Entity'; 34 | return `The selected ${args.property} does not exist in ${entity} entity`; 35 | } 36 | } 37 | 38 | type ExistsValidationConstraints = [ 39 | ObjectType | EntitySchema | string, 40 | ((validationArguments: ValidationArguments) => FindConditions) | keyof E, 41 | ]; 42 | interface ExistsValidationArguments extends ValidationArguments { 43 | constraints: ExistsValidationConstraints; 44 | } 45 | 46 | export function Exists( 47 | constraints: Partial>, 48 | validationOptions?: ValidationOptions, 49 | ) { 50 | return function (object: Object, propertyName: string) { 51 | registerDecorator({ 52 | target: object.constructor, 53 | propertyName: propertyName, 54 | options: validationOptions, 55 | constraints, 56 | validator: ExistsValidator, 57 | }); 58 | }; 59 | } 60 | -------------------------------------------------------------------------------- /src/modules/auth/auth.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Body, Post, Get, Request } from '@nestjs/common'; 2 | import { ApiResponse, ApiTags, ApiBearerAuth } from '@nestjs/swagger'; 3 | import { UsersService } from '../user'; 4 | import { Public } from '../common/decorator/public.decorator'; 5 | import { AuthService } from './auth.service'; 6 | import { LoginPayload } from './payloads/login.payload'; 7 | import { ResetPayload } from './payloads/reset.payload'; 8 | import { RegisterPayload } from './payloads/register.payload'; 9 | 10 | @Controller('api/v1/auth') 11 | @ApiTags('Authentication') 12 | export class AuthController { 13 | /** 14 | * Constructor 15 | * @param authService auth service 16 | * @param userService user service 17 | */ 18 | constructor( 19 | private readonly authService: AuthService, 20 | private readonly userService: UsersService, 21 | ) {} 22 | 23 | /** 24 | * Login User 25 | * @param payload username, password 26 | * @return {token} including expire time, jwt token and user info 27 | */ 28 | @Public() 29 | @Post('login') 30 | @ApiResponse({ status: 201, description: 'Successful Login' }) 31 | @ApiResponse({ status: 400, description: 'Bad Request' }) 32 | @ApiResponse({ status: 401, description: 'Unauthorized' }) 33 | async login(@Body() payload: LoginPayload): Promise { 34 | const user = await this.authService.validateUser(payload); 35 | return await this.authService.createToken(user); 36 | } 37 | 38 | /** 39 | * Change user password 40 | * @param payload change password payload 41 | */ 42 | @Public() 43 | @Post('changePassword') 44 | @ApiResponse({ status: 201, description: 'Successful Reset' }) 45 | @ApiResponse({ status: 400, description: 'Bad Request' }) 46 | @ApiResponse({ status: 401, description: 'Unauthorized' }) 47 | async resetPassword(@Body() payload: ResetPayload): Promise { 48 | const user = await this.userService.changPassword(payload); 49 | return user.toJSON(); 50 | } 51 | 52 | /** 53 | * Register user 54 | * @param payload register payload 55 | */ 56 | @ApiBearerAuth() 57 | @Post('register') 58 | @ApiResponse({ status: 201, description: 'Successful Registration' }) 59 | @ApiResponse({ status: 400, description: 'Bad Request' }) 60 | @ApiResponse({ status: 401, description: 'Unauthorized' }) 61 | async register(@Body() payload: RegisterPayload): Promise { 62 | return await this.userService.create(payload); 63 | } 64 | 65 | /** 66 | * Get request's user info 67 | * @param request express request 68 | */ 69 | @ApiBearerAuth() 70 | @Get('me') 71 | @ApiResponse({ status: 200, description: 'Successful Response' }) 72 | @ApiResponse({ status: 401, description: 'Unauthorized' }) 73 | async getLoggedInUser(@Request() request): Promise { 74 | return await this.userService.getByUsername(request.user.username); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/modules/user/user.controller.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Body, 3 | Controller, 4 | Delete, 5 | Get, 6 | Param, 7 | ParseIntPipe, 8 | Put, 9 | Query, 10 | } from '@nestjs/common'; 11 | import { ApiBearerAuth, ApiQuery, ApiResponse, ApiTags } from '@nestjs/swagger'; 12 | import { UsersService } from './user.service'; 13 | import { Pagination } from 'nestjs-typeorm-paginate'; 14 | import { UserEntity } from './entity/user.entity'; 15 | import { UUIDType } from '../common/validator/FindOneUUID.validator'; 16 | import { UpdatePayload } from './payloads/update.payload'; 17 | import { Public } from '../common/decorator/public.decorator'; 18 | import { Roles } from '../common/decorator/roles.decorator'; 19 | import { AppRoles } from '../common/enum/roles.enum'; 20 | 21 | @Controller('api/v1/user') 22 | @ApiTags('User') 23 | export class UserController { 24 | /** 25 | * User controller constructor 26 | * @param userService user service 27 | */ 28 | constructor(private readonly userService: UsersService) {} 29 | 30 | /** 31 | * Public endpoints (Marked by @Public() ) all users with pagination options 32 | * @param page page number 33 | * @param limit items limit 34 | */ 35 | @Public() 36 | @Get() 37 | @ApiQuery({ name: 'page', required: true, example: '0' }) 38 | @ApiQuery({ name: 'limit', required: true, example: '0' }) 39 | @ApiResponse({ status: 200, description: 'Successful Request' }) 40 | @ApiResponse({ status: 400, description: 'Bad Request' }) 41 | @ApiResponse({ status: 401, description: 'Unauthorized' }) 42 | async getAll( 43 | @Query('page', ParseIntPipe) page = 1, 44 | @Query('limit', ParseIntPipe) limit = 10, 45 | ): Promise> { 46 | limit = limit > 100 ? 100 : limit; 47 | return await this.userService.getAll({ 48 | page, 49 | limit, 50 | }); 51 | } 52 | 53 | /** 54 | * Get user by id 55 | * @param id id in UUID 56 | */ 57 | @ApiBearerAuth() 58 | @Get(':id') 59 | @ApiResponse({ status: 200, description: 'Successful ' }) 60 | @ApiResponse({ status: 400, description: 'Bad Request' }) 61 | @ApiResponse({ status: 401, description: 'Unauthorized' }) 62 | async getUserById(@Param() id: UUIDType): Promise { 63 | return await this.userService.get(id); 64 | } 65 | 66 | /** 67 | * Update user by Id 68 | * @param id id in UUID 69 | * @param updatePayload update payload with optional parameters 70 | */ 71 | @ApiBearerAuth() 72 | @Put(':id') 73 | @ApiResponse({ status: 200, description: 'Successful ' }) 74 | @ApiResponse({ status: 400, description: 'Bad Request' }) 75 | @ApiResponse({ status: 401, description: 'Unauthorized' }) 76 | async update( 77 | @Param() id: UUIDType, 78 | @Body() updatePayload: UpdatePayload, 79 | ): Promise { 80 | return await this.userService.update(id, updatePayload); 81 | } 82 | 83 | /** 84 | * Delete user by Id 85 | * @param id id in UUID 86 | */ 87 | @ApiBearerAuth() 88 | @Roles(AppRoles.ADMINS) 89 | @Delete(':id') 90 | @ApiResponse({ status: 200, description: 'Delete Profile Request Received' }) 91 | @ApiResponse({ status: 400, description: 'Delete Profile Request Failed' }) 92 | async delete(@Param() id: UUIDType): Promise { 93 | return await this.userService.delete(id); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /src/modules/user/user.service.ts: -------------------------------------------------------------------------------- 1 | import { 2 | BadRequestException, 3 | Body, 4 | Injectable, 5 | NotAcceptableException, 6 | Param, 7 | UnauthorizedException, 8 | } from '@nestjs/common'; 9 | import { InjectRepository } from '@nestjs/typeorm'; 10 | import { Repository } from 'typeorm'; 11 | import { UserEntity } from './entity/user.entity'; 12 | import { Hash } from '../../utils/Hash'; 13 | import { 14 | IPaginationOptions, 15 | paginate, 16 | Pagination, 17 | } from 'nestjs-typeorm-paginate'; 18 | import { UUIDType } from '../common/validator/FindOneUUID.validator'; 19 | import { ResetPayload } from '../auth/payloads/reset.payload'; 20 | import { UpdatePayload } from './payloads/update.payload'; 21 | import { RegisterPayload } from '../auth/payloads/register.payload'; 22 | 23 | @Injectable() 24 | export class UsersService { 25 | constructor( 26 | @InjectRepository(UserEntity) 27 | private readonly userRepository: Repository, 28 | ) {} 29 | 30 | async get(@Param() id: UUIDType) { 31 | return this.userRepository.findOne(id); 32 | } 33 | 34 | async getByUsername(username: string) { 35 | return await this.userRepository.findOne({ username: username }); 36 | } 37 | 38 | async update( 39 | @Param() id: UUIDType, 40 | @Body() updatePayload: UpdatePayload, 41 | ): Promise { 42 | const admin = await this.userRepository.findOne(id); 43 | const updated = Object.assign(admin, updatePayload); 44 | delete updated.password; 45 | try { 46 | return await this.userRepository.save(updated); 47 | } catch (e) { 48 | throw new NotAcceptableException('Username or Email already exists!'); 49 | } 50 | } 51 | 52 | async getAll(options: IPaginationOptions): Promise> { 53 | const queryBuilder = await this.userRepository.createQueryBuilder('a'); 54 | queryBuilder.orderBy('a.updatedDate', 'DESC'); 55 | return paginate(queryBuilder, options); 56 | } 57 | 58 | async changPassword(payload: ResetPayload): Promise { 59 | const user = await this.getByUsername(payload.username); 60 | if (!user || !Hash.compare(payload.currentPassword, user.password)) { 61 | throw new UnauthorizedException('Invalid credentials!'); 62 | } 63 | await this.userRepository 64 | .createQueryBuilder('users') 65 | .update(UserEntity) 66 | .set({ password: payload.newPassword }) 67 | .where('username =:username', { username: payload.username }) 68 | .execute(); 69 | return user; 70 | } 71 | 72 | async create(payload: RegisterPayload) { 73 | const user = await this.getByUsername(payload.username); 74 | if (user) { 75 | throw new NotAcceptableException( 76 | 'Admin with provided username already created.', 77 | ); 78 | } 79 | return await this.userRepository.save(this.userRepository.create(payload)); 80 | } 81 | 82 | async delete(@Param() id: UUIDType): Promise { 83 | const user = await this.userRepository.findOne(id); 84 | const deleted = await this.userRepository.delete(id); 85 | if (deleted.affected === 1) { 86 | return { message: `Deleted ${user.username} from records` }; 87 | } else { 88 | throw new BadRequestException( 89 | `Failed to delete a profile by the name of ${user.username}.`, 90 | ); 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "tfd-nest-template", 3 | "version": "1.0.0", 4 | "description": "TFD Nest Boilerplate", 5 | "author": "KimAng Kheang", 6 | "license": "GPL-3.0-or-later", 7 | "scripts": { 8 | "prebuild": "rimraf dist", 9 | "build": "nest build", 10 | "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", 11 | "start": "nest start", 12 | "start:dev": "nodemon", 13 | "start:debug": "nodemon --config nodemon-debug.json", 14 | "start:prod": "node dist/main", 15 | "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", 16 | "test": "jest", 17 | "test:watch": "jest --watch", 18 | "test:cov": "jest --coverage", 19 | "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", 20 | "test:e2e": "jest --config ./test/jest-e2e.json", 21 | "ts-typeorm": "ts-node -r tsconfig-paths/register ./node_modules/.bin/typeorm", 22 | "fixture:generate": "fixtures ./src/fixtures --config ./ormconfig.js --sync --require=ts-node/register --require=tsconfig-paths/register", 23 | "migration:create": "yarn ts-typeorm migration:create -d src/migrations", 24 | "migration:generate": "yarn ts-typeorm migration:generate -d src/migrations", 25 | "migration:run": "yarn ts-typeorm migration:run", 26 | "migration:revert": "yarn ts-typeorm migration:revert" 27 | }, 28 | "dependencies": { 29 | "@nest-auth/redis": "^0.3.0", 30 | "@nestjs/common": "^8.0.0", 31 | "@nestjs/config": "^1.0.1", 32 | "@nestjs/core": "^8.0.0", 33 | "@nestjs/jwt": "^8.0.0", 34 | "@nestjs/passport": "^8.0.1", 35 | "@nestjs/platform-express": "^8.0.0", 36 | "@nestjs/swagger": "^5.0.9", 37 | "@nestjs/typeorm": "^8.0.2", 38 | "@types/bcrypt": "^3.0.0", 39 | "bcrypt": "^5.0.1", 40 | "cache-manager": "^3.4.4", 41 | "cache-manager-redis-store": "^2.0.0", 42 | "class-transformer": "^0.4.0", 43 | "class-validator": "^0.13.1", 44 | "dotenv": "^10.0.0", 45 | "helmet": "^4.6.0", 46 | "nestjs-typeorm-paginate": "^2.6.0", 47 | "passport": "^0.4.1", 48 | "passport-jwt": "^4.0.0", 49 | "pg": "^8.7.1", 50 | "randomstring": "^1.2.1", 51 | "reflect-metadata": "^0.1.13", 52 | "rimraf": "^3.0.2", 53 | "rxjs": "^7.2.0", 54 | "swagger-ui-express": "^4.1.6", 55 | "typeorm": "^0.2.36" 56 | }, 57 | "devDependencies": { 58 | "@nestjs/cli": "^8.0.0", 59 | "@nestjs/schematics": "^8.0.0", 60 | "@nestjs/testing": "^8.0.0", 61 | "@types/cache-manager": "^3.4.2", 62 | "@types/express": "^4.17.13", 63 | "@types/jest": "^26.0.24", 64 | "@types/node": "^16.0.0", 65 | "@types/supertest": "^2.0.11", 66 | "@types/swagger-ui-express": "^4.1.2", 67 | "@typescript-eslint/eslint-plugin": "^4.28.2", 68 | "@typescript-eslint/parser": "^4.28.2", 69 | "eslint": "^7.30.0", 70 | "eslint-config-prettier": "^8.3.0", 71 | "eslint-plugin-prettier": "^3.4.0", 72 | "jest": "27.0.6", 73 | "nodemon": "^2.0.12", 74 | "prettier": "^2.3.2", 75 | "supertest": "^6.1.3", 76 | "ts-jest": "^27.0.3", 77 | "ts-loader": "^9.2.3", 78 | "ts-node": "^10.0.0", 79 | "tsconfig-paths": "^3.10.1", 80 | "typeorm-fixtures-cli": "^1.9.1", 81 | "typescript": "^4.3.5" 82 | }, 83 | "jest": { 84 | "moduleFileExtensions": [ 85 | "js", 86 | "json", 87 | "ts" 88 | ], 89 | "rootDir": "src", 90 | "testRegex": ".*\\.spec\\.ts$", 91 | "transform": { 92 | "^.+\\.(t|j)s$": "ts-jest" 93 | }, 94 | "collectCoverageFrom": [ 95 | "**/*.(t|j)s" 96 | ], 97 | "coverageDirectory": "../coverage", 98 | "testEnvironment": "node" 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { CacheModule, Module } from '@nestjs/common'; 2 | import { TypeOrmModule, TypeOrmModuleAsyncOptions } from '@nestjs/typeorm'; 3 | import { AppController } from './app.controller'; 4 | import { AppService } from './app.service'; 5 | import { APP_GUARD, APP_INTERCEPTOR } from '@nestjs/core'; 6 | import { TimeoutInterceptor } from '../modules/common/interceptor/timeout.interceptor'; 7 | import * as redisStore from 'cache-manager-redis-store'; 8 | import { ConfigModule, ConfigService } from '@nestjs/config'; 9 | import { JwtAuthGuard } from '../modules/auth/jwt-guard'; 10 | import { CommonModule } from '../modules/common/common.module'; 11 | import { AuthModule } from '../modules/auth/auth.module'; 12 | import { UserModule } from '../modules/user'; 13 | import { LoggingInterceptor } from '../modules/common/interceptor/logging.interceptor'; 14 | import { RolesGuard } from '../modules/common/guard/roles.guard'; 15 | @Module({ 16 | imports: [ 17 | ConfigModule.forRoot({ 18 | ignoreEnvFile: process.env.NODE_ENV === 'production', 19 | }), 20 | TypeOrmModule.forRootAsync({ 21 | imports: [ConfigModule], 22 | inject: [ConfigService], 23 | useFactory: (configService: ConfigService) => { 24 | if (process.env.NODE_ENV === 'development') { 25 | return { 26 | type: configService.get('DB_TYPE'), 27 | host: configService.get('DB_HOST'), 28 | port: configService.get('DB_PORT'), 29 | username: configService.get('DB_USERNAME'), 30 | password: configService.get('DB_PASSWORD'), 31 | database: configService.get('DB_DATABASE'), 32 | entities: [__dirname + './../**/**.entity{.ts,.js}'], 33 | subscribers: [__dirname + './../**/**/*.subscriber.{ts,js}'], 34 | synchronize: configService.get('DB_SYNC'), 35 | retryAttempts: 20, 36 | } as TypeOrmModuleAsyncOptions; 37 | } 38 | if (process.env.NODE_ENV === 'production') { 39 | /** 40 | * Use database url in production instead 41 | */ 42 | return { 43 | type: configService.get('DB_TYPE'), 44 | url: configService.get('DATABASE_URL'), 45 | entities: [__dirname + './../**/**.entity{.ts,.js}'], 46 | subscribers: [__dirname + './../**/**/*.subscriber.{ts,js}'], 47 | synchronize: configService.get('DB_SYNC'), 48 | ssl: true, 49 | retryAttempts: 20, 50 | extra: { 51 | ssl: { 52 | rejectUnauthorized: false, 53 | }, 54 | }, 55 | } as TypeOrmModuleAsyncOptions; 56 | } 57 | }, 58 | }), 59 | CacheModule.registerAsync({ 60 | imports: [ConfigModule], 61 | inject: [ConfigService], 62 | useFactory: async (configService: ConfigService) => { 63 | if (process.env.NODE_ENV === 'development') { 64 | return { 65 | ttl: configService.get('CACHE_TTL'), // seconds 66 | max: configService.get('CACHE_MAX'), // maximum number of items in cache 67 | store: redisStore, 68 | host: configService.get('CACHE_HOST'), 69 | port: configService.get('CACHE_PORT'), 70 | }; 71 | } 72 | if (process.env.NODE_ENV === 'production') { 73 | /** 74 | * Use redis url in production instead 75 | */ 76 | return { 77 | ttl: configService.get('CACHE_TTL'), // seconds 78 | max: configService.get('CACHE_MAX'), // maximum number of items in cache 79 | store: redisStore, 80 | url: configService.get('REDIS_URL'), 81 | }; 82 | } 83 | }, 84 | }), 85 | AuthModule, 86 | UserModule, 87 | CommonModule, 88 | ], 89 | controllers: [AppController], 90 | providers: [ 91 | AppService, 92 | { 93 | provide: APP_GUARD, 94 | useClass: JwtAuthGuard, 95 | }, 96 | { 97 | provide: APP_GUARD, 98 | useClass: RolesGuard, 99 | }, 100 | { 101 | provide: APP_INTERCEPTOR, 102 | useClass: TimeoutInterceptor, 103 | }, 104 | { 105 | provide: APP_INTERCEPTOR, 106 | useClass: LoggingInterceptor, 107 | }, 108 | ], 109 | }) 110 | export class AppModule {} 111 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | TFD Logo 3 |

4 | 5 | 6 |

A Nest.js boilerplate by TFD for building scalable API.

7 |

8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | NPM Version 18 | Package License 19 | YouTube Channel Subscribers 20 |
21 | ABA 22 | TFD Logo 23 |

24 | 25 |

Scalable NestJS v8 Boilerplate 26 | 30 | Nest Logo 35 | 36 |

37 | 38 | ## Features 39 | 40 | This is a NestJS boilerplate code with preconfigured libraries and packages with the following features: 41 | - One-click setup with [Docker](https://www.docker.com/) 42 | - [Typeorm](https://typeorm.io/) for Object–relational mapping, use **Postgres DB** by default 43 | - Sample data generation with typeorm-fixture (generate fixture based on .yaml file), visit [RobinCK/typeorm-fixtures](https://github.com/RobinCK/typeorm-fixtures). 44 | - Preconfigured Caching Mechanism ([Redis Store](https://redis.io/)) 45 | - [Swagger UI](https://swagger.io/) (Express) 46 | - Authentication with JWT 47 | - Basic RBAC implementation ( You'll have to attach user object to your request manually ) 48 | - Basic request time logger 49 | 50 | ## Setup Guide 51 | **Be aware that** putting **DB_SYNC** to true in your production may result in irreversible data lost. 52 | **DB_SYNC** should only be put to true in development to skip the necessity of doing migrations. 53 | ### Without Docker 54 | 55 | - Create .env file with command `cp .env.example .env` and replace with your own env variable 56 | - `yarn install` 57 | - `yarn start` (Your API will be exposed through port 3000) 58 | 59 | ### With Docker 60 | Run the following scripts for UNIX (Mac,Linux) 61 | ```bash 62 | $ cp .env.example .env 63 | $ docker-compose up -d 64 | ``` 65 | DOS(Windows) 66 | ```bash 67 | $ copy .env.example .env 68 | $ docker-compose up -d 69 | ``` 70 | ## Available Services with Docker Container 71 | Once you managed to run the docker container, the following service will be available: 72 | - Nginx will serve as a reverse proxy and will be exposed through port 80 (http://localhost) 73 | - Swagger API Docs (http://localhost/api/docs/) 74 | - Database (Postgres 12) (http://localhost:5432) 75 | - Redis Store (Only Available in internal docker network) (http://0.0.0.0:6379) 76 | - NestJs Server (Only Available in internal docker network) (http://0.0.0.0:3000) 77 | ## Migration Guide 78 | New migration with typeorm-cli: 79 | ```bash 80 | $ docker exec -it tfd-nest yarn migration:create -n {CreateTable} 81 | ``` 82 | Migration file will be inside `src/migrations`. 83 | Note that you will have to write migration code inside up and down method on your own. 84 | To generate migration for new database or from the changes in database schema(entities) use: 85 | ```bash 86 | $ docker exec -it tfd-nest yarn migration:generate -n {GenerateTable} 87 | ``` 88 | #### Run Migrations 89 | ```bash 90 | $ docker exec -it tfd-nest yarn migration:run 91 | ``` 92 | #### Revert Migrations 93 | ```bash 94 | $ docker exec -it tfd-nest yarn migration:revert 95 | ``` 96 | 97 | ## Generate Fixture 98 | Fixture lets you play around with sample data. It's not 99 | recommended generating in production since it may erase real data. 100 | visit [RobinCK/typeorm-fixtures](https://github.com/RobinCK/typeorm-fixtures) for more info. 101 | #### Generate Sample Data 102 | Make sure the docker container is running 103 | ```bash 104 | $ docker exec -it tfd-nest yarn fixture:generate 105 | ``` 106 | ## Donation 107 | 108 | Kindly donate to the following bank account (Cambodia) if you want to support our works. 109 | 110 | TFD Logo 111 | 112 | #### KHEANG KIM ANG 113 | #### 001 821 043 114 | You can also donate with **Visa Direct**. 115 | 116 | TFD Logo 117 | 118 | #### 4026 4503 2163 1102 119 | 120 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | tfd-nest-template 635 | Copyright (C) 2021 Oberleutnant KimAng 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 2021 Oberleutnant KimAng 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------