refactor nest app to server folder

This commit is contained in:
Roland Schneider
2025-11-06 17:24:11 +01:00
parent ea74d34363
commit 532299c864
42 changed files with 6 additions and 6 deletions

56
server/.gitignore vendored Normal file
View File

@@ -0,0 +1,56 @@
# compiled output
dist
node_modules
build
# Logs
logs
*.log
npm-debug.log*
pnpm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
coverage
.nyc_output
# IDEs and editors
.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# temp directory
.temp
.tmp
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

4
server/.prettierrc Normal file
View File

@@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "all"
}

98
server/README.md Normal file
View File

@@ -0,0 +1,98 @@
<p align="center">
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a>
</p>
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
[circleci-url]: https://circleci.com/gh/nestjs/nest
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
<p align="center">
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg" alt="Donate us"/></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow" alt="Follow us on Twitter"></a>
</p>
<!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
[![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->
## Description
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
## Project setup
```bash
$ npm install
```
## Compile and run the project
```bash
# development
$ npm run start
# watch mode
$ npm run start:dev
# production mode
$ npm run start:prod
```
## Run tests
```bash
# unit tests
$ npm run test
# e2e tests
$ npm run test:e2e
# test coverage
$ npm run test:cov
```
## Deployment
When you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the [deployment documentation](https://docs.nestjs.com/deployment) for more information.
If you are looking for a cloud-based platform to deploy your NestJS application, check out [Mau](https://mau.nestjs.com), our official platform for deploying NestJS applications on AWS. Mau makes deployment straightforward and fast, requiring just a few simple steps:
```bash
$ npm install -g @nestjs/mau
$ mau deploy
```
With Mau, you can deploy your application in just a few clicks, allowing you to focus on building features rather than managing infrastructure.
## Resources
Check out a few resources that may come in handy when working with NestJS:
- Visit the [NestJS Documentation](https://docs.nestjs.com) to learn more about the framework.
- For questions and support, please visit our [Discord channel](https://discord.gg/G7Qnnhy).
- To dive deeper and get more hands-on experience, check out our official video [courses](https://courses.nestjs.com/).
- Deploy your application to AWS with the help of [NestJS Mau](https://mau.nestjs.com) in just a few clicks.
- Visualize your application graph and interact with the NestJS application in real-time using [NestJS Devtools](https://devtools.nestjs.com).
- Need help with your project (part-time to full-time)? Check out our official [enterprise support](https://enterprise.nestjs.com).
- To stay in the loop and get updates, follow us on [X](https://x.com/nestframework) and [LinkedIn](https://linkedin.com/company/nestjs).
- Looking for a job, or have a job to offer? Check out our official [Jobs board](https://jobs.nestjs.com).
## Support
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
## Stay in touch
- Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)
## License
Nest is [MIT licensed](https://github.com/nestjs/nest/blob/master/LICENSE).

15
server/api.http Normal file
View File

@@ -0,0 +1,15 @@
POST http://localhost:3000/auth/login
Content-Type: application/json
{
"username": "admin",
"password": "123456"
}
> {% client.global.set("auth_token", response.body.access_token); %}
### GET request with parameter
GET http://localhost:3000/users
Accept: application/json
Authorization: Bearer {{auth_token}}

35
server/eslint.config.mjs Normal file
View File

@@ -0,0 +1,35 @@
// @ts-check
import eslint from '@eslint/js';
import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended';
import globals from 'globals';
import tseslint from 'typescript-eslint';
export default tseslint.config(
{
ignores: ['eslint.config.mjs'],
},
eslint.configs.recommended,
...tseslint.configs.recommendedTypeChecked,
eslintPluginPrettierRecommended,
{
languageOptions: {
globals: {
...globals.node,
...globals.jest,
},
sourceType: 'commonjs',
parserOptions: {
projectService: true,
tsconfigRootDir: import.meta.dirname,
},
},
},
{
rules: {
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-floating-promises': 'warn',
'@typescript-eslint/no-unsafe-argument': 'warn',
"prettier/prettier": ["error", { endOfLine: "auto" }],
},
},
);

8
server/nest-cli.json Normal file
View File

@@ -0,0 +1,8 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true
}
}

11780
server/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

88
server/package.json Normal file
View File

@@ -0,0 +1,88 @@
{
"name": "dvbooking",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json",
"typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js",
"migration:generate": "npm run typeorm -- -d src/data-source.ts migration:generate src/migration/$npm_config_name",
"migration:run": "npm run typeorm -- -d src/data-source.ts migration:run"
},
"dependencies": {
"@nestjs/common": "^11.0.1",
"@nestjs/config": "^4.0.2",
"@nestjs/core": "^11.0.1",
"@nestjs/jwt": "^11.0.1",
"@nestjs/passport": "^11.0.5",
"@nestjs/platform-express": "^11.0.1",
"@nestjs/swagger": "^11.2.1",
"@nestjs/typeorm": "^11.0.0",
"bcrypt": "^5.1.1",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.0",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
"pg": "^8.16.3",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
"typeorm": "^0.3.27"
},
"devDependencies": {
"@eslint/eslintrc": "^3.2.0",
"@eslint/js": "^9.18.0",
"@nestjs/cli": "^11.0.0",
"@nestjs/schematics": "^11.0.0",
"@nestjs/testing": "^11.0.1",
"@types/bcrypt": "^5.0.2",
"@types/express": "^5.0.0",
"@types/jest": "^30.0.0",
"@types/node": "^22.10.7",
"@types/passport-jwt": "^4.0.0",
"@types/supertest": "^6.0.2",
"eslint": "^9.18.0",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-prettier": "^5.2.2",
"globals": "^16.0.0",
"jest": "^30.0.0",
"prettier": "^3.4.2",
"source-map-support": "^0.5.21",
"supertest": "^7.0.0",
"ts-jest": "^29.2.5",
"ts-loader": "^9.5.2",
"ts-node": "^10.9.2",
"tsconfig-paths": "^4.2.0",
"typescript": "^5.7.3",
"typescript-eslint": "^8.20.0"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}

View File

@@ -0,0 +1,22 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
});

View File

@@ -0,0 +1,12 @@
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
}

42
server/src/app.module.ts Normal file
View File

@@ -0,0 +1,42 @@
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { UserModule } from './user/user.module';
import { AuthModule } from './auth/auth.module';
import { User } from './entity/user';
import { UserGroup } from './entity/user-group';
import { UserRole } from './entity/user-role';
import { LoggerModule } from './logger/logger.module';
const moduleTypeOrm = TypeOrmModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (configService: ConfigService) => {
return {
type: 'postgres',
host: configService.get<string>('DATABASE_HOST'),
port: parseInt(configService.get<string>('DATABASE_PORT') as string, 10),
username: configService.get<string>('DATABASE_USER'),
password: configService.get<string>('DATABASE_PASS'),
database: configService.get<string>('DATABASE_NAME'),
entities: [User, UserGroup, UserRole],
logging: true,
// synchronize: true,
};
},
});
@Module({
imports: [
ConfigModule.forRoot(),
moduleTypeOrm,
UserModule,
AuthModule,
LoggerModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}

View File

@@ -0,0 +1,8 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}

View File

@@ -0,0 +1,13 @@
import { Controller, Post, Body, ValidationPipe } from '@nestjs/common';
import { AuthService } from './auth.service';
import { LoginRequestDto } from './dto/login-request.dto';
@Controller('auth')
export class AuthController {
constructor(private authService: AuthService) {}
@Post('login')
async login(@Body(new ValidationPipe()) body: LoginRequestDto) {
return await this.authService.login(body);
}
}

View File

@@ -0,0 +1,27 @@
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { UserModule } from '../user/user.module';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { JwtStrategy } from './jwt.strategy';
import { ConfigModule, ConfigService } from '@nestjs/config';
@Module({
imports: [
ConfigModule, // <--- Import ConfigModule here
UserModule,
PassportModule,
JwtModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (configService: ConfigService) => ({
secret: configService.get<string>('JWT_SECRET'),
signOptions: { expiresIn: '60m' },
}),
}),
],
providers: [AuthService, JwtStrategy],
controllers: [AuthController],
})
export class AuthModule {}

View File

@@ -0,0 +1,52 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { UserService } from '../user/user.service';
import { JwtService } from '@nestjs/jwt';
import * as bcrypt from 'bcrypt';
import { User } from '../entity/user';
import { LoginRequest, LoginResponse } from '../types';
@Injectable()
export class AuthService {
constructor(
private userService: UserService,
private jwtService: JwtService,
) {}
async validateUser(username: string, pass: string): Promise<User | null> {
const user = await this.userService.findByUsername(username, {
groups: {
roles: true,
},
});
if (user && (await bcrypt.compare(pass, user.password))) {
return user;
}
return null;
}
async login(loginData: LoginRequest): Promise<LoginResponse> {
const user: User | null = await this.validateUser(
loginData.username,
loginData.password,
);
if (!user) {
throw new UnauthorizedException();
}
const roles: Set<string> = new Set<string>();
for (const group of user.groups ?? []) {
for (const role of group.roles ?? []) {
roles.add(role.name);
}
}
const payload = {
username: user.username,
sub: user.id,
roles: Array.from(roles),
};
return {
access_token: this.jwtService.sign(payload),
};
}
}

View File

@@ -0,0 +1,12 @@
import { IsString } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
export class LoginRequestDto {
@IsString()
@ApiProperty()
username: string;
@IsString()
@ApiProperty()
password: string;
}

View File

@@ -0,0 +1,5 @@
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}

View File

@@ -0,0 +1,24 @@
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { ConfigService } from '@nestjs/config';
import { Role } from './role.enum';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(configService: ConfigService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: configService.get<string>('JWT_SECRET') as string,
});
}
validate(payload: { sub: string; username: string; roles: Role[] }) {
return {
userId: payload.sub,
username: payload.username,
roles: payload.roles,
};
}
}

