initial code stash
This commit is contained in:
commit
db68884824
25
.eslintrc.js
Normal file
25
.eslintrc.js
Normal file
@ -0,0 +1,25 @@
|
||||
module.exports = {
|
||||
parser: '@typescript-eslint/parser',
|
||||
parserOptions: {
|
||||
project: 'tsconfig.json',
|
||||
tsconfigRootDir : __dirname,
|
||||
sourceType: 'module',
|
||||
},
|
||||
plugins: ['@typescript-eslint/eslint-plugin'],
|
||||
extends: [
|
||||
'plugin:@typescript-eslint/recommended',
|
||||
'plugin:prettier/recommended',
|
||||
],
|
||||
root: true,
|
||||
env: {
|
||||
node: true,
|
||||
jest: true,
|
||||
},
|
||||
ignorePatterns: ['.eslintrc.js'],
|
||||
rules: {
|
||||
'@typescript-eslint/interface-name-prefix': 'off',
|
||||
'@typescript-eslint/explicit-function-return-type': 'off',
|
||||
'@typescript-eslint/explicit-module-boundary-types': 'off',
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
},
|
||||
};
|
40
.gitignore
vendored
Normal file
40
.gitignore
vendored
Normal file
@ -0,0 +1,40 @@
|
||||
# compiled output
|
||||
/dist
|
||||
/node_modules
|
||||
|
||||
# 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
|
||||
|
||||
# Secrets
|
||||
.env*
|
||||
/private
|
||||
/database
|
4
.prettierrc
Normal file
4
.prettierrc
Normal file
@ -0,0 +1,4 @@
|
||||
{
|
||||
"singleQuote": true,
|
||||
"trailingComma": "all"
|
||||
}
|
3
.vscode/settings.json
vendored
Normal file
3
.vscode/settings.json
vendored
Normal file
@ -0,0 +1,3 @@
|
||||
{
|
||||
"editor.formatOnSave": true
|
||||
}
|
74
README.md
Normal file
74
README.md
Normal file
@ -0,0 +1,74 @@
|
||||
<p align="center">
|
||||
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="200" 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://coveralls.io/github/nestjs/nest?branch=master" target="_blank"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#9" alt="Coverage" /></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"/></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"></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.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
$ npm install
|
||||
```
|
||||
|
||||
## Running the app
|
||||
|
||||
```bash
|
||||
# development
|
||||
$ docker run -it --rm --name homemanager-db -p 3306:3306 -v $PWD/database:/var/lib/mysql --env MARIADB_USER=homemanager --env MARIADB_PASSWORD=homemanager --env MARIADB_ROOT_PASSWORD=homemanager --env MARIADB_DATABASE=homemanager mariadb:latest
|
||||
$ npm run start
|
||||
|
||||
# watch mode
|
||||
$ npm run start:dev
|
||||
|
||||
# production mode
|
||||
$ npm run start:prod
|
||||
```
|
||||
|
||||
## Test
|
||||
|
||||
```bash
|
||||
# unit tests
|
||||
$ npm run test
|
||||
|
||||
# e2e tests
|
||||
$ npm run test:e2e
|
||||
|
||||
# test coverage
|
||||
$ npm run test:cov
|
||||
```
|
||||
|
||||
## 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://kamilmysliwiec.com)
|
||||
- Website - [https://nestjs.com](https://nestjs.com/)
|
||||
- Twitter - [@nestframework](https://twitter.com/nestframework)
|
||||
|
||||
## License
|
||||
|
||||
Nest is [MIT licensed](LICENSE).
|
5
nest-cli.json
Normal file
5
nest-cli.json
Normal file
@ -0,0 +1,5 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/nest-cli",
|
||||
"collection": "@nestjs/schematics",
|
||||
"sourceRoot": "src"
|
||||
}
|
16231
package-lock.json
generated
Normal file
16231
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
90
package.json
Normal file
90
package.json
Normal file
@ -0,0 +1,90 @@
|
||||
{
|
||||
"name": "homemanager",
|
||||
"version": "0.0.1",
|
||||
"description": "",
|
||||
"author": "",
|
||||
"private": true,
|
||||
"license": "UNLICENSED",
|
||||
"scripts": {
|
||||
"prebuild": "rimraf dist",
|
||||
"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"
|
||||
},
|
||||
"dependencies": {
|
||||
"@nestjs/common": "^9.0.0",
|
||||
"@nestjs/config": "^2.2.0",
|
||||
"@nestjs/core": "^9.0.0",
|
||||
"@nestjs/platform-express": "^9.0.0",
|
||||
"@nestjs/swagger": "^6.1.4",
|
||||
"@nestjs/typeorm": "^9.0.1",
|
||||
"bcrypt": "^5.1.0",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.0",
|
||||
"jsonwebtoken": "^9.0.0",
|
||||
"lodash.get": "^4.4.2",
|
||||
"lodash.omit": "^4.5.0",
|
||||
"lodash.pick": "^4.4.0",
|
||||
"lodash.set": "^4.3.2",
|
||||
"mysql2": "^2.3.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"rxjs": "^7.2.0",
|
||||
"typeorm": "^0.3.11"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nestjs/cli": "^9.0.0",
|
||||
"@nestjs/schematics": "^9.0.0",
|
||||
"@nestjs/testing": "^9.0.0",
|
||||
"@types/bcrypt": "^5.0.0",
|
||||
"@types/express": "^4.17.13",
|
||||
"@types/jest": "28.1.4",
|
||||
"@types/jsonwebtoken": "^9.0.0",
|
||||
"@types/lodash.get": "^4.4.7",
|
||||
"@types/lodash.omit": "^4.5.7",
|
||||
"@types/lodash.pick": "^4.4.7",
|
||||
"@types/lodash.set": "^4.3.7",
|
||||
"@types/node": "^16.0.0",
|
||||
"@types/supertest": "^2.0.11",
|
||||
"@typescript-eslint/eslint-plugin": "^5.0.0",
|
||||
"@typescript-eslint/parser": "^5.0.0",
|
||||
"eslint": "^8.0.1",
|
||||
"eslint-config-prettier": "^8.3.0",
|
||||
"eslint-plugin-prettier": "^4.0.0",
|
||||
"jest": "28.1.2",
|
||||
"prettier": "^2.3.2",
|
||||
"source-map-support": "^0.5.20",
|
||||
"supertest": "^6.1.3",
|
||||
"ts-jest": "28.0.5",
|
||||
"ts-loader": "^9.2.3",
|
||||
"ts-node": "^10.0.0",
|
||||
"tsconfig-paths": "4.0.0",
|
||||
"typescript": "^4.3.5"
|
||||
},
|
||||
"jest": {
|
||||
"moduleFileExtensions": [
|
||||
"js",
|
||||
"json",
|
||||
"ts"
|
||||
],
|
||||
"rootDir": "src",
|
||||
"testRegex": ".*\\.spec\\.ts$",
|
||||
"transform": {
|
||||
"^.+\\.(t|j)s$": "ts-jest"
|
||||
},
|
||||
"collectCoverageFrom": [
|
||||
"**/*.(t|j)s"
|
||||
],
|
||||
"coverageDirectory": "../coverage",
|
||||
"testEnvironment": "node"
|
||||
}
|
||||
}
|
108
src/app-building/app-building.controller.ts
Normal file
108
src/app-building/app-building.controller.ts
Normal file
@ -0,0 +1,108 @@
|
||||
import {
|
||||
Body,
|
||||
ClassSerializerInterceptor,
|
||||
Controller,
|
||||
Get,
|
||||
Param,
|
||||
ParseIntPipe,
|
||||
Patch,
|
||||
Post,
|
||||
UseGuards,
|
||||
UseInterceptors,
|
||||
} from '@nestjs/common';
|
||||
import {
|
||||
ApiTags,
|
||||
ApiSecurity,
|
||||
ApiOperation,
|
||||
ApiOkResponse,
|
||||
ApiBody,
|
||||
ApiNotFoundResponse,
|
||||
} from '@nestjs/swagger';
|
||||
import { User } from 'src/objects/user/user.entity';
|
||||
import { LoggedInUser } from 'src/shared/decorators/user.decorator';
|
||||
import { AuthGuard } from 'src/shared/guards/auth.guard';
|
||||
import { AppBuildingService } from './app-building.service';
|
||||
import { BuildingFloorUpdateRequestDto } from './dto/building-floor-request.dto';
|
||||
import { CreateBuildingRequestDto } from './dto/buildings-create-request.dto';
|
||||
import {
|
||||
BuildingFloorResponseDto,
|
||||
BuildingsListResponseDto,
|
||||
BuildingsResponseDto,
|
||||
} from './dto/buildings-response.dto';
|
||||
|
||||
@Controller({
|
||||
path: 'buildings',
|
||||
})
|
||||
@ApiTags('buildings')
|
||||
@ApiSecurity('Bearer token')
|
||||
@UseInterceptors(ClassSerializerInterceptor)
|
||||
@UseGuards(AuthGuard)
|
||||
export class AppBuildingController {
|
||||
constructor(private readonly service: AppBuildingService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: 'Get buildings' })
|
||||
@ApiOkResponse({ isArray: true, type: BuildingsListResponseDto })
|
||||
async getBuildings(
|
||||
@LoggedInUser() user: User,
|
||||
): Promise<BuildingsListResponseDto[]> {
|
||||
return this.service.getUserBuildings(user);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: 'Create building' })
|
||||
@ApiNotFoundResponse({ description: 'Invalid group ID' })
|
||||
@ApiBody({ type: CreateBuildingRequestDto })
|
||||
@ApiOkResponse({ type: BuildingsResponseDto })
|
||||
async createBuilding(
|
||||
@LoggedInUser() user: User,
|
||||
@Body() body: CreateBuildingRequestDto,
|
||||
): Promise<BuildingsResponseDto> {
|
||||
return this.service.createBuilding(user, body);
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
@ApiOperation({ summary: 'Get building by ID' })
|
||||
@ApiNotFoundResponse({ description: 'Building not found' })
|
||||
@ApiOkResponse({ type: BuildingsResponseDto })
|
||||
async getBuildingById(
|
||||
@Param('id', ParseIntPipe) id: number,
|
||||
@LoggedInUser() user: User,
|
||||
): Promise<BuildingsResponseDto> {
|
||||
return this.service.getBuildingById(user, id);
|
||||
}
|
||||
|
||||
@Get(':id/floors')
|
||||
@ApiOperation({ summary: 'Get building floors by ID' })
|
||||
@ApiOkResponse({ type: BuildingFloorResponseDto, isArray: true })
|
||||
async getBuildingFloorsById(
|
||||
@Param('id', ParseIntPipe) id: number,
|
||||
@LoggedInUser() user: User,
|
||||
): Promise<BuildingFloorResponseDto[]> {
|
||||
return this.service.getBuildingFloors(user, id);
|
||||
}
|
||||
|
||||
@Get(':id/floors/:number')
|
||||
@ApiOperation({ summary: 'Get building floors by ID' })
|
||||
@ApiOkResponse({ type: BuildingFloorResponseDto })
|
||||
async getBuildingFloorByIdByNumber(
|
||||
@Param('id', ParseIntPipe) id: number,
|
||||
@Param('number', ParseIntPipe) floor: number,
|
||||
@LoggedInUser() user: User,
|
||||
): Promise<BuildingFloorResponseDto> {
|
||||
return this.service.getBuildingFloor(user, id, floor);
|
||||
}
|
||||
|
||||
@Patch(':id/floors/:number')
|
||||
@ApiBody({ type: BuildingFloorUpdateRequestDto })
|
||||
@ApiOperation({ summary: 'Update building floor' })
|
||||
@ApiOkResponse({ type: BuildingFloorResponseDto })
|
||||
async updateBuildingFloorByIdByNumber(
|
||||
@Param('id', ParseIntPipe) id: number,
|
||||
@Param('number', ParseIntPipe) floor: number,
|
||||
@Body() body: BuildingFloorUpdateRequestDto,
|
||||
@LoggedInUser() user: User,
|
||||
): Promise<BuildingFloorResponseDto> {
|
||||
return this.service.updateBuildingFloor(user, body, id, floor);
|
||||
}
|
||||
}
|
14
src/app-building/app-building.module.ts
Normal file
14
src/app-building/app-building.module.ts
Normal file
@ -0,0 +1,14 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { BuildingModule } from 'src/objects/building/building.module';
|
||||
import { GroupModule } from 'src/objects/group/group.module';
|
||||
import { UserModule } from 'src/objects/user/user.module';
|
||||
import { AuthModule } from 'src/shared/auth/auth.module';
|
||||
import { AppBuildingController } from './app-building.controller';
|
||||
import { AppBuildingService } from './app-building.service';
|
||||
|
||||
@Module({
|
||||
imports: [GroupModule, BuildingModule, UserModule, AuthModule],
|
||||
controllers: [AppBuildingController],
|
||||
providers: [AppBuildingService],
|
||||
})
|
||||
export class AppBuildingModule {}
|
113
src/app-building/app-building.service.ts
Normal file
113
src/app-building/app-building.service.ts
Normal file
@ -0,0 +1,113 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import omit from 'lodash.omit';
|
||||
import pick from 'lodash.pick';
|
||||
import { BuildingService } from 'src/objects/building/building.service';
|
||||
import { GroupService } from 'src/objects/group/group.service';
|
||||
import { User } from 'src/objects/user/user.entity';
|
||||
import { UserService } from 'src/objects/user/user.service';
|
||||
import { BuildingFloorUpdateRequestDto } from './dto/building-floor-request.dto';
|
||||
import { CreateBuildingRequestDto } from './dto/buildings-create-request.dto';
|
||||
|
||||
@Injectable()
|
||||
export class AppBuildingService {
|
||||
constructor(
|
||||
private readonly buildingService: BuildingService,
|
||||
private readonly userService: UserService,
|
||||
private readonly groupService: GroupService,
|
||||
) {}
|
||||
|
||||
async getUserBuildings(user: User) {
|
||||
return this.buildingService.getBuildingsByUserSub(user.sub);
|
||||
}
|
||||
|
||||
async createBuilding(user: User, body: CreateBuildingRequestDto) {
|
||||
const getGroup = await this.groupService.getByIdAndMemberSub(
|
||||
body.group,
|
||||
user.sub,
|
||||
);
|
||||
if (!getGroup) {
|
||||
throw new NotFoundException('Group not found');
|
||||
}
|
||||
|
||||
// TODO: validate color
|
||||
|
||||
const newBuilding = await this.buildingService.saveBuilding({
|
||||
...pick(body, ['displayName', 'color', 'address']),
|
||||
groups: [getGroup],
|
||||
});
|
||||
|
||||
const newFloor = await this.buildingService.saveFloor({
|
||||
displayName: 'Ground Floor',
|
||||
number: 0,
|
||||
plan: '{}',
|
||||
building: newBuilding,
|
||||
});
|
||||
|
||||
delete newFloor.building;
|
||||
newBuilding.floors = [newFloor];
|
||||
|
||||
return omit(newBuilding, ['groups']);
|
||||
}
|
||||
|
||||
async getBuildingById(user: User, id: number) {
|
||||
const building = await this.buildingService.getBuildingByIdAndUserSub(
|
||||
id,
|
||||
user.sub,
|
||||
['floors', 'floors.rooms'],
|
||||
);
|
||||
|
||||
if (!building) {
|
||||
throw new NotFoundException('Building not found');
|
||||
}
|
||||
|
||||
return omit(building, ['groups']);
|
||||
}
|
||||
|
||||
async getBuildingFloors(user: User, buildingId: number) {
|
||||
const floors = await this.buildingService.getFloorsByBuildingAndUserSub(
|
||||
buildingId,
|
||||
user.sub,
|
||||
['rooms'],
|
||||
);
|
||||
|
||||
return floors.map((floor) => omit(floor, ['building']));
|
||||
}
|
||||
|
||||
async getBuildingFloor(user: User, buildingId: number, floorNumber: number) {
|
||||
const floor = await this.buildingService.getFloorByBuildingAndUserSub(
|
||||
buildingId,
|
||||
floorNumber,
|
||||
user.sub,
|
||||
['rooms'],
|
||||
);
|
||||
|
||||
if (!floor) {
|
||||
throw new NotFoundException('Floor not found');
|
||||
}
|
||||
|
||||
return omit(floor, ['building']);
|
||||
}
|
||||
|
||||
async updateBuildingFloor(
|
||||
user: User,
|
||||
body: BuildingFloorUpdateRequestDto,
|
||||
buildingId: number,
|
||||
floorNumber: number,
|
||||
) {
|
||||
const floor = await this.buildingService.getFloorByBuildingAndUserSub(
|
||||
buildingId,
|
||||
floorNumber,
|
||||
user.sub,
|
||||
['rooms'],
|
||||
);
|
||||
|
||||
if (!floor) {
|
||||
throw new NotFoundException('Floor not found');
|
||||
}
|
||||
|
||||
Object.assign(floor, body);
|
||||
|
||||
await this.buildingService.saveFloor(floor);
|
||||
return omit(floor, ['building']);
|
||||
}
|
||||
}
|
12
src/app-building/dto/building-floor-request.dto.ts
Normal file
12
src/app-building/dto/building-floor-request.dto.ts
Normal file
@ -0,0 +1,12 @@
|
||||
import { PartialType, PickType } from '@nestjs/swagger';
|
||||
import { Floor } from 'src/objects/building/entities/floor.entity';
|
||||
|
||||
export class BuildingFloorRequestDto extends PickType(Floor, [
|
||||
'displayName',
|
||||
'number',
|
||||
'plan',
|
||||
]) {}
|
||||
|
||||
export class BuildingFloorUpdateRequestDto extends PartialType(
|
||||
BuildingFloorRequestDto,
|
||||
) {}
|
27
src/app-building/dto/buildings-create-request.dto.ts
Normal file
27
src/app-building/dto/buildings-create-request.dto.ts
Normal file
@ -0,0 +1,27 @@
|
||||
import { ApiProperty, PickType } from '@nestjs/swagger';
|
||||
import { IsNumber, IsString, MaxLength, MinLength } from 'class-validator';
|
||||
import { Building } from 'src/objects/building/entities/building.entity';
|
||||
|
||||
export class CreateBuildingRequestDto extends PickType(Building, [
|
||||
'displayName',
|
||||
'address',
|
||||
'color',
|
||||
]) {
|
||||
@ApiProperty()
|
||||
@IsNumber()
|
||||
group: number;
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
displayName: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
address: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
@MinLength(4)
|
||||
@MaxLength(16)
|
||||
color: string;
|
||||
}
|
32
src/app-building/dto/buildings-response.dto.ts
Normal file
32
src/app-building/dto/buildings-response.dto.ts
Normal file
@ -0,0 +1,32 @@
|
||||
import { ApiProperty, OmitType } from '@nestjs/swagger';
|
||||
import { Type } from 'class-transformer';
|
||||
import { Building } from 'src/objects/building/entities/building.entity';
|
||||
import { Floor } from 'src/objects/building/entities/floor.entity';
|
||||
import { Room } from 'src/objects/building/entities/room.entity';
|
||||
|
||||
export class BuildingRoomResponseDto extends OmitType(Room, [
|
||||
'floor',
|
||||
'building',
|
||||
]) {}
|
||||
|
||||
export class BuildingFloorResponseDto extends OmitType(Floor, [
|
||||
'building',
|
||||
'rooms',
|
||||
]) {
|
||||
@ApiProperty({ type: BuildingRoomResponseDto, isArray: true })
|
||||
@Type(() => BuildingRoomResponseDto)
|
||||
rooms: BuildingRoomResponseDto[];
|
||||
}
|
||||
|
||||
export class BuildingsResponseDto extends OmitType(Building, [
|
||||
'groups',
|
||||
'floors',
|
||||
]) {
|
||||
@ApiProperty({ type: BuildingFloorResponseDto, isArray: true })
|
||||
@Type(() => BuildingFloorResponseDto)
|
||||
floors: BuildingFloorResponseDto[];
|
||||
}
|
||||
|
||||
export class BuildingsListResponseDto extends OmitType(BuildingsResponseDto, [
|
||||
'floors',
|
||||
]) {}
|
51
src/app-group/app-group.controller.ts
Normal file
51
src/app-group/app-group.controller.ts
Normal file
@ -0,0 +1,51 @@
|
||||
import {
|
||||
Body,
|
||||
ClassSerializerInterceptor,
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
UseGuards,
|
||||
UseInterceptors,
|
||||
} from '@nestjs/common';
|
||||
import {
|
||||
ApiBody,
|
||||
ApiOkResponse,
|
||||
ApiOperation,
|
||||
ApiSecurity,
|
||||
ApiTags,
|
||||
} from '@nestjs/swagger';
|
||||
import { User } from 'src/objects/user/user.entity';
|
||||
import { LoggedInUser } from 'src/shared/decorators/user.decorator';
|
||||
import { AuthGuard } from 'src/shared/guards/auth.guard';
|
||||
import { AppGroupService } from './app-group.service';
|
||||
import { CreateGroupRequestDto } from './dto/groups-create-request.dto';
|
||||
import { GroupsResponseDto } from './dto/groups-response.dto';
|
||||
|
||||
@Controller({
|
||||
path: 'groups',
|
||||
})
|
||||
@ApiTags('groups')
|
||||
@ApiSecurity('Bearer token')
|
||||
@UseInterceptors(ClassSerializerInterceptor)
|
||||
@UseGuards(AuthGuard)
|
||||
export class AppGroupController {
|
||||
constructor(private readonly service: AppGroupService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: 'Get user groups' })
|
||||
@ApiOkResponse({ type: GroupsResponseDto, isArray: true })
|
||||
async getGroups(@LoggedInUser() user: User) {
|
||||
return this.service.getUserGroups(user);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: 'Create a new group' })
|
||||
@ApiBody({ type: CreateGroupRequestDto })
|
||||
@ApiOkResponse({ type: GroupsResponseDto })
|
||||
async createGroup(
|
||||
@LoggedInUser() user: User,
|
||||
@Body() body: CreateGroupRequestDto,
|
||||
) {
|
||||
return this.service.createNewGroup(user, body);
|
||||
}
|
||||
}
|
13
src/app-group/app-group.module.ts
Normal file
13
src/app-group/app-group.module.ts
Normal file
@ -0,0 +1,13 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { GroupModule } from 'src/objects/group/group.module';
|
||||
import { UserModule } from 'src/objects/user/user.module';
|
||||
import { AuthModule } from 'src/shared/auth/auth.module';
|
||||
import { AppGroupController } from './app-group.controller';
|
||||
import { AppGroupService } from './app-group.service';
|
||||
|
||||
@Module({
|
||||
imports: [GroupModule, UserModule, AuthModule],
|
||||
providers: [AppGroupService],
|
||||
controllers: [AppGroupController],
|
||||
})
|
||||
export class AppGroupModule {}
|
51
src/app-group/app-group.service.ts
Normal file
51
src/app-group/app-group.service.ts
Normal file
@ -0,0 +1,51 @@
|
||||
import { BadRequestException, Injectable } from '@nestjs/common';
|
||||
import { GroupService } from 'src/objects/group/group.service';
|
||||
import { User } from 'src/objects/user/user.entity';
|
||||
import { UserService } from 'src/objects/user/user.service';
|
||||
import { CreateGroupRequestDto } from './dto/groups-create-request.dto';
|
||||
import { GroupsResponseDto, PartialUser } from './dto/groups-response.dto';
|
||||
import pick from 'lodash.pick';
|
||||
import { Group } from 'src/objects/group/group.entity';
|
||||
|
||||
@Injectable()
|
||||
export class AppGroupService {
|
||||
constructor(
|
||||
private readonly userService: UserService,
|
||||
private readonly groupService: GroupService,
|
||||
) {}
|
||||
|
||||
async getUserGroups(user: User) {
|
||||
const { groups } = await this.userService.getUserById(user.id, [
|
||||
'groups',
|
||||
'groups.members',
|
||||
]);
|
||||
|
||||
(groups as GroupsResponseDto[]).forEach((group) => {
|
||||
this.mapGroup(group);
|
||||
});
|
||||
|
||||
return groups;
|
||||
}
|
||||
|
||||
async createNewGroup(user: User, body: CreateGroupRequestDto) {
|
||||
const { color } = body;
|
||||
if (
|
||||
!color.startsWith('#') &&
|
||||
!color.startsWith('rgb') &&
|
||||
!color.startsWith('hsl') &&
|
||||
!color.startsWith('hsv')
|
||||
) {
|
||||
throw new BadRequestException('Invalid color value');
|
||||
}
|
||||
|
||||
const result = await this.groupService.create(body, user);
|
||||
return this.mapGroup(result);
|
||||
}
|
||||
|
||||
private mapGroup(input: Group | GroupsResponseDto): GroupsResponseDto {
|
||||
input.members = input.members.map((member: PartialUser) =>
|
||||
pick(member, ['sub', 'name', 'color', 'picture']),
|
||||
);
|
||||
return input;
|
||||
}
|
||||
}
|
17
src/app-group/dto/groups-create-request.dto.ts
Normal file
17
src/app-group/dto/groups-create-request.dto.ts
Normal file
@ -0,0 +1,17 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsOptional, IsString, MaxLength, MinLength } from 'class-validator';
|
||||
|
||||
export class CreateGroupRequestDto {
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
@MinLength(3)
|
||||
@MaxLength(32)
|
||||
name: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
@MinLength(4)
|
||||
@MaxLength(16)
|
||||
color?: string;
|
||||
}
|
18
src/app-group/dto/groups-response.dto.ts
Normal file
18
src/app-group/dto/groups-response.dto.ts
Normal file
@ -0,0 +1,18 @@
|
||||
import { ApiProperty, OmitType, PickType } from '@nestjs/swagger';
|
||||
import { Group } from 'src/objects/group/group.entity';
|
||||
import { User } from 'src/objects/user/user.entity';
|
||||
|
||||
export class PartialUser extends PickType(User, [
|
||||
'sub',
|
||||
'name',
|
||||
'color',
|
||||
'picture',
|
||||
]) {}
|
||||
|
||||
export class GroupsResponseDto extends OmitType(Group, [
|
||||
'members',
|
||||
'buildings',
|
||||
]) {
|
||||
@ApiProperty({ type: PartialUser, isArray: true })
|
||||
members: PartialUser[];
|
||||
}
|
55
src/app-user/app-user.controller.ts
Normal file
55
src/app-user/app-user.controller.ts
Normal file
@ -0,0 +1,55 @@
|
||||
import {
|
||||
Body,
|
||||
ClassSerializerInterceptor,
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
UseGuards,
|
||||
UseInterceptors,
|
||||
} from '@nestjs/common';
|
||||
import {
|
||||
ApiBadRequestResponse,
|
||||
ApiBearerAuth,
|
||||
ApiBody,
|
||||
ApiOkResponse,
|
||||
ApiOperation,
|
||||
ApiTags,
|
||||
} from '@nestjs/swagger';
|
||||
import { User } from 'src/objects/user/user.entity';
|
||||
import { LoggedInUser } from 'src/shared/decorators/user.decorator';
|
||||
import { AuthGuard } from 'src/shared/guards/auth.guard';
|
||||
import { AppUserService } from './app-user.service';
|
||||
import { UserLoginResponseDto } from './dto/user-login-response.dto';
|
||||
import { UserLoginDto } from './dto/user-login.dto';
|
||||
|
||||
@ApiTags('users')
|
||||
@UseInterceptors(ClassSerializerInterceptor)
|
||||
@Controller({
|
||||
path: 'user',
|
||||
})
|
||||
export class AppUserController {
|
||||
constructor(private readonly service: AppUserService) {}
|
||||
|
||||
@Post('login')
|
||||
@ApiBody({ type: UserLoginDto })
|
||||
@ApiOperation({ summary: 'Log in using email and password' })
|
||||
@ApiBadRequestResponse()
|
||||
@ApiOkResponse({ type: UserLoginResponseDto })
|
||||
async userDoLogin(@Body() body: UserLoginDto) {
|
||||
return this.service.login(body);
|
||||
}
|
||||
|
||||
@Get()
|
||||
@UseGuards(AuthGuard)
|
||||
@ApiOperation({ summary: 'Get logged in user' })
|
||||
@ApiBearerAuth('Bearer auth')
|
||||
async userGetInfo(@LoggedInUser() user: User) {
|
||||
return {
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
emailVerified: user.emailVerified,
|
||||
picture: user.picture,
|
||||
updatedAt: user.updatedAt,
|
||||
};
|
||||
}
|
||||
}
|
12
src/app-user/app-user.module.ts
Normal file
12
src/app-user/app-user.module.ts
Normal file
@ -0,0 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { UserModule } from 'src/objects/user/user.module';
|
||||
import { AuthModule } from 'src/shared/auth/auth.module';
|
||||
import { AppUserController } from './app-user.controller';
|
||||
import { AppUserService } from './app-user.service';
|
||||
|
||||
@Module({
|
||||
imports: [UserModule, AuthModule],
|
||||
controllers: [AppUserController],
|
||||
providers: [AppUserService],
|
||||
})
|
||||
export class AppUser {}
|
33
src/app-user/app-user.service.ts
Normal file
33
src/app-user/app-user.service.ts
Normal file
@ -0,0 +1,33 @@
|
||||
import { UserService } from 'src/objects/user/user.service';
|
||||
import { BadRequestException, Injectable } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { UserLoginDto } from './dto/user-login.dto';
|
||||
import { UserLoginResponseDto } from './dto/user-login-response.dto';
|
||||
import { AuthService } from 'src/shared/auth/auth.service';
|
||||
|
||||
@Injectable()
|
||||
export class AppUserService {
|
||||
constructor(
|
||||
private readonly userService: UserService,
|
||||
private readonly config: ConfigService,
|
||||
private readonly auth: AuthService,
|
||||
) {}
|
||||
|
||||
async login({ email, password }: UserLoginDto) {
|
||||
const user = await this.userService.getUserByEmail(email);
|
||||
if (!user) {
|
||||
throw new BadRequestException('Invalid username or password');
|
||||
}
|
||||
|
||||
if (!(await this.auth.comparePassword(user, password))) {
|
||||
throw new BadRequestException('Invalid username or password');
|
||||
}
|
||||
|
||||
const token = await this.auth.issueJWT(user);
|
||||
|
||||
return new UserLoginResponseDto({
|
||||
accessToken: token,
|
||||
expiresIn: this.auth.expiry,
|
||||
});
|
||||
}
|
||||
}
|
10
src/app-user/dto/user-login-response.dto.ts
Normal file
10
src/app-user/dto/user-login-response.dto.ts
Normal file
@ -0,0 +1,10 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { ConstructableDto } from 'src/shared/dto/constructable.dto';
|
||||
|
||||
export class UserLoginResponseDto extends ConstructableDto<UserLoginResponseDto> {
|
||||
@ApiProperty()
|
||||
accessToken: string;
|
||||
|
||||
@ApiProperty()
|
||||
expiresIn: number;
|
||||
}
|
12
src/app-user/dto/user-login.dto.ts
Normal file
12
src/app-user/dto/user-login.dto.ts
Normal file
@ -0,0 +1,12 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsEmail, IsString } from 'class-validator';
|
||||
|
||||
export class UserLoginDto {
|
||||
@ApiProperty()
|
||||
@IsEmail()
|
||||
email: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
password: string;
|
||||
}
|
22
src/app.controller.spec.ts
Normal file
22
src/app.controller.spec.ts
Normal 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!');
|
||||
});
|
||||
});
|
||||
});
|
23
src/app.controller.ts
Normal file
23
src/app.controller.ts
Normal file
@ -0,0 +1,23 @@
|
||||
import { Controller, Get, Inject } from '@nestjs/common';
|
||||
import { AppService } from './app.service';
|
||||
|
||||
@Controller()
|
||||
export class AppController {
|
||||
constructor(
|
||||
private readonly appService: AppService,
|
||||
@Inject('JWT_JWKS')
|
||||
private readonly jwks: string,
|
||||
) {}
|
||||
|
||||
@Get()
|
||||
getHello(): string {
|
||||
return this.appService.getHello();
|
||||
}
|
||||
|
||||
@Get('/.well-known/jwks.json')
|
||||
getJWKs() {
|
||||
return {
|
||||
keys: [this.jwks],
|
||||
};
|
||||
}
|
||||
}
|
49
src/app.module.ts
Normal file
49
src/app.module.ts
Normal file
@ -0,0 +1,49 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { AppBuildingModule } from './app-building/app-building.module';
|
||||
import { AppGroupModule } from './app-group/app-group.module';
|
||||
import { AppUser } from './app-user/app-user.module';
|
||||
import { AppController } from './app.controller';
|
||||
import { AppService } from './app.service';
|
||||
import { BuildingModule } from './objects/building/building.module';
|
||||
import { GroupModule } from './objects/group/group.module';
|
||||
import { StorageModule } from './objects/storage/storage.module';
|
||||
import { UserModule } from './objects/user/user.module';
|
||||
import { AuthModule } from './shared/auth/auth.module';
|
||||
import { SecretsModule } from './shared/secrets/secrets.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({
|
||||
envFilePath: ['.env.development', '.env'],
|
||||
isGlobal: true,
|
||||
}),
|
||||
TypeOrmModule.forRootAsync({
|
||||
imports: [ConfigModule],
|
||||
useFactory: (configService: ConfigService) => ({
|
||||
type: 'mysql',
|
||||
host: configService.get('DATABASE_HOST'),
|
||||
port: +configService.get('DATABASE_PORT'),
|
||||
username: configService.get('DATABASE_USER'),
|
||||
password: configService.get('DATABASE_PASS'),
|
||||
database: configService.get('DATABASE_BASE'),
|
||||
autoLoadEntities: true,
|
||||
synchronize: true,
|
||||
}),
|
||||
inject: [ConfigService],
|
||||
}),
|
||||
GroupModule,
|
||||
UserModule,
|
||||
BuildingModule,
|
||||
StorageModule,
|
||||
SecretsModule,
|
||||
AuthModule,
|
||||
AppUser,
|
||||
AppGroupModule,
|
||||
AppBuildingModule,
|
||||
],
|
||||
controllers: [AppController],
|
||||
providers: [AppService],
|
||||
})
|
||||
export class AppModule {}
|
8
src/app.service.ts
Normal file
8
src/app.service.ts
Normal file
@ -0,0 +1,8 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
@Injectable()
|
||||
export class AppService {
|
||||
getHello(): string {
|
||||
return 'Hello World!';
|
||||
}
|
||||
}
|
34
src/main.ts
Normal file
34
src/main.ts
Normal file
@ -0,0 +1,34 @@
|
||||
import { ValidationPipe } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
||||
import { AppModule } from './app.module';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule);
|
||||
const configService = app.get(ConfigService);
|
||||
const config = new DocumentBuilder()
|
||||
.setTitle('Home Manager')
|
||||
.setDescription('Home manager API')
|
||||
.setVersion('1.0')
|
||||
.addTag('users')
|
||||
.addTag('groups')
|
||||
.addTag('storage')
|
||||
.addTag('buildings')
|
||||
.addBearerAuth({
|
||||
name: 'Bearer token',
|
||||
type: 'apiKey',
|
||||
})
|
||||
.build();
|
||||
const document = SwaggerModule.createDocument(app, config);
|
||||
SwaggerModule.setup('api', app, document);
|
||||
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({
|
||||
forbidNonWhitelisted: true,
|
||||
whitelist: true,
|
||||
}),
|
||||
);
|
||||
await app.listen(+configService.get('PORT'));
|
||||
}
|
||||
bootstrap();
|
14
src/objects/building/building.module.ts
Normal file
14
src/objects/building/building.module.ts
Normal file
@ -0,0 +1,14 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { GroupModule } from '../group/group.module';
|
||||
import { Building } from './entities/building.entity';
|
||||
import { BuildingService } from './building.service';
|
||||
import { Floor } from './entities/floor.entity';
|
||||
import { Room } from './entities/room.entity';
|
||||
|
||||
@Module({
|
||||
imports: [GroupModule, TypeOrmModule.forFeature([Building, Floor, Room])],
|
||||
providers: [BuildingService],
|
||||
exports: [TypeOrmModule, BuildingService],
|
||||
})
|
||||
export class BuildingModule {}
|
107
src/objects/building/building.service.ts
Normal file
107
src/objects/building/building.service.ts
Normal file
@ -0,0 +1,107 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { GroupService } from '../group/group.service';
|
||||
import { Building } from './entities/building.entity';
|
||||
import { Floor } from './entities/floor.entity';
|
||||
import { Room } from './entities/room.entity';
|
||||
|
||||
@Injectable()
|
||||
export class BuildingService {
|
||||
constructor(
|
||||
@InjectRepository(Building)
|
||||
private readonly buildingRepository: Repository<Building>,
|
||||
@InjectRepository(Floor)
|
||||
private readonly floorRepository: Repository<Floor>,
|
||||
@InjectRepository(Room)
|
||||
private readonly roomRepository: Repository<Room>,
|
||||
private readonly groupService: GroupService,
|
||||
) {}
|
||||
|
||||
async getBuildingsByUserSub(sub: string, relations = []) {
|
||||
return this.buildingRepository.find({
|
||||
where: {
|
||||
groups: {
|
||||
members: {
|
||||
sub,
|
||||
},
|
||||
},
|
||||
},
|
||||
relations,
|
||||
});
|
||||
}
|
||||
|
||||
async getBuildingByIdAndUserSub(id: number, sub: string, relations = []) {
|
||||
return this.buildingRepository.findOne({
|
||||
where: {
|
||||
id,
|
||||
groups: {
|
||||
members: {
|
||||
sub,
|
||||
},
|
||||
},
|
||||
},
|
||||
relations,
|
||||
});
|
||||
}
|
||||
|
||||
async getFloorByBuildingAndUserSub(
|
||||
buildingId: number,
|
||||
floorNumber: number,
|
||||
sub: string,
|
||||
relations = [],
|
||||
) {
|
||||
return this.floorRepository.findOne({
|
||||
where: {
|
||||
number: floorNumber,
|
||||
building: {
|
||||
id: buildingId,
|
||||
groups: {
|
||||
members: {
|
||||
sub,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
relations,
|
||||
});
|
||||
}
|
||||
|
||||
async getFloorsByBuildingAndUserSub(
|
||||
buildingId: number,
|
||||
sub: string,
|
||||
relations = [],
|
||||
) {
|
||||
return this.floorRepository.find({
|
||||
where: {
|
||||
building: {
|
||||
id: buildingId,
|
||||
groups: {
|
||||
members: {
|
||||
sub,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
relations,
|
||||
});
|
||||
}
|
||||
|
||||
async saveBuilding(data: Partial<Building>) {
|
||||
const newBuilding = new Building();
|
||||
Object.assign(newBuilding, data);
|
||||
return this.buildingRepository.save(newBuilding);
|
||||
}
|
||||
|
||||
async saveFloor(data: Partial<Floor>) {
|
||||
const newFloor = new Floor();
|
||||
Object.assign(newFloor, data);
|
||||
return this.floorRepository.save(newFloor);
|
||||
}
|
||||
|
||||
async saveRoom(data: Partial<Room>) {
|
||||
const newRoom = new Room();
|
||||
Object.assign(newRoom, data);
|
||||
return this.roomRepository.save(newRoom);
|
||||
}
|
||||
}
|
49
src/objects/building/entities/building.entity.ts
Normal file
49
src/objects/building/entities/building.entity.ts
Normal file
@ -0,0 +1,49 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
JoinTable,
|
||||
ManyToMany,
|
||||
OneToMany,
|
||||
PrimaryGeneratedColumn,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
import { Group } from '../../group/group.entity';
|
||||
import { Floor } from './floor.entity';
|
||||
|
||||
@Entity()
|
||||
export class Building {
|
||||
@ApiProperty()
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@ApiProperty()
|
||||
@Column()
|
||||
displayName: string;
|
||||
|
||||
@ApiProperty()
|
||||
@Column()
|
||||
address: string;
|
||||
|
||||
@ApiProperty()
|
||||
@Column()
|
||||
color: string;
|
||||
|
||||
@ApiProperty()
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
|
||||
@ApiProperty()
|
||||
@UpdateDateColumn()
|
||||
updatedAt: Date;
|
||||
|
||||
@ApiProperty({ type: Group, isArray: true })
|
||||
@ManyToMany(() => Group, (group) => group.buildings)
|
||||
@JoinTable()
|
||||
groups: Group[];
|
||||
|
||||
@ApiProperty({ type: Floor, isArray: true })
|
||||
@OneToMany(() => Floor, (floor) => floor.building)
|
||||
floors: Floor[];
|
||||
}
|
47
src/objects/building/entities/floor.entity.ts
Normal file
47
src/objects/building/entities/floor.entity.ts
Normal file
@ -0,0 +1,47 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
ManyToOne,
|
||||
OneToMany,
|
||||
PrimaryGeneratedColumn,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
import { Building } from './building.entity';
|
||||
import { Room } from './room.entity';
|
||||
|
||||
@Entity()
|
||||
export class Floor {
|
||||
@ApiProperty()
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@ApiProperty()
|
||||
@Column()
|
||||
displayName: string;
|
||||
|
||||
@ApiProperty()
|
||||
@Column()
|
||||
number: number;
|
||||
|
||||
@ApiProperty()
|
||||
@Column()
|
||||
plan: string;
|
||||
|
||||
@ApiProperty({ type: () => Building })
|
||||
@ManyToOne(() => Building)
|
||||
building: Building;
|
||||
|
||||
@ApiProperty({ type: () => Room, isArray: true })
|
||||
@OneToMany(() => Room, (room) => room.floor)
|
||||
rooms: Room[];
|
||||
|
||||
@ApiProperty()
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
|
||||
@ApiProperty()
|
||||
@UpdateDateColumn()
|
||||
updatedAt: Date;
|
||||
}
|
34
src/objects/building/entities/room.entity.ts
Normal file
34
src/objects/building/entities/room.entity.ts
Normal file
@ -0,0 +1,34 @@
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
ManyToOne,
|
||||
PrimaryGeneratedColumn,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
import { Building } from './building.entity';
|
||||
import { Floor } from './floor.entity';
|
||||
|
||||
@Entity()
|
||||
export class Room {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@ManyToOne(() => Building)
|
||||
building: Building;
|
||||
|
||||
@ManyToOne(() => Floor)
|
||||
floor: Floor;
|
||||
|
||||
@Column()
|
||||
displayName: string;
|
||||
|
||||
@Column()
|
||||
plan: string;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn()
|
||||
updatedAt: Date;
|
||||
}
|
44
src/objects/group/group.entity.ts
Normal file
44
src/objects/group/group.entity.ts
Normal file
@ -0,0 +1,44 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
JoinTable,
|
||||
ManyToMany,
|
||||
PrimaryGeneratedColumn,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
import { Building } from '../building/entities/building.entity';
|
||||
import { User } from '../user/user.entity';
|
||||
|
||||
@Entity()
|
||||
export class Group {
|
||||
@ApiProperty()
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@ApiProperty()
|
||||
@Column()
|
||||
name: string;
|
||||
|
||||
@ApiProperty()
|
||||
@Column()
|
||||
color: string;
|
||||
|
||||
@ApiProperty()
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
|
||||
@ApiProperty()
|
||||
@UpdateDateColumn()
|
||||
updatedAt: Date;
|
||||
|
||||
@ApiProperty({ type: User, isArray: true })
|
||||
@ManyToMany(() => User, (member) => member.groups)
|
||||
@JoinTable()
|
||||
members: User[];
|
||||
|
||||
@ApiProperty({ type: Building, isArray: true })
|
||||
@ManyToMany(() => Building, (building) => building.groups)
|
||||
buildings: Building[];
|
||||
}
|
11
src/objects/group/group.module.ts
Normal file
11
src/objects/group/group.module.ts
Normal file
@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { Group } from './group.entity';
|
||||
import { GroupService } from './group.service';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([Group])],
|
||||
providers: [GroupService],
|
||||
exports: [TypeOrmModule, GroupService],
|
||||
})
|
||||
export class GroupModule {}
|
55
src/objects/group/group.service.ts
Normal file
55
src/objects/group/group.service.ts
Normal file
@ -0,0 +1,55 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { User } from '../user/user.entity';
|
||||
import { Group } from './group.entity';
|
||||
|
||||
@Injectable()
|
||||
export class GroupService {
|
||||
constructor(
|
||||
@InjectRepository(Group)
|
||||
private readonly groupRepository: Repository<Group>,
|
||||
) {}
|
||||
|
||||
async create({ name, color }: Partial<Group>, user: User) {
|
||||
const group = new Group();
|
||||
group.name = name;
|
||||
group.color = color;
|
||||
group.members = [user];
|
||||
|
||||
return this.groupRepository.save(group);
|
||||
}
|
||||
|
||||
async getById(id: number, relations = []) {
|
||||
return this.groupRepository.findOne({ where: { id }, relations });
|
||||
}
|
||||
|
||||
async getByIdAndMemberSub(id: number, sub: string, relations = []) {
|
||||
return this.groupRepository.findOne({
|
||||
where: { id, members: { sub } },
|
||||
relations,
|
||||
});
|
||||
}
|
||||
|
||||
async getGroupsByMemberSub(sub: string, relations = []) {
|
||||
return this.groupRepository.find({
|
||||
where: {
|
||||
members: {
|
||||
sub,
|
||||
},
|
||||
},
|
||||
relations: ['members', ...relations],
|
||||
});
|
||||
}
|
||||
|
||||
async getGroupsForBuilding(buildingId: number, relations = []) {
|
||||
return this.groupRepository.find({
|
||||
where: {
|
||||
buildings: {
|
||||
id: buildingId,
|
||||
},
|
||||
},
|
||||
relations: ['buildings', ...relations],
|
||||
});
|
||||
}
|
||||
}
|
50
src/objects/storage/entities/item-transaction.entity.ts
Normal file
50
src/objects/storage/entities/item-transaction.entity.ts
Normal file
@ -0,0 +1,50 @@
|
||||
import { User } from 'src/objects/user/user.entity';
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
ManyToOne,
|
||||
PrimaryGeneratedColumn,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
import { TransactionType } from '../enums/transaction-type.enum';
|
||||
import { StoredItem } from './stored-item.entity';
|
||||
|
||||
@Entity()
|
||||
export class StoredItemTransaction {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Column({ type: String, default: TransactionType.ACQUIRED })
|
||||
type: TransactionType;
|
||||
|
||||
@Column({ nullable: true })
|
||||
price?: number;
|
||||
|
||||
@Column({ nullable: true, default: 'EUR', length: 3 })
|
||||
currency?: string;
|
||||
|
||||
@ManyToOne(() => StoredItem, {
|
||||
onDelete: 'CASCADE',
|
||||
onUpdate: 'CASCADE',
|
||||
})
|
||||
storedItem: StoredItem;
|
||||
|
||||
@ManyToOne(() => User, {
|
||||
onDelete: 'SET NULL',
|
||||
nullable: true,
|
||||
})
|
||||
actor?: User;
|
||||
|
||||
@Column({ nullable: true })
|
||||
notes?: string;
|
||||
|
||||
@Column({ type: 'datetime', nullable: true })
|
||||
actionAt?: Date;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn()
|
||||
updatedAt: Date;
|
||||
}
|
60
src/objects/storage/entities/item.entity.ts
Normal file
60
src/objects/storage/entities/item.entity.ts
Normal file
@ -0,0 +1,60 @@
|
||||
import { User } from 'src/objects/user/user.entity';
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
ManyToOne,
|
||||
OneToMany,
|
||||
PrimaryGeneratedColumn,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
import { ItemType } from '../enums/item-type.enum';
|
||||
import { StoredItem } from './stored-item.entity';
|
||||
|
||||
@Entity()
|
||||
export class Item {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Column()
|
||||
displayName: string;
|
||||
|
||||
@Column({ type: String, default: ItemType.ITEM })
|
||||
type: ItemType;
|
||||
|
||||
@Column({ nullable: true })
|
||||
barcode?: string;
|
||||
|
||||
@Column({ default: false })
|
||||
consumable: boolean;
|
||||
|
||||
@Column({ nullable: true })
|
||||
image?: string;
|
||||
|
||||
@Column({ nullable: true })
|
||||
weight?: number;
|
||||
|
||||
@Column({ nullable: true })
|
||||
url?: string;
|
||||
|
||||
@Column({ nullable: true })
|
||||
notes?: string;
|
||||
|
||||
@OneToMany(() => StoredItem, (store) => store.item)
|
||||
instances?: StoredItem[];
|
||||
|
||||
@ManyToOne(() => User, {
|
||||
onDelete: 'SET NULL',
|
||||
nullable: true,
|
||||
})
|
||||
addedBy: User;
|
||||
|
||||
@Column({ default: false })
|
||||
public: boolean;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn()
|
||||
updatedAt: Date;
|
||||
}
|
55
src/objects/storage/entities/storage-set.entity.ts
Normal file
55
src/objects/storage/entities/storage-set.entity.ts
Normal file
@ -0,0 +1,55 @@
|
||||
import { Room } from 'src/objects/building/entities/room.entity';
|
||||
import { User } from 'src/objects/user/user.entity';
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
ManyToOne,
|
||||
OneToMany,
|
||||
PrimaryGeneratedColumn,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
import { StorageSetType } from '../enums/storage-set-type.enum';
|
||||
import { Storage } from './storage.entity';
|
||||
|
||||
@Entity()
|
||||
export class StorageSet {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Column()
|
||||
displayName: string;
|
||||
|
||||
@ManyToOne(() => Room, {
|
||||
onDelete: 'CASCADE',
|
||||
onUpdate: 'CASCADE',
|
||||
})
|
||||
room: Room;
|
||||
|
||||
@Column({ type: String })
|
||||
type: StorageSetType;
|
||||
|
||||
@Column()
|
||||
location: string;
|
||||
|
||||
@Column()
|
||||
locationDescription: string;
|
||||
|
||||
@Column()
|
||||
color: string;
|
||||
|
||||
@OneToMany(() => Storage, (storage) => storage.set)
|
||||
storages: Storage[];
|
||||
|
||||
@ManyToOne(() => User, {
|
||||
onDelete: 'SET NULL',
|
||||
nullable: true,
|
||||
})
|
||||
addedBy: User;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn()
|
||||
updatedAt: Date;
|
||||
}
|
63
src/objects/storage/entities/storage.entity.ts
Normal file
63
src/objects/storage/entities/storage.entity.ts
Normal file
@ -0,0 +1,63 @@
|
||||
import { Room } from 'src/objects/building/entities/room.entity';
|
||||
import { User } from 'src/objects/user/user.entity';
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
ManyToOne,
|
||||
OneToMany,
|
||||
PrimaryGeneratedColumn,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
import { StorageType } from '../enums/storage-type.enum';
|
||||
import { StorageSet } from './storage-set.entity';
|
||||
import { StoredItem } from './stored-item.entity';
|
||||
|
||||
@Entity()
|
||||
export class Storage {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Column()
|
||||
displayName: string;
|
||||
|
||||
@ManyToOne(() => Room, {
|
||||
onDelete: 'CASCADE',
|
||||
onUpdate: 'CASCADE',
|
||||
})
|
||||
room: Room;
|
||||
|
||||
@Column({ type: String })
|
||||
type: StorageType;
|
||||
|
||||
@Column()
|
||||
location: string;
|
||||
|
||||
@Column()
|
||||
locationDescription: string;
|
||||
|
||||
@OneToMany(() => StoredItem, (item) => item.storage)
|
||||
items: StoredItem[];
|
||||
|
||||
@ManyToOne(() => StorageSet, {
|
||||
nullable: true,
|
||||
onDelete: 'SET NULL',
|
||||
onUpdate: 'CASCADE',
|
||||
})
|
||||
set?: StorageSet;
|
||||
|
||||
@Column()
|
||||
color: string;
|
||||
|
||||
@ManyToOne(() => User, {
|
||||
onDelete: 'SET NULL',
|
||||
nullable: true,
|
||||
})
|
||||
addedBy: User;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn()
|
||||
updatedAt: Date;
|
||||
}
|
57
src/objects/storage/entities/stored-item.entity.ts
Normal file
57
src/objects/storage/entities/stored-item.entity.ts
Normal file
@ -0,0 +1,57 @@
|
||||
import { User } from 'src/objects/user/user.entity';
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
ManyToOne,
|
||||
PrimaryGeneratedColumn,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
import { Item } from './item.entity';
|
||||
import { Storage } from './storage.entity';
|
||||
|
||||
@Entity()
|
||||
export class StoredItem {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Column()
|
||||
displayName: string;
|
||||
|
||||
@ManyToOne(() => Item, {
|
||||
onDelete: 'CASCADE',
|
||||
onUpdate: 'CASCADE',
|
||||
})
|
||||
item: Item;
|
||||
|
||||
@ManyToOne(() => Storage, {
|
||||
nullable: true,
|
||||
onDelete: 'SET NULL',
|
||||
onUpdate: 'CASCADE',
|
||||
})
|
||||
storage?: Storage;
|
||||
|
||||
@Column({ nullable: true })
|
||||
notes?: string;
|
||||
|
||||
@ManyToOne(() => User, {
|
||||
onDelete: 'SET NULL',
|
||||
nullable: true,
|
||||
})
|
||||
addedBy: User;
|
||||
|
||||
@Column({ nullable: true, type: 'datetime' })
|
||||
expiresAt?: Date;
|
||||
|
||||
@Column({ nullable: true, type: 'datetime' })
|
||||
acquiredAt?: Date;
|
||||
|
||||
@Column({ nullable: true, type: 'datetime' })
|
||||
consumedAt?: Date;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn()
|
||||
updatedAt: Date;
|
||||
}
|
14
src/objects/storage/enums/item-type.enum.ts
Normal file
14
src/objects/storage/enums/item-type.enum.ts
Normal file
@ -0,0 +1,14 @@
|
||||
export enum ItemType {
|
||||
ITEM = 'ITEM',
|
||||
OBJECT = 'OBJECT',
|
||||
TECHNOLOGY = 'TECHNOLOGY',
|
||||
TOOL = 'TOOL',
|
||||
FOOD = 'FOOD',
|
||||
MEDICINE = 'MEDICINE',
|
||||
ART = 'ART',
|
||||
CRAFT = 'CRAFT',
|
||||
COMPOSITION = 'COMPOSITION',
|
||||
CLOTHING = 'CLOTHING',
|
||||
SERVICE = 'SERVICE',
|
||||
OTHER = 'OTHER',
|
||||
}
|
11
src/objects/storage/enums/storage-set-type.enum.ts
Normal file
11
src/objects/storage/enums/storage-set-type.enum.ts
Normal file
@ -0,0 +1,11 @@
|
||||
export enum StorageSetType {
|
||||
DRAWERS = 'DRAWERS',
|
||||
SHELVES = 'SHELVES',
|
||||
CUPBOARD = 'CUPBOARD',
|
||||
CLOSET = 'CLOSET',
|
||||
FRIDGE = 'FRIDGE',
|
||||
FREEZER = 'FREEZER',
|
||||
BOX = 'BOX',
|
||||
BOXES = 'BOXES',
|
||||
OTHER = 'OTHER',
|
||||
}
|
14
src/objects/storage/enums/storage-type.enum.ts
Normal file
14
src/objects/storage/enums/storage-type.enum.ts
Normal file
@ -0,0 +1,14 @@
|
||||
export enum StorageType {
|
||||
DRAWER = 'DRAWER',
|
||||
SHELF = 'SHELF',
|
||||
ASSEMBLY = 'ASSEMBLY',
|
||||
CUPBOARD = 'CUPBOARD',
|
||||
CLOSET = 'CLOSET',
|
||||
FRIDGE = 'FRIDGE',
|
||||
FREEZER = 'FREEZER',
|
||||
TABLE = 'TABLE',
|
||||
BOX = 'BOX',
|
||||
VIRTUAL = 'VIRTUAL',
|
||||
PERSON = 'PERSON',
|
||||
OTHER = 'OTHER',
|
||||
}
|
8
src/objects/storage/enums/transaction-type.enum.ts
Normal file
8
src/objects/storage/enums/transaction-type.enum.ts
Normal file
@ -0,0 +1,8 @@
|
||||
export enum TransactionType {
|
||||
ACQUIRED = 'ACQUIRED',
|
||||
SOLD = 'SOLD',
|
||||
DESTROYED = 'DESTROYED',
|
||||
BINNED = 'BINNED',
|
||||
MOVED = 'MOVED',
|
||||
TRANSFERRED = 'TRANSFERRED',
|
||||
}
|
29
src/objects/storage/storage.module.ts
Normal file
29
src/objects/storage/storage.module.ts
Normal file
@ -0,0 +1,29 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { BuildingModule } from '../building/building.module';
|
||||
import { GroupModule } from '../group/group.module';
|
||||
import { UserModule } from '../user/user.module';
|
||||
import { StoredItemTransaction } from './entities/item-transaction.entity';
|
||||
import { Item } from './entities/item.entity';
|
||||
import { StorageSet } from './entities/storage-set.entity';
|
||||
import { Storage } from './entities/storage.entity';
|
||||
import { StoredItem } from './entities/stored-item.entity';
|
||||
import { StorageService } from './storage.service';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([
|
||||
Storage,
|
||||
StorageSet,
|
||||
Item,
|
||||
StoredItem,
|
||||
StoredItemTransaction,
|
||||
]),
|
||||
BuildingModule,
|
||||
UserModule,
|
||||
GroupModule,
|
||||
],
|
||||
providers: [StorageService],
|
||||
exports: [TypeOrmModule, StorageService],
|
||||
})
|
||||
export class StorageModule {}
|
30
src/objects/storage/storage.service.ts
Normal file
30
src/objects/storage/storage.service.ts
Normal file
@ -0,0 +1,30 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { BuildingService } from '../building/building.service';
|
||||
import { GroupService } from '../group/group.service';
|
||||
import { UserService } from '../user/user.service';
|
||||
import { StoredItemTransaction } from './entities/item-transaction.entity';
|
||||
import { Item } from './entities/item.entity';
|
||||
import { StorageSet } from './entities/storage-set.entity';
|
||||
import { Storage } from './entities/storage.entity';
|
||||
import { StoredItem } from './entities/stored-item.entity';
|
||||
|
||||
@Injectable()
|
||||
export class StorageService {
|
||||
constructor(
|
||||
@InjectRepository(Item)
|
||||
private readonly itemRepository: Repository<Item>,
|
||||
@InjectRepository(Storage)
|
||||
private readonly storageRepository: Repository<Storage>,
|
||||
@InjectRepository(StorageSet)
|
||||
private readonly storageSetRepository: Repository<StorageSet>,
|
||||
@InjectRepository(StoredItem)
|
||||
private readonly storedItemRepository: Repository<StoredItem>,
|
||||
@InjectRepository(StoredItemTransaction)
|
||||
private readonly transactionRepository: Repository<StoredItemTransaction>,
|
||||
private readonly groupService: GroupService,
|
||||
private readonly userService: UserService,
|
||||
private readonly buildingService: BuildingService,
|
||||
) {}
|
||||
}
|
62
src/objects/user/user.entity.ts
Normal file
62
src/objects/user/user.entity.ts
Normal file
@ -0,0 +1,62 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
Index,
|
||||
ManyToMany,
|
||||
PrimaryGeneratedColumn,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
import { Group } from '../group/group.entity';
|
||||
|
||||
@Entity()
|
||||
export class User {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@ApiProperty()
|
||||
@Column()
|
||||
name: string;
|
||||
|
||||
@Index()
|
||||
@ApiProperty()
|
||||
@Column()
|
||||
sub: string;
|
||||
|
||||
@Index()
|
||||
@ApiProperty()
|
||||
@Column()
|
||||
email: string;
|
||||
|
||||
@ApiProperty()
|
||||
@Column({ default: false })
|
||||
emailVerified: boolean;
|
||||
|
||||
@Column()
|
||||
password: string;
|
||||
|
||||
@ApiProperty()
|
||||
@Column({ nullable: true, default: 'EUR', length: 3 })
|
||||
currency?: string;
|
||||
|
||||
@ApiProperty()
|
||||
@Column({ nullable: true })
|
||||
picture?: string;
|
||||
|
||||
@ApiProperty()
|
||||
@Column()
|
||||
color: string;
|
||||
|
||||
@ApiProperty({ type: Group, isArray: true })
|
||||
@ManyToMany(() => Group, (group) => group.members)
|
||||
groups: Group[];
|
||||
|
||||
@ApiProperty()
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
|
||||
@ApiProperty()
|
||||
@UpdateDateColumn()
|
||||
updatedAt: Date;
|
||||
}
|
12
src/objects/user/user.module.ts
Normal file
12
src/objects/user/user.module.ts
Normal file
@ -0,0 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { GroupModule } from '../group/group.module';
|
||||
import { User } from './user.entity';
|
||||
import { UserService } from './user.service';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([User]), GroupModule],
|
||||
providers: [UserService],
|
||||
exports: [TypeOrmModule, UserService],
|
||||
})
|
||||
export class UserModule {}
|
34
src/objects/user/user.service.ts
Normal file
34
src/objects/user/user.service.ts
Normal file
@ -0,0 +1,34 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { GroupService } from '../group/group.service';
|
||||
import { User } from './user.entity';
|
||||
|
||||
@Injectable()
|
||||
export class UserService {
|
||||
constructor(
|
||||
@InjectRepository(User) private readonly userRepository: Repository<User>,
|
||||
private readonly groupService: GroupService,
|
||||
) {}
|
||||
|
||||
async getUserById(id: number, relations = []) {
|
||||
return this.userRepository.findOne({
|
||||
where: { id },
|
||||
relations,
|
||||
});
|
||||
}
|
||||
|
||||
async getUserBySub(sub: string, relations = []) {
|
||||
return this.userRepository.findOne({
|
||||
where: { sub },
|
||||
relations,
|
||||
});
|
||||
}
|
||||
|
||||
async getUserByEmail(email: string, relations = []) {
|
||||
return this.userRepository.findOne({
|
||||
where: { email },
|
||||
relations,
|
||||
});
|
||||
}
|
||||
}
|
11
src/shared/auth/auth.module.ts
Normal file
11
src/shared/auth/auth.module.ts
Normal file
@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { UserModule } from 'src/objects/user/user.module';
|
||||
import { SecretsModule } from '../secrets/secrets.module';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
@Module({
|
||||
imports: [UserModule, SecretsModule],
|
||||
providers: [AuthService],
|
||||
exports: [AuthService],
|
||||
})
|
||||
export class AuthModule {}
|
75
src/shared/auth/auth.service.ts
Normal file
75
src/shared/auth/auth.service.ts
Normal file
@ -0,0 +1,75 @@
|
||||
import { Inject, Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { UserService } from 'src/objects/user/user.service';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
import * as jwt from 'jsonwebtoken';
|
||||
import { User } from 'src/objects/user/user.entity';
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
public expiry = +this.config.get('TOKEN_EXPIRY');
|
||||
private issuer = this.config.get('BACKEND_URL');
|
||||
private audience = this.config.get('FRONTEND_URL');
|
||||
|
||||
constructor(
|
||||
@Inject('JWT_PRIVATE_KEY')
|
||||
private readonly privateKey: string,
|
||||
@Inject('JWT_PUBLIC_KEY')
|
||||
private readonly publicKey: string,
|
||||
private readonly userService: UserService,
|
||||
private readonly config: ConfigService,
|
||||
) {}
|
||||
|
||||
async comparePassword(user: User, password: string) {
|
||||
return bcrypt.compare(password, user.password);
|
||||
}
|
||||
|
||||
async hashPassword(password: string) {
|
||||
return bcrypt.hash(password, 12);
|
||||
}
|
||||
|
||||
async issueJWT(user: User) {
|
||||
return jwt.sign(
|
||||
{
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
email_verified: user.emailVerified,
|
||||
picture: user.picture,
|
||||
updated_at: user.updatedAt.toISOString(),
|
||||
},
|
||||
this.privateKey,
|
||||
{
|
||||
algorithm: 'RS256',
|
||||
audience: this.audience,
|
||||
subject: user.sub,
|
||||
expiresIn: this.expiry,
|
||||
issuer: this.issuer,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async getUserFromJWT(token: string) {
|
||||
let payload: jwt.JwtPayload;
|
||||
try {
|
||||
const data = jwt.verify(token, this.publicKey, {
|
||||
algorithms: ['RS256'],
|
||||
issuer: this.issuer,
|
||||
audience: this.audience,
|
||||
complete: true,
|
||||
});
|
||||
|
||||
payload = data.payload as jwt.JwtPayload;
|
||||
} catch {
|
||||
throw new UnauthorizedException('Invalid token');
|
||||
}
|
||||
|
||||
if (!payload || typeof payload === 'string') {
|
||||
throw new UnauthorizedException('Invalid token');
|
||||
}
|
||||
|
||||
const user = await this.userService.getUserBySub(payload.sub);
|
||||
if (!user) throw new UnauthorizedException('Invalid token');
|
||||
|
||||
return user;
|
||||
}
|
||||
}
|
15
src/shared/decorators/token.decorator.ts
Normal file
15
src/shared/decorators/token.decorator.ts
Normal file
@ -0,0 +1,15 @@
|
||||
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||
import { Request } from 'express';
|
||||
|
||||
/**
|
||||
* Get the token from the response.
|
||||
*/
|
||||
export const Token = createParamDecorator(
|
||||
(data: unknown, ctx: ExecutionContext) => {
|
||||
const request = ctx.switchToHttp().getRequest() as Request;
|
||||
const authHeader = request.header('authorization');
|
||||
if (!authHeader) return null;
|
||||
const [, token] = authHeader.split(' ');
|
||||
return token;
|
||||
},
|
||||
);
|
13
src/shared/decorators/user.decorator.ts
Normal file
13
src/shared/decorators/user.decorator.ts
Normal file
@ -0,0 +1,13 @@
|
||||
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||
import { Response } from 'express';
|
||||
import { User } from 'src/objects/user/user.entity';
|
||||
|
||||
/**
|
||||
* Get the user from the response.
|
||||
*/
|
||||
export const LoggedInUser = createParamDecorator(
|
||||
(data: unknown, ctx: ExecutionContext) => {
|
||||
const response = ctx.switchToHttp().getResponse() as Response;
|
||||
return response.locals.user as User;
|
||||
},
|
||||
);
|
5
src/shared/dto/constructable.dto.ts
Normal file
5
src/shared/dto/constructable.dto.ts
Normal file
@ -0,0 +1,5 @@
|
||||
export class ConstructableDto<T> {
|
||||
constructor(obj: Partial<T>) {
|
||||
Object.assign(this, obj);
|
||||
}
|
||||
}
|
25
src/shared/guards/auth.guard.ts
Normal file
25
src/shared/guards/auth.guard.ts
Normal file
@ -0,0 +1,25 @@
|
||||
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
|
||||
@Injectable()
|
||||
export class AuthGuard implements CanActivate {
|
||||
constructor(private readonly authService: AuthService) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const http = context.switchToHttp();
|
||||
const request = http.getRequest();
|
||||
const response = http.getResponse();
|
||||
|
||||
const authHeader = request.header('authorization');
|
||||
if (!authHeader) return false;
|
||||
const [, token] = authHeader.split(' ');
|
||||
if (!token) return false;
|
||||
|
||||
const user = await this.authService.getUserFromJWT(token);
|
||||
if (!user) return false;
|
||||
|
||||
response.locals.user = user;
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
8
src/shared/secrets/secrets.module.ts
Normal file
8
src/shared/secrets/secrets.module.ts
Normal file
@ -0,0 +1,8 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { secretsProviders } from './secrets.providers';
|
||||
|
||||
@Module({
|
||||
providers: [...secretsProviders],
|
||||
exports: [...secretsProviders],
|
||||
})
|
||||
export class SecretsModule {}
|
28
src/shared/secrets/secrets.providers.ts
Normal file
28
src/shared/secrets/secrets.providers.ts
Normal file
@ -0,0 +1,28 @@
|
||||
import { join } from 'path';
|
||||
import { readFile } from 'fs/promises';
|
||||
import { FactoryProvider, ValueProvider } from '@nestjs/common';
|
||||
|
||||
export const secretsProviders = [
|
||||
{
|
||||
provide: 'PRIVATE_PATH',
|
||||
useValue: join(process.cwd(), 'private'),
|
||||
} as ValueProvider<string>,
|
||||
{
|
||||
provide: 'JWT_PRIVATE_KEY',
|
||||
useFactory: async (path: string) => readFile(join(path, 'jwt.private.pem')),
|
||||
inject: ['PRIVATE_PATH'],
|
||||
} as FactoryProvider<Buffer>,
|
||||
{
|
||||
provide: 'JWT_PUBLIC_KEY',
|
||||
useFactory: async (path: string) => readFile(join(path, 'jwt.public.pem')),
|
||||
inject: ['PRIVATE_PATH'],
|
||||
} as FactoryProvider<Buffer>,
|
||||
{
|
||||
provide: 'JWT_JWKS',
|
||||
useFactory: async (path: string) =>
|
||||
JSON.parse(
|
||||
await readFile(join(path, 'jwks.json'), { encoding: 'utf-8' }),
|
||||
),
|
||||
inject: ['PRIVATE_PATH'],
|
||||
} as FactoryProvider<Record<string, unknown>>,
|
||||
];
|
24
test/app.e2e-spec.ts
Normal file
24
test/app.e2e-spec.ts
Normal file
@ -0,0 +1,24 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import * as request from 'supertest';
|
||||
import { AppModule } from './../src/app.module';
|
||||
|
||||
describe('AppController (e2e)', () => {
|
||||
let app: INestApplication;
|
||||
|
||||
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!');
|
||||
});
|
||||
});
|
9
test/jest-e2e.json
Normal file
9
test/jest-e2e.json
Normal file
@ -0,0 +1,9 @@
|
||||
{
|
||||
"moduleFileExtensions": ["js", "json", "ts"],
|
||||
"rootDir": ".",
|
||||
"testEnvironment": "node",
|
||||
"testRegex": ".e2e-spec.ts$",
|
||||
"transform": {
|
||||
"^.+\\.(t|j)s$": "ts-jest"
|
||||
}
|
||||
}
|
4
tsconfig.build.json
Normal file
4
tsconfig.build.json
Normal file
@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
|
||||
}
|
22
tsconfig.json
Normal file
22
tsconfig.json
Normal file
@ -0,0 +1,22 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"declaration": true,
|
||||
"removeComments": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"experimentalDecorators": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"target": "es2017",
|
||||
"sourceMap": true,
|
||||
"outDir": "./dist",
|
||||
"baseUrl": "./",
|
||||
"incremental": true,
|
||||
"skipLibCheck": true,
|
||||
"strictNullChecks": false,
|
||||
"noImplicitAny": false,
|
||||
"strictBindCallApply": false,
|
||||
"forceConsistentCasingInFileNames": false,
|
||||
"noFallthroughCasesInSwitch": false,
|
||||
"esModuleInterop": true
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user