View File

@@ -0,0 +1,4 @@
export enum Role {
User = 'user',
Admin = 'admin',
}

View File

@@ -0,0 +1,5 @@
import { SetMetadata } from '@nestjs/common';
import { Role } from './role.enum';
export const ROLES_KEY = 'roles';
export const Roles = (...roles: Role[]) => SetMetadata(ROLES_KEY, roles);

View File

@@ -0,0 +1,21 @@
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Role } from './role.enum';
import { ROLES_KEY } from './roles.decorator';
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const requiredRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [
context.getHandler(),
context.getClass(),
]);
if (!requiredRoles) {
return true;
}
const { user } = context.switchToHttp().getRequest();
return requiredRoles.some((role) => user.roles?.includes(role));
}
}

25
server/src/data-source.ts Normal file
View File

@@ -0,0 +1,25 @@
import 'reflect-metadata';
import { DataSource } from 'typeorm';
import { User } from './entity/user';
import * as dotenv from 'dotenv';
import { UserGroup } from './entity/user-group';
import { UserRole } from './entity/user-role';
dotenv.config();
export const AppDataSource = new DataSource({
type: 'postgres',
host: process.env.DATABASE_HOST,
port: parseInt(process.env.DATABASE_PORT as string, 10),
username: process.env.DATABASE_USER,
password: process.env.DATABASE_PASS,
database: process.env.DATABASE_NAME,
synchronize: false,
logging: false,
entities: [User, UserGroup, UserRole],
migrations: [
'src/migration/**/*.ts'
],
subscribers: [],
});

View File

@@ -0,0 +1,21 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
ManyToMany,
JoinTable,
} from 'typeorm';
import { UserRole } from './user-role';
@Entity()
export class UserGroup {
@PrimaryGeneratedColumn()
id: number;
@Column({ unique: true })
name: string;
@ManyToMany(() => UserRole)
@JoinTable()
roles: UserRole[];
}

View File

@@ -0,0 +1,10 @@
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity()
export class UserRole {
@PrimaryGeneratedColumn()
id: number;
@Column({ unique: true })
name: string;
}

27
server/src/entity/user.ts Normal file
View File

@@ -0,0 +1,27 @@
import {
Entity,
Column,
PrimaryGeneratedColumn,
ManyToMany,
JoinTable,
} from 'typeorm';
import { UserGroup } from './user-group';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
username: string;
@Column()
email: string;
@Column()
password: string;
@ManyToMany(() => UserGroup)
@JoinTable()
groups: UserGroup[];
}

View File

@@ -0,0 +1,24 @@
import { ConsoleLogger, Injectable } from '@nestjs/common';
@Injectable()
export class DvbookingLoggerService extends ConsoleLogger {
log(message: string, context?: string) {
super.log(message, context);
}
error(message: string, trace?: string, context?: string) {
super.error(message, trace, context);
}
warn(message: string, context?: string) {
super.warn(message, context);
}
debug(message: string, context?: string) {
super.debug(message, context);
}
verbose(message: string, context?: string) {
super.verbose(message, context);
}
}

View File

@@ -0,0 +1,9 @@
import { Global, Module } from '@nestjs/common';
import { DvbookingLoggerService } from './dvbooking-logger.service';
@Global()
@Module({
providers: [DvbookingLoggerService],
exports: [DvbookingLoggerService],
})
export class LoggerModule {}

21
server/src/main.ts Normal file
View File

@@ -0,0 +1,21 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { DvbookingLoggerService } from './logger/dvbooking-logger.service';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useLogger(app.get(DvbookingLoggerService));
const config = new DocumentBuilder()
.setTitle('DV Booking API')
.setDescription('The DV Booking API description')
.setVersion('1.0')
.addTag('dvbooking')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document);
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();

View File

@@ -0,0 +1,15 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class AddUserTable1761571888108 implements MigrationInterface {
name = 'AddUserTable1761571888108';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE TABLE "user" ("id" SERIAL NOT NULL, "username" character varying NOT NULL, "email" character varying NOT NULL, "password" character varying NOT NULL, CONSTRAINT "PK_cace4a159ff9f2512dd42373760" PRIMARY KEY ("id"))`,
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`DROP TABLE "user"`);
}
}

View File

@@ -0,0 +1,14 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class AddAdminUser1761581879633 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
// add dev user: admin:123456
await queryRunner.query(
`insert into "user" ( username, email, password) values ('admin','admin@test.com','$2a$12$sT7bIBfUdAvCzcwyppSX/uVd4EP6ORgWiEg7jqXvMKJErR5jWhnmO');`,
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query("delete from user where username='admin'");
}
}

View File

@@ -0,0 +1,75 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class AddRbac1761597406101 implements MigrationInterface {
name = 'AddRbac1761597406101';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE TABLE "user_role" ("id" SERIAL NOT NULL, "name" character varying NOT NULL, CONSTRAINT "UQ_31f96f2013b7ac833d7682bf021" UNIQUE ("name"), CONSTRAINT "PK_fb2e442d14add3cefbdf33c4561" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`CREATE TABLE "user_group" ("id" SERIAL NOT NULL, "name" character varying NOT NULL, CONSTRAINT "UQ_11b85d8d72220e3ca816d3e907a" UNIQUE ("name"), CONSTRAINT "PK_3c29fba6fe013ec8724378ce7c9" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`CREATE TABLE "user_group_roles_user_role" ("userGroupId" integer NOT NULL, "userRoleId" integer NOT NULL, CONSTRAINT "PK_ebde92504ad1d97331b6b64a6df" PRIMARY KEY ("userGroupId", "userRoleId"))`,
);
await queryRunner.query(
`CREATE INDEX "IDX_411df6d2b8a7e01aacc3c8a6ea" ON "user_group_roles_user_role" ("userGroupId") `,
);
await queryRunner.query(
`CREATE INDEX "IDX_9172c01a353d2db376e54ee91b" ON "user_group_roles_user_role" ("userRoleId") `,
);
await queryRunner.query(
`CREATE TABLE "user_groups_user_group" ("userId" integer NOT NULL, "userGroupId" integer NOT NULL, CONSTRAINT "PK_a4c39cf055515d3478562577ce4" PRIMARY KEY ("userId", "userGroupId"))`,
);
await queryRunner.query(
`CREATE INDEX "IDX_372e638c75644389a7832a604e" ON "user_groups_user_group" ("userId") `,
);
await queryRunner.query(
`CREATE INDEX "IDX_235ca434168087abe1c665fd37" ON "user_groups_user_group" ("userGroupId") `,
);
await queryRunner.query(
`ALTER TABLE "user_group_roles_user_role" ADD CONSTRAINT "FK_411df6d2b8a7e01aacc3c8a6eae" FOREIGN KEY ("userGroupId") REFERENCES "user_group"("id") ON DELETE CASCADE ON UPDATE CASCADE`,
);
await queryRunner.query(
`ALTER TABLE "user_group_roles_user_role" ADD CONSTRAINT "FK_9172c01a353d2db376e54ee91bb" FOREIGN KEY ("userRoleId") REFERENCES "user_role"("id") ON DELETE CASCADE ON UPDATE CASCADE`,
);
await queryRunner.query(
`ALTER TABLE "user_groups_user_group" ADD CONSTRAINT "FK_372e638c75644389a7832a604ed" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE`,
);
await queryRunner.query(
`ALTER TABLE "user_groups_user_group" ADD CONSTRAINT "FK_235ca434168087abe1c665fd375" FOREIGN KEY ("userGroupId") REFERENCES "user_group"("id") ON DELETE CASCADE ON UPDATE CASCADE`,
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "user_groups_user_group" DROP CONSTRAINT "FK_235ca434168087abe1c665fd375"`,
);
await queryRunner.query(
`ALTER TABLE "user_groups_user_group" DROP CONSTRAINT "FK_372e638c75644389a7832a604ed"`,
);
await queryRunner.query(
`ALTER TABLE "user_group_roles_user_role" DROP CONSTRAINT "FK_9172c01a353d2db376e54ee91bb"`,
);
await queryRunner.query(
`ALTER TABLE "user_group_roles_user_role" DROP CONSTRAINT "FK_411df6d2b8a7e01aacc3c8a6eae"`,
);
await queryRunner.query(
`DROP INDEX "public"."IDX_235ca434168087abe1c665fd37"`,
);
await queryRunner.query(
`DROP INDEX "public"."IDX_372e638c75644389a7832a604e"`,
);
await queryRunner.query(`DROP TABLE "user_groups_user_group"`);
await queryRunner.query(
`DROP INDEX "public"."IDX_9172c01a353d2db376e54ee91b"`,
);
await queryRunner.query(
`DROP INDEX "public"."IDX_411df6d2b8a7e01aacc3c8a6ea"`,
);
await queryRunner.query(`DROP TABLE "user_group_roles_user_role"`);
await queryRunner.query(`DROP TABLE "user_group"`);
await queryRunner.query(`DROP TABLE "user_role"`);
}
}

View File

@@ -0,0 +1,63 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class AddRbacToAdmin1761597689677 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
const idRoleAdmin = await this.doInsert(queryRunner, 'user_role', {
name: 'admin',
});
console.info('idRoleAdmin', idRoleAdmin);
const idRoleUserManagement = await this.doInsert(queryRunner, 'user_role', {
name: 'user_manager',
});
console.info('idRoleUserManagement', idRoleUserManagement);
const idGroupAdmin = await this.doInsert(queryRunner, 'user_group', {
name: 'admin',
});
console.info('idGroupAdmin', idGroupAdmin);
await this.doInsert(queryRunner, 'user_group_roles_user_role', {
userGroupId: idGroupAdmin,
userRoleId: idRoleAdmin,
});
await this.doInsert(queryRunner, 'user_group_roles_user_role', {
userGroupId: idGroupAdmin,
userRoleId: idRoleUserManagement,
});
const users: object[] = (await queryRunner.query(
`SELECT * FROM "user" WHERE "username" = $1`,
['admin'],
)) as object[];
let userId: number | undefined = undefined;
if (users?.length > 0) {
const user = users[0] as { id: number };
userId = user.id;
}
await this.doInsert(queryRunner, 'user_groups_user_group', {
userGroupId: idGroupAdmin,
userId: userId,
});
}
public async down(_queryRunner: QueryRunner): Promise<void> {
// await queryRunner.query(
}
private async doInsert(
queryRunner: QueryRunner,
table: string,
values: Record<string, any>,
): Promise<string> {
console.info("inserting values",values);
const insertResult = await queryRunner.manager
.createQueryBuilder()
.insert()
.into(table)
.values(values)
.execute();
return insertResult.raw[0]?.id as string;
}
}

11
server/src/types.ts Normal file
View File

@@ -0,0 +1,11 @@
export interface LoginRequest{
username: string;
password: string;
}
export interface LoginResponse{
access_token: string;
}

View File

@@ -0,0 +1,18 @@
import { IsString, IsEmail, MinLength } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
export class CreateUserDto {
@IsString()
@MinLength(3)
@ApiProperty()
username: string;
@IsEmail()
@ApiProperty()
email: string;
@IsString()
@MinLength(6)
@ApiProperty()
password: string;
}

View File

@@ -0,0 +1,24 @@
import { IsString, IsEmail, MinLength, IsOptional } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
export class UpdateUserDto {
@IsOptional()
@IsString()
@MinLength(3)
@ApiProperty()
username?: string;
@IsOptional()
@IsEmail()
@ApiProperty()
email?: string;
@IsOptional()
@IsString()
@MinLength(6)
@ApiProperty()
password?: string;
}

View File

@@ -0,0 +1,57 @@
import {
Controller,
Get,
Post,
Body,
Patch,
Param,
Delete,
UseGuards,
ValidationPipe,
} from '@nestjs/common';
import { UserService } from './user.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { User } from '../entity/user';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { Roles } from '../auth/roles.decorator';
import { Role } from '../auth/role.enum';
import { RolesGuard } from '../auth/roles.guard';
@Controller('users')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(Role.Admin)
export class UserController {
constructor(private readonly userService: UserService) {}
@Post()
create(
@Body(new ValidationPipe()) createUserDto: CreateUserDto,
): Promise<User> {
return this.userService.create(createUserDto);
}
@Get()
findAll(): Promise<User[]> {
return this.userService.findAll();
}
@Get(':id')
findOne(@Param('id') id: string): Promise<User | null> {
return this.userService.findOne(+id);
}
@Patch(':id')
update(
@Param('id') id: string,
@Body(new ValidationPipe()) updateUserDto: UpdateUserDto,
): Promise<User | null> {
return this.userService.update(+id, updateUserDto);
}
@Roles(Role.Admin)
@Delete(':id')
remove(@Param('id') id: string): Promise<void> {
return this.userService.remove(+id);
}
}

View File

@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserService } from './user.service';
import { UserController } from './user.controller';
import { User } from '../entity/user';
@Module({
imports: [TypeOrmModule.forFeature([User])],
providers: [UserService],
controllers: [UserController],
exports: [UserService],
})
export class UserModule {}

View File

@@ -0,0 +1,57 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../entity/user';
import * as bcrypt from 'bcrypt';
import { FindOptionsRelations } from 'typeorm/find-options/FindOptionsRelations';
import { DvbookingLoggerService } from '../logger/dvbooking-logger.service';
@Injectable()
export class UserService {
constructor(
@InjectRepository(User)
private usersRepository: Repository<User>,
private readonly logger: DvbookingLoggerService,
) {}
findAll(): Promise<User[]> {
this.logger.log('Finding all users', 'UserService');
return this.usersRepository.find();
}
findOne(id: number): Promise<User | null> {
this.logger.log(`Finding user with id: ${id}`, 'UserService');
return this.usersRepository.findOneBy({ id });
}
findByUsername(
username: string,
relations: FindOptionsRelations<User>,
): Promise<User | null> {
this.logger.log(`Finding user with username: ${username}`, 'UserService');
return this.usersRepository.findOne({ where: { username }, relations });
}
async create(user: Partial<User>): Promise<User> {
this.logger.log('Creating a new user', 'UserService');
if (user.password) {
user.password = await bcrypt.hash(user.password, 12);
}
const newUser = this.usersRepository.create(user);
return this.usersRepository.save(newUser);
}
async update(id: number, user: Partial<User>): Promise<User | null> {
this.logger.log(`Updating user with id: ${id}`, 'UserService');
if (user.password) {
user.password = await bcrypt.hash(user.password, 12);
}
await this.usersRepository.update(id, user);
return this.usersRepository.findOneBy({ id });
}
async remove(id: number): Promise<void> {
this.logger.log(`Removing user with id: ${id}`, 'UserService');
await this.usersRepository.delete(id);
}
}

View File

@@ -0,0 +1,25 @@
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import request from 'supertest';
import { App } from 'supertest/types';
import { AppModule } from './../src/app.module';
describe('AppController (e2e)', () => {
let app: INestApplication<App>;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
it('/ (GET)', () => {
return request(app.getHttpServer())
.get('/')
.expect(200)
.expect('Hello World!');
});
});

View File

@@ -0,0 +1,9 @@
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}

View File

@@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}

25
server/tsconfig.json Normal file
View File

@@ -0,0 +1,25 @@
{
"compilerOptions": {
"module": "nodenext",
"moduleResolution": "nodenext",
"resolvePackageJsonExports": true,
"esModuleInterop": true,
"isolatedModules": true,
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2023",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": true,
"forceConsistentCasingInFileNames": true,
"noImplicitAny": false,
"strictBindCallApply": false,
"noFallthroughCasesInSwitch": false
}
}