Compare commits
35 Commits
main
...
developmen
| Author | SHA1 | Date |
|---|---|---|
|
|
9dd8740171 | |
|
|
4e6774a15b | |
|
|
e4f6afbc93 | |
|
|
61529f7d94 | |
|
|
9543d136aa | |
|
|
456203f5cf | |
|
|
82b1d4825b | |
|
|
4ec9031005 | |
|
|
7a5521648c | |
|
|
ca98adc338 | |
|
|
405ba2e95d | |
|
|
7452e05a92 | |
|
|
bd12fe02ae | |
|
|
a00c2942f5 | |
|
|
768f0a5daf | |
|
|
c2fd263f27 | |
|
|
ac1980566a | |
|
|
db0ae34948 | |
|
|
81184a8acc | |
|
|
a830cc079d | |
|
|
a986ddbb95 | |
|
|
9232da69d3 | |
|
|
aa8f0b8f31 | |
|
|
1b87dee60d | |
|
|
b54bbe2db2 | |
|
|
924b538559 | |
|
|
0ce522d04a | |
|
|
ccb5c172ae | |
|
|
cbe62d8734 | |
|
|
e9cb161f90 | |
|
|
6cf7ce1397 | |
|
|
f39dc541e1 | |
|
|
2e10de9758 | |
|
|
b4b752ca3a | |
|
|
8ca2d34dc6 |
|
|
@ -0,0 +1,7 @@
|
|||
node_modules
|
||||
dist
|
||||
.dockerignore
|
||||
.git
|
||||
.env
|
||||
npm-debug.log
|
||||
api_env.env
|
||||
|
|
@ -0,0 +1,64 @@
|
|||
# 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
|
||||
env
|
||||
.env
|
||||
**/.prisma-cache
|
||||
|
||||
venv/
|
||||
.vscode/
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
{
|
||||
"git.ignoreLimitWarning": true
|
||||
}
|
||||
63
README.md
63
README.md
|
|
@ -1,3 +1,62 @@
|
|||
# production-evyos-systems-and-services-4
|
||||
# Backend
|
||||
|
||||
production-evyos-systems-and-services-4
|
||||
```bash
|
||||
docker compose up --build
|
||||
```
|
||||
|
||||
```bash
|
||||
docker compose -f docker-compose.dev.yml up --build
|
||||
```
|
||||
|
||||
```bash
|
||||
docker compose down
|
||||
```
|
||||
|
||||
```bash
|
||||
docker compose -f docker-compose.dev.yml down
|
||||
```
|
||||
|
||||
NEST start:
|
||||
root : sudo npm i -g @nestjs/cli
|
||||
cd backend && npm install --save-dev @types/node
|
||||
|
||||
docker volume rm production-evyos-systems-and-services-4_node_modules
|
||||
docker builder prune --all
|
||||
|
||||
npm install @prisma/client
|
||||
npm install -D prisma
|
||||
npm install class-validator class-transformer --legacy-peer-deps
|
||||
|
||||
npx prisma generate # generate client
|
||||
npx prisma db pull # update local schema
|
||||
|
||||
npx prisma db seed # seed database
|
||||
|
||||
nest generate module
|
||||
nest generate service
|
||||
nest generate controller
|
||||
|
||||
or / alias
|
||||
nest g module
|
||||
nest g service
|
||||
nest g controller
|
||||
|
||||
npm install @liaoliaots/nestjs-redis ioredis --legacy-peer-deps
|
||||
|
||||
npx prisma migrate dev --name "comment" # good for production creates step of migration
|
||||
npx prisma db push # update remote schema # not good for production creates no step of migration
|
||||
|
||||
npx prisma validate
|
||||
npx prisma format
|
||||
|
||||
# Frontend
|
||||
|
||||
npx create-next-app@latest
|
||||
|
||||
!npm install next-intl now towking with latest next js
|
||||
npm install --save nestjs-i18n
|
||||
npm install ioredis
|
||||
npm install -D daisyui@latest
|
||||
npm install tailwindcss @tailwindcss/postcss daisyui@latest
|
||||
npm install lucide-react
|
||||
npm install next-crypto
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"singleQuote": true,
|
||||
"trailingComma": "all"
|
||||
}
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
# --- Build Aşaması ---
|
||||
FROM node:20-alpine AS builder
|
||||
|
||||
WORKDIR /usr/src/app
|
||||
|
||||
COPY ServicesApi/package*.json ./
|
||||
|
||||
RUN npm install -g npm@latest
|
||||
RUN npm ci --legacy-peer-deps
|
||||
|
||||
COPY ServicesApi .
|
||||
|
||||
RUN npm run build
|
||||
|
||||
# --- Prod Image ---
|
||||
FROM node:20-alpine AS production
|
||||
|
||||
WORKDIR /usr/src/app
|
||||
ENV NODE_ENV=production
|
||||
|
||||
COPY --from=builder /usr/src/app/dist ./dist
|
||||
COPY --from=builder /usr/src/app/node_modules ./node_modules
|
||||
COPY --from=builder /usr/src/app/package.json ./package.json
|
||||
|
||||
RUN npm prune --production
|
||||
|
||||
USER node
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
CMD ["node", "dist/main.js"]
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
FROM node:20-alpine
|
||||
|
||||
WORKDIR /usr/src/app
|
||||
|
||||
# Npm güncelle (opsiyonel)
|
||||
RUN npm install -g npm@latest
|
||||
|
||||
# Global Nest CLI kur (start:dev için)
|
||||
RUN npm install -g @nestjs/cli
|
||||
|
||||
# package.json ve lock dosyalarını kopyala
|
||||
COPY backend/package*.json ./
|
||||
|
||||
# Tüm bağımlılıkları kur (dev + prod)
|
||||
RUN npm ci
|
||||
|
||||
# Kodları kopyala
|
||||
COPY backend .
|
||||
|
||||
# Uygulamayı dev modda başlat (hot reload ile)
|
||||
CMD ["npm", "run", "start:dev"]
|
||||
|
||||
EXPOSE 3000
|
||||
|
|
@ -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>
|
||||
<!--[](https://opencollective.com/nest#backer)
|
||||
[](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).
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
MONGO_ENGINE=mongodb
|
||||
MONGO_DB=appdb
|
||||
MONGO_HOST=10.10.2.13
|
||||
MONGO_PORT=27017
|
||||
MONGO_USER=appuser
|
||||
MONGO_AUTH_DB=appdb
|
||||
MONGO_PASSWORD=apppassword
|
||||
|
||||
POSTGRES_USER=postgres
|
||||
POSTGRES_PASSWORD=password
|
||||
POSTGRES_DB=postgres
|
||||
POSTGRES_HOST=10.10.2.14
|
||||
POSTGRES_PORT=5432
|
||||
POSTGRES_ENGINE=postgresql+psycopg2
|
||||
POSTGRES_POOL_PRE_PING=True
|
||||
POSTGRES_POOL_SIZE=20
|
||||
POSTGRES_MAX_OVERFLOW=10
|
||||
POSTGRES_POOL_RECYCLE=600
|
||||
POSTGRES_POOL_TIMEOUT=30
|
||||
POSTGRES_ECHO=True
|
||||
DATABASE_URL="postgresql://postgres:password@10.10.2.14:5432/sample_db?schema=public"
|
||||
|
||||
REDIS_HOST=10.10.2.15
|
||||
REDIS_PASSWORD=your_strong_password_here
|
||||
REDIS_PORT=6379
|
||||
REDIS_DB=0
|
||||
|
||||
API_ACCESS_EMAIL_EXT=evyos.com.tr
|
||||
API_ALGORITHM=HS256
|
||||
API_ACCESS_TOKEN_LENGTH=90
|
||||
API_REFRESHER_TOKEN_LENGTH=144
|
||||
API_EMAIL_HOST=10.10.2.36
|
||||
API_DATETIME_FORMAT=YYYY-MM-DD HH:mm:ss Z
|
||||
API_FORGOT_LINK=https://www.evyos.com.tr/password/create?tokenUrl=
|
||||
API_VERSION=0.1.001
|
||||
API_ACCESS_TOKEN_TAG=eys-acs-tkn
|
||||
|
||||
EMAIL_HOST=10.10.2.34
|
||||
EMAIL_USERNAME=karatay@mehmetkaratay.com.tr
|
||||
EMAIL_PASSWORD=system
|
||||
EMAIL_PORT=587
|
||||
EMAIL_SEND=0
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
// @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'
|
||||
},
|
||||
},
|
||||
);
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
{
|
||||
"$schema": "https://json.schemastore.org/nest-cli",
|
||||
"collection": "@nestjs/schematics",
|
||||
"sourceRoot": "src",
|
||||
"compilerOptions": {
|
||||
"deleteOutDir": true
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,85 @@
|
|||
{
|
||||
"name": "backend",
|
||||
"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"
|
||||
},
|
||||
"dependencies": {
|
||||
"@liaoliaots/nestjs-redis": "^10.0.0",
|
||||
"@nestjs/common": "^11.0.1",
|
||||
"@nestjs/core": "^11.0.1",
|
||||
"@nestjs/platform-express": "^11.0.1",
|
||||
"@prisma/client": "^6.12.0",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.2",
|
||||
"ioredis": "^5.6.1",
|
||||
"mongodb": "^6.18.0",
|
||||
"otplib": "^12.0.1",
|
||||
"qrcode": "^1.5.4",
|
||||
"redis": "^5.6.1",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.1",
|
||||
"uuid": "^11.1.0",
|
||||
"zod": "^4.0.10"
|
||||
},
|
||||
"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",
|
||||
"@swc/cli": "^0.6.0",
|
||||
"@swc/core": "^1.10.7",
|
||||
"@types/express": "^5.0.0",
|
||||
"@types/jest": "^29.5.14",
|
||||
"@types/node": "^22.17.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": "^29.7.0",
|
||||
"prettier": "^3.4.2",
|
||||
"prisma": "^6.12.0",
|
||||
"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"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
import { Module } from '@nestjs/common';
|
||||
import { PrismaService } from '@/src/prisma.service';
|
||||
|
||||
@Module({
|
||||
providers: [PrismaService],
|
||||
exports: [PrismaService],
|
||||
})
|
||||
export class PrismaModule {}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,18 @@
|
|||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { AccountsController } from './accounts.controller';
|
||||
|
||||
describe('AccountsController', () => {
|
||||
let controller: AccountsController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [AccountsController],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<AccountsController>(AccountsController);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Put,
|
||||
Delete,
|
||||
Param,
|
||||
Body,
|
||||
HttpCode,
|
||||
UseGuards,
|
||||
NotFoundException,
|
||||
Req,
|
||||
Query,
|
||||
} from '@nestjs/common';
|
||||
import { AccountsService } from './accounts.service';
|
||||
import { AuthControlGuard, EndpointControlGuard } from '@/src/middleware/access-control.guard';
|
||||
import { Navigator } from '@/src/utils/navigator/navigator';
|
||||
|
||||
@Controller('accounts')
|
||||
export class AccountsController {
|
||||
|
||||
constructor(
|
||||
private accountsService: AccountsService,
|
||||
private navigator: Navigator
|
||||
) { }
|
||||
|
||||
@Get('events')
|
||||
@HttpCode(200)
|
||||
@UseGuards(AuthControlGuard)
|
||||
async getEvents(@Query() query: any) {
|
||||
const { userToken } = query;
|
||||
if (!userToken) { throw new NotFoundException('User token is missing or null') }
|
||||
const events = await this.navigator.getInfos(this.accountsService, userToken)
|
||||
return { events, message: "Events fetched successfully" };
|
||||
}
|
||||
|
||||
@Post('filter')
|
||||
@HttpCode(200)
|
||||
@UseGuards(AuthControlGuard, EndpointControlGuard)
|
||||
async filterAccounts(@Body() query: any, @Req() req: any) { return await this.navigator.getFunction(req, this.accountsService.mapper, query) }
|
||||
}
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
import { Module } from '@nestjs/common';
|
||||
import { AccountsService } from './accounts.service';
|
||||
import { AccountsController } from './accounts.controller';
|
||||
import { PrismaModule } from '@/prisma/prisma.module';
|
||||
import { CacheService } from '../database/redis/redis.service';
|
||||
import { UtilsModule } from '../utils/utils.module';
|
||||
import { RedisModule } from '../database/redis/redis.module';
|
||||
import {
|
||||
AuthControlGuard,
|
||||
EndpointControlGuard,
|
||||
} from '@/src/middleware/access-control.guard';
|
||||
import { SuperUsersService } from './superusers/superusers.service';
|
||||
import { UrlHandler } from '../utils/navigator/urlHandler';
|
||||
import { Navigator } from '@/src/utils/navigator/navigator';
|
||||
import { NavigatorModule } from '../navigator/navigator.module';
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule, UtilsModule, RedisModule, NavigatorModule],
|
||||
providers: [
|
||||
AccountsService,
|
||||
AuthControlGuard,
|
||||
EndpointControlGuard,
|
||||
SuperUsersService,
|
||||
UrlHandler,
|
||||
Navigator,
|
||||
],
|
||||
controllers: [AccountsController],
|
||||
})
|
||||
export class AccountsModule {
|
||||
constructor() { }
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { AccountsService } from './accounts.service';
|
||||
|
||||
describe('AccountsService', () => {
|
||||
let service: AccountsService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [AccountsService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<AccountsService>(AccountsService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
import { Injectable } from '@nestjs/common';
|
||||
import { SuperUsersService } from './superusers/superusers.service';
|
||||
import { EventsService } from '../navigator/events/events.service';
|
||||
|
||||
@Injectable()
|
||||
export class AccountsService {
|
||||
mapper: any
|
||||
|
||||
constructor(
|
||||
private superUsersService: SuperUsersService,
|
||||
private eventService: EventsService,
|
||||
) {
|
||||
this.mapper = {
|
||||
"j0adQOsJBR0xq24dxLKdDU9EQRmt4gzE05CmhA": this.superUsersService,
|
||||
}
|
||||
}
|
||||
|
||||
async onModuleInit() {
|
||||
Object.entries(this.mapper).map(async ([key, value]) => {
|
||||
const service = value as any
|
||||
await this.eventService.setEvents(service.events, "AccountsService")
|
||||
})
|
||||
// const accountPages = await fetch(
|
||||
// "http://localhost:3000/pages",
|
||||
// {
|
||||
// method: 'POST',
|
||||
// headers: {
|
||||
// 'Content-Type': 'application/json',
|
||||
// },
|
||||
// body: JSON.stringify({
|
||||
// token: 'j0adQOsJBR0xq24dxLKdDU9EQRmt4gzE05CmhA',
|
||||
// pages: {
|
||||
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
// )
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { SuperusersService } from './superusers.service';
|
||||
|
||||
describe('SuperusersService', () => {
|
||||
let service: SuperusersService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [SuperusersService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<SuperusersService>(SuperusersService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,54 @@
|
|||
import { PaginationHelper } from '@/src/utils/pagination-helper';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { PaginationInfo } from '@/src/utils/pagination-helper';
|
||||
import { PrismaService } from '@/src/prisma.service';
|
||||
import { UrlHandler } from '@/src/utils/navigator/urlHandler';
|
||||
|
||||
@Injectable()
|
||||
export class SuperUsersService {
|
||||
userToken: string = "j0adQOsJBR0xq24dxLKdDU9EQRmt4gzE05CmhA"
|
||||
constructor(
|
||||
private paginationHelper: PaginationHelper,
|
||||
private prisma: PrismaService,
|
||||
private urlHandler: UrlHandler,
|
||||
) { }
|
||||
|
||||
events = {
|
||||
"e6hewIe7YqbQZHO3:j0adQOsJBR0xq24dxLKdDU9EQRmt4gzE05CmhA": [
|
||||
{
|
||||
"key": "qt5P0xoeThjNT9EuWfwBgxsntHY5ydRtKFr1pgKGcgxx",
|
||||
"endpoint": "/accounts/filter:POST",
|
||||
"eToken": "e6hewIe7YqbQZHO3",
|
||||
"token": "j0adQOsJBR0xq24dxLKdDU9EQRmt4gzE05CmhA",
|
||||
"description": "Super Users Account Filter",
|
||||
"isDefault": true,
|
||||
"query": { "query": true, "page": false, "pageSize": false },
|
||||
"pages": []
|
||||
}
|
||||
]
|
||||
};
|
||||
mapper = {
|
||||
"e6hewIe7YqbQZHO3:j0adQOsJBR0xq24dxLKdDU9EQRmt4gzE05CmhA:qt5P0xoeThjNT9EuWfwBgxsntHY5ydRtKFr1pgKGcgxx": (query: any) => this.filter(query),
|
||||
}
|
||||
|
||||
async getEvents() { return this.urlHandler.getEvents(this.events, this.mapper) }
|
||||
|
||||
async infoEvents(userToken: string) { return Object.entries(this.events).filter(([key]) => key.endsWith(userToken)) }
|
||||
|
||||
async filter(query: any & { page?: number; pageSize?: number }): Promise<{ pagination: PaginationInfo; data: any[] }> {
|
||||
const result = await this.paginationHelper.findWithPagination(query, this.prisma.account_records);
|
||||
const { pagination, data } = result;
|
||||
|
||||
if (data.length === 0) { return { pagination, data: [] } }
|
||||
const resultRefined = data.map((rec: any) => ({
|
||||
...rec,
|
||||
build_decision_book_payments: rec.build_decision_book_payments?.map(
|
||||
(pmt: any) => ({
|
||||
...pmt,
|
||||
ratePercent: ((pmt.payment_amount / rec.currency_value) * 100).toFixed(2) + '%',
|
||||
}),
|
||||
),
|
||||
}));
|
||||
return { pagination, data: resultRefined };
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
http://localhost:3000/accounts/filter
|
||||
|
||||
{
|
||||
"where": {
|
||||
"build_parts": {
|
||||
"part_code": {
|
||||
"contains": "10",
|
||||
"mode": "insensitive"
|
||||
}
|
||||
}
|
||||
},
|
||||
"select": {
|
||||
"process_comment": true,
|
||||
"bank_date": true,
|
||||
"currency_value": true,
|
||||
"build_parts": {
|
||||
"select": {
|
||||
"part_code": true
|
||||
}
|
||||
},
|
||||
"build_decision_book_payments": {
|
||||
"select": {
|
||||
"payment_amount": true,
|
||||
"process_date": true,
|
||||
"build_decision_book_items": {
|
||||
"select": {
|
||||
"item_order": true,
|
||||
"item_comment": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"page": 2,
|
||||
"pageSize": 5
|
||||
}
|
||||
|
|
@ -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!');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
import {
|
||||
MiddlewareConsumer,
|
||||
Module,
|
||||
NestModule,
|
||||
RequestMethod,
|
||||
} from '@nestjs/common';
|
||||
import { AppController } from './app.controller';
|
||||
import { AppService } from './app.service';
|
||||
import { UsersModule } from './users/users.module';
|
||||
import { PrismaModule } from '../prisma/prisma.module';
|
||||
import { AccountsModule } from './accounts/accounts.module';
|
||||
import { AuthModule } from './auth/auth.module';
|
||||
import { RedisModule } from './database/redis/redis.module';
|
||||
import { LoggerMiddleware } from '@/src/middleware/logger.middleware';
|
||||
import { DiscoveryModule } from '@nestjs/core';
|
||||
import { NavigatorModule } from './navigator/navigator.module';
|
||||
|
||||
const modulesList = [UsersModule, AccountsModule, AuthModule];
|
||||
const serviceModuleList = [
|
||||
PrismaModule,
|
||||
RedisModule.forRootWithConfig(true),
|
||||
DiscoveryModule,
|
||||
];
|
||||
const controllersList = [AppController];
|
||||
const providersList = [AppService];
|
||||
const exportsList = [];
|
||||
|
||||
@Module({
|
||||
imports: [...serviceModuleList, ...modulesList, NavigatorModule],
|
||||
controllers: controllersList,
|
||||
providers: providersList,
|
||||
exports: exportsList,
|
||||
})
|
||||
export class AppModule implements NestModule {
|
||||
configure(consumer: MiddlewareConsumer) {
|
||||
consumer
|
||||
.apply(LoggerMiddleware)
|
||||
.exclude(
|
||||
{ path: 'accounts', method: RequestMethod.ALL },
|
||||
{ path: 'users/*path', method: RequestMethod.ALL },
|
||||
)
|
||||
.forRoutes('*');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
@Injectable()
|
||||
export class AppService {
|
||||
getHello(): string {
|
||||
return 'Hello World!';
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,80 @@
|
|||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Put,
|
||||
Delete,
|
||||
Param,
|
||||
Body,
|
||||
HttpCode,
|
||||
UseGuards,
|
||||
Req,
|
||||
} from '@nestjs/common';
|
||||
import { AuthService } from './auth.service';
|
||||
import { userLoginValidator } from './login/dtoValidator';
|
||||
import { userSelectValidator } from './select/dtoValidator';
|
||||
import { userLogoutValidator } from './logout/dtoValidator';
|
||||
import { AuthControlGuard } from '../middleware/access-control.guard';
|
||||
import { userCreatePasswordValidator } from './password/create/dtoValidator';
|
||||
import { userChangePasswordValidator } from './password/change/dtoValidator';
|
||||
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
constructor(private readonly authService: AuthService) {}
|
||||
|
||||
@Post('login')
|
||||
@HttpCode(200)
|
||||
async login(@Body() query: userLoginValidator) {
|
||||
return await this.authService.login(query);
|
||||
}
|
||||
|
||||
@Post('select')
|
||||
@HttpCode(200)
|
||||
@UseGuards(AuthControlGuard)
|
||||
async select(@Body() query: userSelectValidator, @Req() req: Request) {
|
||||
return await this.authService.select(query, req);
|
||||
}
|
||||
|
||||
@Post('/password/create')
|
||||
@HttpCode(200)
|
||||
async createPassword(@Body() query: userCreatePasswordValidator) {
|
||||
return await this.authService.createPassword(query);
|
||||
}
|
||||
|
||||
@Post('/password/change')
|
||||
@HttpCode(200)
|
||||
@UseGuards(AuthControlGuard)
|
||||
async changePassword(
|
||||
@Body() query: userChangePasswordValidator,
|
||||
@Req() req: Request,
|
||||
) {
|
||||
return await this.authService.changePassword(query, req);
|
||||
}
|
||||
|
||||
@Post('/password/reset')
|
||||
@HttpCode(200)
|
||||
async resetPassword() {
|
||||
return { message: 'Password reset successfully' };
|
||||
}
|
||||
|
||||
@Post('/password/verify-otp')
|
||||
@HttpCode(200)
|
||||
@UseGuards(AuthControlGuard)
|
||||
async verifyOtp() {
|
||||
return { message: 'Password verified successfully' };
|
||||
}
|
||||
|
||||
@Post('logout')
|
||||
@HttpCode(200)
|
||||
@UseGuards(AuthControlGuard)
|
||||
async logout(@Body() query: userLogoutValidator) {
|
||||
return { message: 'Logout successful' };
|
||||
}
|
||||
|
||||
@Post('disconnect')
|
||||
@HttpCode(200)
|
||||
@UseGuards(AuthControlGuard)
|
||||
async disconnect() {
|
||||
return { message: 'Disconnect successful' };
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
import { Module } from '@nestjs/common';
|
||||
import { AuthController } from '@/src/auth/auth.controller';
|
||||
import { LoginService } from '@/src/auth/login/login.service';
|
||||
import { LogoutService } from '@/src/auth/logout/logout.service';
|
||||
import { AuthService } from '@/src/auth/auth.service';
|
||||
import { SelectService } from '@/src/auth/select/select.service';
|
||||
import { UtilsModule } from '@/src/utils/utils.module';
|
||||
import { PrismaService } from '../prisma.service';
|
||||
import { CreatePasswordService } from './password/create/create.service';
|
||||
import { ResetPasswordService } from './password/reset/reset.service';
|
||||
import { ChangePasswordService } from './password/change/change.service';
|
||||
import { VerifyOtpService } from './password/verify-otp/verify-otp.service';
|
||||
import { DisconnectService } from './disconnect/disconnect.service';
|
||||
import { MongoModule } from '@/src/database/mongo/mongo.module';
|
||||
import { MongoService } from '@/src/database/mongo/mongo.service';
|
||||
import { NavigatorModule } from '../navigator/navigator.module';
|
||||
|
||||
@Module({
|
||||
imports: [UtilsModule, MongoModule, NavigatorModule],
|
||||
controllers: [AuthController],
|
||||
providers: [
|
||||
AuthService,
|
||||
LoginService,
|
||||
LogoutService,
|
||||
SelectService,
|
||||
CreatePasswordService,
|
||||
ChangePasswordService,
|
||||
ResetPasswordService,
|
||||
VerifyOtpService,
|
||||
DisconnectService,
|
||||
MongoService,
|
||||
PrismaService,
|
||||
],
|
||||
exports: [AuthService],
|
||||
})
|
||||
export class AuthModule { }
|
||||
|
|
@ -0,0 +1,57 @@
|
|||
import { Injectable } from '@nestjs/common';
|
||||
import { LoginService } from './login/login.service';
|
||||
import { LogoutService } from './logout/logout.service';
|
||||
import { SelectService } from './select/select.service';
|
||||
import { userLoginValidator } from '@/src/auth/login/dtoValidator';
|
||||
import { userSelectValidator } from './select/dtoValidator';
|
||||
import { userLogoutValidator } from './logout/dtoValidator';
|
||||
import { CreatePasswordService } from './password/create/create.service';
|
||||
import { ResetPasswordService } from './password/reset/reset.service';
|
||||
import { ChangePasswordService } from './password/change/change.service';
|
||||
import { VerifyOtpService } from './password/verify-otp/verify-otp.service';
|
||||
import { DisconnectService } from './disconnect/disconnect.service';
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
constructor(
|
||||
private loginService: LoginService,
|
||||
private logoutService: LogoutService,
|
||||
private selectService: SelectService,
|
||||
private createPasswordService: CreatePasswordService,
|
||||
private changePasswordService: ChangePasswordService,
|
||||
private resetPasswordService: ResetPasswordService,
|
||||
private verifyOtpService: VerifyOtpService,
|
||||
private disconnectService: DisconnectService,
|
||||
) {}
|
||||
|
||||
async login(dto: userLoginValidator) {
|
||||
return await this.loginService.run(dto);
|
||||
}
|
||||
|
||||
async logout(dto: userLogoutValidator) {
|
||||
return await this.logoutService.run(dto);
|
||||
}
|
||||
|
||||
async select(dto: userSelectValidator, req: Request) {
|
||||
return await this.selectService.run(dto, req);
|
||||
}
|
||||
|
||||
async createPassword(dto: any) {
|
||||
return await this.createPasswordService.run(dto);
|
||||
}
|
||||
|
||||
async changePassword(dto: any, req: Request) {
|
||||
return await this.changePasswordService.run(dto, req);
|
||||
}
|
||||
|
||||
async resetPassword(dto: any) {
|
||||
return await this.resetPasswordService.run(dto);
|
||||
}
|
||||
|
||||
async verifyOtp(dto: any) {
|
||||
return await this.verifyOtpService.run(dto);
|
||||
}
|
||||
async disconnect() {
|
||||
return await this.disconnectService.run();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { DisconnectService } from './disconnect.service';
|
||||
|
||||
describe('DisconnectService', () => {
|
||||
let service: DisconnectService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [DisconnectService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<DisconnectService>(DisconnectService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
@Injectable()
|
||||
export class DisconnectService {
|
||||
async run() {
|
||||
return { message: 'Disconnect successful' };
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
import { IsOptional, IsString, IsBoolean } from 'class-validator';
|
||||
|
||||
export class userLoginValidator {
|
||||
@IsString()
|
||||
accessKey: string;
|
||||
|
||||
@IsString()
|
||||
password: string;
|
||||
|
||||
@IsBoolean()
|
||||
@IsOptional()
|
||||
rememberMe?: boolean;
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { LoginService } from './login.service';
|
||||
|
||||
describe('LoginService', () => {
|
||||
let service: LoginService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [LoginService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<LoginService>(LoginService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,167 @@
|
|||
import { Injectable } from '@nestjs/common';
|
||||
import { userLoginValidator } from '@/src/auth/login/dtoValidator';
|
||||
import { RedisHandlers } from '@/src/utils/store/redisHandlers';
|
||||
import { PasswordHandlers } from '@/src/utils/store/loginHandler';
|
||||
import { PrismaService } from '@/src/prisma.service';
|
||||
import { AuthTokenSchema } from '@/src/types/auth/token';
|
||||
|
||||
@Injectable()
|
||||
export class LoginService {
|
||||
constructor(
|
||||
private readonly redis: RedisHandlers,
|
||||
private readonly passHandlers: PasswordHandlers,
|
||||
private readonly prisma: PrismaService,
|
||||
) { }
|
||||
|
||||
async run(dto: userLoginValidator) {
|
||||
const foundUser = await this.prisma.users.findFirstOrThrow({
|
||||
where: { email: dto.accessKey },
|
||||
});
|
||||
if (foundUser.password_token) {
|
||||
throw new Error('Password need to be set first');
|
||||
}
|
||||
const isPasswordValid = this.passHandlers.check_password(
|
||||
foundUser.uu_id,
|
||||
dto.password,
|
||||
foundUser.hash_password,
|
||||
);
|
||||
if (!isPasswordValid) {
|
||||
throw new Error('Invalid password');
|
||||
}
|
||||
const foundPerson = await this.prisma.people.findFirstOrThrow({
|
||||
where: { id: foundUser.id },
|
||||
});
|
||||
const alreadyExists = await this.redis.callExistingLoginToken(
|
||||
foundUser.uu_id,
|
||||
);
|
||||
if (alreadyExists) {
|
||||
return {
|
||||
token: alreadyExists,
|
||||
message: 'User already logged in',
|
||||
};
|
||||
} else {
|
||||
let selectList: any[] = [];
|
||||
if (foundUser.user_type === 'occupant') {
|
||||
const livingSpaces = await this.prisma.build_living_space.findMany({
|
||||
where: { people: { id: foundPerson.id } },
|
||||
orderBy: {
|
||||
build_parts: {
|
||||
build: {
|
||||
id: 'asc',
|
||||
},
|
||||
},
|
||||
},
|
||||
select: {
|
||||
uu_id: true,
|
||||
occupant_types: {
|
||||
select: {
|
||||
uu_id: true,
|
||||
occupant_code: true,
|
||||
occupant_type: true,
|
||||
// function_retriever: true,
|
||||
},
|
||||
},
|
||||
build_parts: {
|
||||
select: {
|
||||
uu_id: true,
|
||||
part_code: true,
|
||||
part_no: true,
|
||||
part_level: true,
|
||||
human_livable: true,
|
||||
api_enum_dropdown_build_parts_part_type_idToapi_enum_dropdown: {
|
||||
select: {
|
||||
uu_id: true,
|
||||
enum_class: true,
|
||||
value: true,
|
||||
},
|
||||
},
|
||||
build: {
|
||||
select: {
|
||||
uu_id: true,
|
||||
build_name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
selectList = livingSpaces;
|
||||
} else if (foundUser.user_type === 'employee') {
|
||||
const employees = await this.prisma.employees.findMany({
|
||||
where: { people: { id: foundPerson.id } },
|
||||
orderBy: {
|
||||
staff: {
|
||||
duties: {
|
||||
departments: {
|
||||
companies: {
|
||||
formal_name: 'asc',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
select: {
|
||||
uu_id: true,
|
||||
staff: {
|
||||
select: {
|
||||
uu_id: true,
|
||||
staff_code: true,
|
||||
// function_retriever: true,
|
||||
duties: {
|
||||
select: {
|
||||
uu_id: true,
|
||||
departments: {
|
||||
select: {
|
||||
uu_id: true,
|
||||
department_code: true,
|
||||
department_name: true,
|
||||
companies: {
|
||||
select: {
|
||||
uu_id: true,
|
||||
formal_name: true,
|
||||
public_name: true,
|
||||
addresses: {
|
||||
select: {
|
||||
comment_address: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
selectList = employees;
|
||||
}
|
||||
let fullName = `${foundPerson.firstname}`;
|
||||
if (foundPerson.middle_name) fullName += ` ${foundPerson.middle_name}`;
|
||||
if (foundPerson.birthname) fullName += ` ${foundPerson.birthname}`;
|
||||
fullName += ` ${foundPerson.surname}`;
|
||||
const redisData = AuthTokenSchema.parse({
|
||||
people: foundPerson,
|
||||
users: foundUser,
|
||||
credentials: {
|
||||
uuid: foundPerson.uu_id,
|
||||
fullName: fullName,
|
||||
},
|
||||
selectionList: {
|
||||
type: foundUser.user_type,
|
||||
list: selectList,
|
||||
},
|
||||
});
|
||||
|
||||
const accessToken = await this.redis.setLoginToRedis(
|
||||
redisData,
|
||||
foundUser.uu_id,
|
||||
);
|
||||
return {
|
||||
token: accessToken,
|
||||
message: 'Login successful',
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
import { IsString } from 'class-validator';
|
||||
|
||||
export class userLogoutValidator {
|
||||
@IsString()
|
||||
selected_uu_id: string;
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { LogoutService } from './logout.service';
|
||||
|
||||
describe('LogoutService', () => {
|
||||
let service: LogoutService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [LogoutService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<LogoutService>(LogoutService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
import { Injectable } from '@nestjs/common';
|
||||
import { userLogoutValidator } from '@/src/auth/logout/dtoValidator';
|
||||
|
||||
@Injectable()
|
||||
export class LogoutService {
|
||||
async run(dto: userLogoutValidator) {
|
||||
return dto;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { ChangeService } from './change.service';
|
||||
|
||||
describe('ChangeService', () => {
|
||||
let service: ChangeService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [ChangeService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<ChangeService>(ChangeService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,196 @@
|
|||
import { PrismaService } from '@/src/prisma.service';
|
||||
import {
|
||||
Injectable,
|
||||
BadRequestException,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { userChangePasswordValidator } from './dtoValidator';
|
||||
import { RedisHandlers } from '@/src/utils/store/redisHandlers';
|
||||
import { PasswordHandlers } from '@/src/utils/store/loginHandler';
|
||||
|
||||
@Injectable()
|
||||
export class ChangePasswordService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly redis: RedisHandlers,
|
||||
private readonly passHandlers: PasswordHandlers,
|
||||
) { }
|
||||
|
||||
private async syncPasswordHistory(
|
||||
foundUser: any,
|
||||
dto: userChangePasswordValidator,
|
||||
hashPassword: string,
|
||||
) {
|
||||
const passwordHistory = await this.prisma.password_history.findFirst({
|
||||
where: { userUUID: foundUser.uu_id },
|
||||
});
|
||||
console.log('passwordHistory', passwordHistory);
|
||||
console.log('dto', dto);
|
||||
console.log('hashPassword', hashPassword);
|
||||
|
||||
if (passwordHistory) {
|
||||
if (!passwordHistory.old_password_first) {
|
||||
await this.prisma.password_history.update({
|
||||
where: { id: passwordHistory.id },
|
||||
data: {
|
||||
password: hashPassword,
|
||||
old_password_first: dto.password,
|
||||
old_password_first_modified_at: new Date(),
|
||||
},
|
||||
});
|
||||
} else if (!passwordHistory.old_password_second) {
|
||||
await this.prisma.password_history.update({
|
||||
where: { id: passwordHistory.id },
|
||||
data: {
|
||||
password: hashPassword,
|
||||
old_password_second: dto.password,
|
||||
old_password_second_modified_at: new Date(),
|
||||
},
|
||||
});
|
||||
} else if (!passwordHistory.old_password_third) {
|
||||
await this.prisma.password_history.update({
|
||||
where: { id: passwordHistory.id },
|
||||
data: {
|
||||
password: hashPassword,
|
||||
old_password_third: dto.password,
|
||||
old_password_third_modified_at: new Date(),
|
||||
},
|
||||
});
|
||||
} else {
|
||||
const firstTimestamp = new Date(
|
||||
passwordHistory.old_password_first_modified_at,
|
||||
).getTime();
|
||||
const secondTimestamp = new Date(
|
||||
passwordHistory.old_password_second_modified_at,
|
||||
).getTime();
|
||||
const thirdTimestamp = new Date(
|
||||
passwordHistory.old_password_third_modified_at,
|
||||
).getTime();
|
||||
|
||||
let oldestIndex = 'first';
|
||||
let oldestTimestamp = firstTimestamp;
|
||||
|
||||
if (secondTimestamp < oldestTimestamp) {
|
||||
oldestIndex = 'second';
|
||||
oldestTimestamp = secondTimestamp;
|
||||
}
|
||||
if (thirdTimestamp < oldestTimestamp) {
|
||||
oldestIndex = 'third';
|
||||
}
|
||||
|
||||
await this.prisma.password_history.update({
|
||||
where: { id: passwordHistory.id },
|
||||
data: {
|
||||
password: hashPassword,
|
||||
...(oldestIndex === 'first'
|
||||
? {
|
||||
old_password_first: dto.password,
|
||||
old_password_first_modified_at: new Date(),
|
||||
}
|
||||
: oldestIndex === 'second'
|
||||
? {
|
||||
old_password_second: dto.password,
|
||||
old_password_second_modified_at: new Date(),
|
||||
}
|
||||
: {
|
||||
old_password_third: dto.password,
|
||||
old_password_third_modified_at: new Date(),
|
||||
}),
|
||||
},
|
||||
});
|
||||
}
|
||||
} else {
|
||||
await this.prisma.password_history.create({
|
||||
data: {
|
||||
userUUID: foundUser.uu_id,
|
||||
password: hashPassword,
|
||||
old_password_first: dto.password,
|
||||
old_password_first_modified_at: new Date(),
|
||||
old_password_second: '',
|
||||
old_password_second_modified_at: new Date(),
|
||||
old_password_third: '',
|
||||
old_password_third_modified_at: new Date(),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async run(dto: userChangePasswordValidator, req: Request) {
|
||||
const isValid = () => {
|
||||
const isOldPasswordDifferent = dto.password !== dto.oldPassword;
|
||||
const isPasswordMatchesWithRePassword = dto.password === dto.rePassword;
|
||||
return isOldPasswordDifferent && isPasswordMatchesWithRePassword;
|
||||
};
|
||||
|
||||
if (!isValid()) {
|
||||
throw new BadRequestException(
|
||||
'Passwords do not match or new password is the same as old password',
|
||||
);
|
||||
}
|
||||
const accessObject = await this.redis.getLoginFromRedis(req);
|
||||
const userFromRedis = accessObject?.value.users;
|
||||
if (!userFromRedis) {
|
||||
throw new UnauthorizedException('User not authenticated');
|
||||
}
|
||||
|
||||
const foundUser = await this.prisma.users.findFirstOrThrow({
|
||||
where: { uu_id: userFromRedis.uu_id },
|
||||
});
|
||||
|
||||
if (foundUser.password_token) {
|
||||
throw new BadRequestException('Set password first before changing');
|
||||
}
|
||||
const isPasswordValid = this.passHandlers.check_password(
|
||||
foundUser.uu_id,
|
||||
dto.oldPassword,
|
||||
foundUser.hash_password,
|
||||
);
|
||||
if (!isPasswordValid) {
|
||||
throw new UnauthorizedException('Invalid password');
|
||||
}
|
||||
|
||||
const passwordHistory = await this.prisma.password_history.findFirst({
|
||||
where: {
|
||||
userUUID: foundUser.uu_id,
|
||||
OR: [
|
||||
{
|
||||
old_password_first: {
|
||||
equals: dto.password,
|
||||
mode: 'insensitive',
|
||||
},
|
||||
},
|
||||
{
|
||||
old_password_second: {
|
||||
equals: dto.password,
|
||||
mode: 'insensitive',
|
||||
},
|
||||
},
|
||||
{
|
||||
old_password_third: {
|
||||
equals: dto.password,
|
||||
mode: 'insensitive',
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
if (passwordHistory) {
|
||||
throw new UnauthorizedException(
|
||||
'Invalid password, new password can not be same as old password',
|
||||
);
|
||||
}
|
||||
|
||||
const hashPassword = this.passHandlers.create_hashed_password(
|
||||
foundUser.uu_id,
|
||||
dto.password,
|
||||
);
|
||||
await this.prisma.users.update({
|
||||
where: { id: foundUser.id },
|
||||
data: {
|
||||
hash_password: hashPassword,
|
||||
},
|
||||
});
|
||||
await this.syncPasswordHistory(foundUser, dto, hashPassword);
|
||||
return { message: 'Password changed successfully' };
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
import { IsString } from 'class-validator';
|
||||
|
||||
export class userChangePasswordValidator {
|
||||
@IsString()
|
||||
oldPassword: string;
|
||||
|
||||
@IsString()
|
||||
password: string;
|
||||
|
||||
@IsString()
|
||||
rePassword: string;
|
||||
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { CreateService } from './create.service';
|
||||
|
||||
describe('CreateService', () => {
|
||||
let service: CreateService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [CreateService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<CreateService>(CreateService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,70 @@
|
|||
import { userCreatePasswordValidator } from './dtoValidator';
|
||||
import { PrismaService } from '@/src/prisma.service';
|
||||
import { PasswordHandlers } from '@/src/utils/store/loginHandler';
|
||||
import { Injectable, BadRequestException } from '@nestjs/common';
|
||||
|
||||
@Injectable()
|
||||
export class CreatePasswordService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly passHandlers: PasswordHandlers,
|
||||
) { }
|
||||
|
||||
async run(dto: userCreatePasswordValidator) {
|
||||
if (dto.password !== dto.rePassword) {
|
||||
throw new BadRequestException('Passwords do not match');
|
||||
}
|
||||
const foundUser = await this.prisma.users.findFirstOrThrow({
|
||||
where: { password_token: dto.passwordToken },
|
||||
});
|
||||
|
||||
const passwordExpiryDate = new Date(foundUser.password_expiry_begins);
|
||||
const passwordExpiryDay = foundUser.password_expires_day;
|
||||
const dayInMilliseconds = 24 * 60 * 60 * 1000;
|
||||
console.log(
|
||||
'exp : ',
|
||||
passwordExpiryDate,
|
||||
passwordExpiryDay,
|
||||
dayInMilliseconds,
|
||||
);
|
||||
const today = new Date().getTime();
|
||||
const comparasionDate = new Date(
|
||||
passwordExpiryDate.getTime() + passwordExpiryDay * dayInMilliseconds,
|
||||
).getTime();
|
||||
if (today >= comparasionDate) {
|
||||
throw new BadRequestException(
|
||||
'Password token is expired contact to your admin',
|
||||
);
|
||||
}
|
||||
|
||||
const hashPassword = this.passHandlers.create_hashed_password(
|
||||
foundUser.uu_id,
|
||||
dto.password,
|
||||
);
|
||||
|
||||
const updatedUser = await this.prisma.users.update({
|
||||
where: { id: foundUser.id },
|
||||
data: {
|
||||
hash_password: hashPassword,
|
||||
password_token: '',
|
||||
password_expiry_begins: new Date(),
|
||||
},
|
||||
});
|
||||
console.log('updatedUser');
|
||||
console.dir(updatedUser);
|
||||
await this.prisma.password_history.create({
|
||||
data: {
|
||||
userUUID: foundUser.uu_id,
|
||||
password: hashPassword,
|
||||
old_password_first: dto.password,
|
||||
old_password_first_modified_at: new Date(),
|
||||
old_password_second: '',
|
||||
old_password_second_modified_at: new Date(),
|
||||
old_password_third: '',
|
||||
old_password_third_modified_at: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
return { message: 'Password created successfully' };
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
import { IsString } from 'class-validator';
|
||||
|
||||
export class userCreatePasswordValidator {
|
||||
@IsString()
|
||||
passwordToken: string;
|
||||
|
||||
@IsString()
|
||||
password: string;
|
||||
|
||||
@IsString()
|
||||
rePassword: string;
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
import { IsString } from 'class-validator';
|
||||
|
||||
export class userResetPasswordValidator {
|
||||
@IsString()
|
||||
accessKey: string;
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { ResetService } from './reset.service';
|
||||
|
||||
describe('ResetService', () => {
|
||||
let service: ResetService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [ResetService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<ResetService>(ResetService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
import { Injectable, BadRequestException } from '@nestjs/common';
|
||||
import { userResetPasswordValidator } from './dtoValidator';
|
||||
import { PrismaService } from '@/src/prisma.service';
|
||||
import { PasswordHandlers } from '@/src/utils/store/loginHandler';
|
||||
|
||||
@Injectable()
|
||||
export class ResetPasswordService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly passHandlers: PasswordHandlers,
|
||||
) { }
|
||||
async run(dto: userResetPasswordValidator) {
|
||||
const foundUser = await this.prisma.users.findFirstOrThrow({
|
||||
where: {
|
||||
OR: [{ email: dto.accessKey }, { phone_number: dto.accessKey }],
|
||||
},
|
||||
});
|
||||
if (!foundUser) {
|
||||
throw new BadRequestException(
|
||||
'User not found. Please check your email or phone number',
|
||||
);
|
||||
}
|
||||
|
||||
await this.prisma.users.update({
|
||||
where: { id: foundUser.id },
|
||||
data: {
|
||||
password_token: this.passHandlers.generateRefreshToken(),
|
||||
password_expiry_begins: new Date(),
|
||||
password_expires_day: 30,
|
||||
},
|
||||
});
|
||||
return {
|
||||
message: 'Password reset token sent successfully',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
import { IsNumber, Max, Min } from 'class-validator';
|
||||
|
||||
export class userVerifyOtpValidator {
|
||||
@IsNumber()
|
||||
@Min(6)
|
||||
@Max(6)
|
||||
otp: number;
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { VerifyOtpService } from './verify-otp.service';
|
||||
|
||||
describe('VerifyOtpService', () => {
|
||||
let service: VerifyOtpService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [VerifyOtpService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<VerifyOtpService>(VerifyOtpService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
import { Injectable } from '@nestjs/common';
|
||||
import { authenticator } from 'otplib';
|
||||
import * as qrcode from 'qrcode';
|
||||
import { PrismaService } from '@/src/prisma.service';
|
||||
|
||||
@Injectable()
|
||||
export class VerifyOtpService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
generate2FASecret(username: string) {
|
||||
const serviceName = 'BenimUygulamam';
|
||||
const secret = authenticator.generateSecret();
|
||||
const otpauthUrl = authenticator.keyuri(username, serviceName, secret);
|
||||
return { secret, otpauthUrl };
|
||||
}
|
||||
|
||||
async generateQRCode(otpauthUrl: string): Promise<string> {
|
||||
return await qrcode.toDataURL(otpauthUrl);
|
||||
}
|
||||
|
||||
verify2FACode(code: string, secret: string): boolean {
|
||||
return authenticator.verify({ token: code, secret });
|
||||
}
|
||||
|
||||
async run(dto: any) {
|
||||
return dto;
|
||||
}
|
||||
}
|
||||
|
||||
// // controller veya resolver içinden
|
||||
// const { secret, otpauthUrl } = authService.generate2FASecret('mehmet');
|
||||
// const qrCodeImage = await authService.generateQRCode(otpauthUrl);
|
||||
// // qrCodeImage → frontend’e gönder, <img src="data:image/png;base64,..."> diye gösterilebilir
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
import { IsString } from 'class-validator';
|
||||
|
||||
export class userSelectValidator {
|
||||
@IsString()
|
||||
uuid: string;
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { SelectService } from './select.service';
|
||||
|
||||
describe('SelectService', () => {
|
||||
let service: SelectService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [SelectService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<SelectService>(SelectService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,268 @@
|
|||
import { Injectable, UnauthorizedException, NotAcceptableException } from '@nestjs/common';
|
||||
import { userSelectValidator } from '@/src/auth/select/dtoValidator';
|
||||
import { RedisHandlers } from '@/src/utils/store/redisHandlers';
|
||||
import { EmployeeTokenSchema, OccupantTokenSchema, UserType } from '@/src/types/auth/token';
|
||||
import { PrismaService } from '@/src/prisma.service';
|
||||
import { EventsService } from '@/src/navigator/events/events.service';
|
||||
import { PagesService } from '@/src/navigator/pages/pages.service';
|
||||
import { MenusService } from '@/src/navigator/menus/menu.service';
|
||||
import { includes } from 'zod';
|
||||
|
||||
@Injectable()
|
||||
export class SelectService {
|
||||
constructor(
|
||||
private readonly redis: RedisHandlers,
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly pagesService: PagesService,
|
||||
private readonly eventService: EventsService,
|
||||
private readonly menusService: MenusService,
|
||||
) { }
|
||||
|
||||
async run(dto: userSelectValidator, req: Request) {
|
||||
const accessObject = await this.redis.getLoginFromRedis(req);
|
||||
if (!accessObject) { throw new UnauthorizedException('Authorization failed. Please login to continue') }
|
||||
const accessToken = accessObject.key.split(':')[1];
|
||||
const existingSelectToken = await this.redis.callExistingSelectToken(accessObject.value.users.uu_id, dto.uuid);
|
||||
if (existingSelectToken) { return { message: 'Select successful', token: existingSelectToken } }
|
||||
const userType = accessObject.value.users.user_type;
|
||||
if (userType === 'employee') {
|
||||
const employee = await this.prisma.employees.findFirstOrThrow({ where: { uu_id: dto.uuid }, omit: { id: true } });
|
||||
const staff = await this.prisma.staff.findFirstOrThrow({
|
||||
where: { uu_id: employee.staff_uu_id },
|
||||
select: {
|
||||
uu_id: true,
|
||||
staff_code: true,
|
||||
user_type_id: true,
|
||||
duties_id: true,
|
||||
staff_name: true,
|
||||
staff_description: true,
|
||||
duties_uu_id: true,
|
||||
created_credentials_token: true,
|
||||
updated_credentials_token: true,
|
||||
confirmed_credentials_token: true,
|
||||
is_confirmed: true,
|
||||
deleted: true,
|
||||
active: true,
|
||||
is_notification_send: true,
|
||||
is_email_send: true,
|
||||
expiry_starts: true,
|
||||
expiry_ends: true,
|
||||
created_at: true,
|
||||
updated_at: true,
|
||||
ref_int: true,
|
||||
user_types: {
|
||||
select: {
|
||||
token: true,
|
||||
type_token: true
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
const duties = await this.prisma.duties.findFirstOrThrow({
|
||||
where: { id: staff.duties_id },
|
||||
omit: { id: true },
|
||||
});
|
||||
const department = await this.prisma.departments.findFirstOrThrow({
|
||||
where: { id: duties.department_id },
|
||||
omit: { id: true },
|
||||
});
|
||||
const duty = await this.prisma.duty.findFirstOrThrow({
|
||||
where: { id: duties.duties_id },
|
||||
omit: { id: true },
|
||||
});
|
||||
const company = await this.prisma.companies.findFirstOrThrow({
|
||||
where: { id: duties.company_id },
|
||||
omit: { id: true },
|
||||
});
|
||||
const staffUserType = staff.user_type_id ?
|
||||
await this.prisma.user_types.findFirst({
|
||||
where: { id: staff.user_type_id },
|
||||
select: {
|
||||
token: true,
|
||||
type_token: true
|
||||
}
|
||||
}) : null;
|
||||
const employeeToken = EmployeeTokenSchema.parse({
|
||||
uuid: dto.uuid,
|
||||
company: company,
|
||||
department: department,
|
||||
duty: duty,
|
||||
employee: employee,
|
||||
staff: staff,
|
||||
menu: null,
|
||||
pages: null,
|
||||
events: null,
|
||||
selection: await this.prisma.employees.findFirstOrThrow({
|
||||
where: { uu_id: dto.uuid },
|
||||
select: {
|
||||
uu_id: true,
|
||||
staff: {
|
||||
select: {
|
||||
uu_id: true,
|
||||
staff_code: true,
|
||||
user_types: {
|
||||
select: {
|
||||
uu_id: true,
|
||||
token: true,
|
||||
},
|
||||
},
|
||||
duties: {
|
||||
select: {
|
||||
uu_id: true,
|
||||
departments: {
|
||||
select: {
|
||||
uu_id: true,
|
||||
department_code: true,
|
||||
department_name: true,
|
||||
companies: {
|
||||
select: {
|
||||
uu_id: true,
|
||||
formal_name: true,
|
||||
public_name: true,
|
||||
addresses: {
|
||||
select: {
|
||||
comment_address: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
typeToken: staffUserType?.type_token,
|
||||
functionsRetriever: staffUserType?.token,
|
||||
kind: UserType.employee,
|
||||
});
|
||||
// Render page and menu
|
||||
// const collection = this.mongoService.getDb(`Events/${company.uu_id}`)
|
||||
const events = ""
|
||||
|
||||
|
||||
const tokenSelect = await this.redis.setSelectToRedis(
|
||||
accessToken,
|
||||
employeeToken,
|
||||
accessObject.value.users.uu_id,
|
||||
dto.uuid,
|
||||
);
|
||||
return { message: 'Select successful', token: tokenSelect };
|
||||
} else if (userType === 'occupant') {
|
||||
const livingSpace = await this.prisma.build_living_space.findFirstOrThrow({
|
||||
where: { uu_id: dto.uuid },
|
||||
select: {
|
||||
uu_id: true,
|
||||
build_parts_uu_id: true,
|
||||
occupant_type_uu_id: true,
|
||||
occupant_types: {
|
||||
select: {
|
||||
user_types: {
|
||||
select: {
|
||||
token: true,
|
||||
type_token: true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
const occupantType = await this.prisma.occupant_types.findFirstOrThrow({
|
||||
where: { uu_id: livingSpace.occupant_type_uu_id }
|
||||
});
|
||||
const userTypeInfo = occupantType.user_type_uu_id ?
|
||||
await this.prisma.user_types.findFirst({
|
||||
where: { uu_id: occupantType.user_type_uu_id },
|
||||
select: {
|
||||
uu_id: true,
|
||||
type: true,
|
||||
description: true,
|
||||
type_token: true,
|
||||
token: true
|
||||
}
|
||||
}) : null;
|
||||
const part = await this.prisma.build_parts.findFirstOrThrow({
|
||||
where: { uu_id: livingSpace.build_parts_uu_id },
|
||||
select: {
|
||||
uu_id: true,
|
||||
part_code: true,
|
||||
part_no: true,
|
||||
part_level: true,
|
||||
human_livable: true,
|
||||
build_uu_id: true,
|
||||
api_enum_dropdown_build_parts_part_type_idToapi_enum_dropdown: {
|
||||
select: {
|
||||
uu_id: true,
|
||||
enum_class: true,
|
||||
value: true
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
const build = await this.prisma.build.findFirstOrThrow({
|
||||
where: { uu_id: part.build_uu_id },
|
||||
select: {
|
||||
uu_id: true,
|
||||
build_name: true
|
||||
}
|
||||
});
|
||||
const company = await this.prisma.companies.findFirstOrThrow({
|
||||
where: { uu_id: accessObject.value.users.related_company },
|
||||
select: {
|
||||
uu_id: true,
|
||||
is_confirmed: true,
|
||||
deleted: true,
|
||||
active: true,
|
||||
created_at: true,
|
||||
updated_at: true,
|
||||
ref_int: true
|
||||
}
|
||||
});
|
||||
const occupantToken = OccupantTokenSchema.parse({
|
||||
uuid: dto.uuid,
|
||||
livingSpace: livingSpace,
|
||||
occupant: occupantType,
|
||||
build: build,
|
||||
part: part,
|
||||
company: company,
|
||||
menu: null,
|
||||
pages: null,
|
||||
events: null,
|
||||
selection: {
|
||||
occupant_types: {
|
||||
uu_id: occupantType.uu_id,
|
||||
occupant_code: occupantType.occupant_code,
|
||||
occupant_type: occupantType.occupant_type
|
||||
},
|
||||
build_parts: {
|
||||
uu_id: part.uu_id,
|
||||
part_code: part.part_code,
|
||||
part_no: part.part_no,
|
||||
part_level: part.part_level,
|
||||
human_livable: part.human_livable,
|
||||
api_enum_dropdown_build_parts_part_type_idToapi_enum_dropdown: {
|
||||
uu_id: part.api_enum_dropdown_build_parts_part_type_idToapi_enum_dropdown.uu_id,
|
||||
enum_class: part.api_enum_dropdown_build_parts_part_type_idToapi_enum_dropdown.enum_class,
|
||||
value: part.api_enum_dropdown_build_parts_part_type_idToapi_enum_dropdown.value
|
||||
},
|
||||
build: {
|
||||
uu_id: build.uu_id, build_name: build.build_name
|
||||
}
|
||||
}
|
||||
},
|
||||
typeToken: userTypeInfo?.type_token,
|
||||
functionsRetriever: userTypeInfo?.token,
|
||||
kind: UserType.occupant
|
||||
});
|
||||
|
||||
occupantToken.events = await this.eventService.getEventsOccupants(livingSpace.uu_id);
|
||||
occupantToken.pages = await this.pagesService.getPagesOccupants(accessObject.value.users.uu_id, livingSpace.occupant_types.user_types?.token || '');
|
||||
occupantToken.menu = await this.menusService.renderOccupantMenu(occupantToken.pages);
|
||||
|
||||
const tokenSelect = await this.redis.setSelectToRedis(accessToken, occupantToken, accessObject.value.users.uu_id, dto.uuid);
|
||||
return { message: 'Select successful', token: tokenSelect };
|
||||
} else { throw new NotAcceptableException('Invalid user type') }
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
import { Module } from '@nestjs/common';
|
||||
import { MongoService } from './mongo.service';
|
||||
import { MongoProvider } from './mongo.provider';
|
||||
|
||||
@Module({
|
||||
providers: [MongoProvider, MongoService],
|
||||
exports: [MongoService, MongoProvider, 'MONGO_DB']
|
||||
})
|
||||
export class MongoModule {}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
import { MongoClient, Db } from 'mongodb';
|
||||
|
||||
export const MongoProvider = {
|
||||
provide: 'MONGO_DB',
|
||||
useFactory: async (): Promise<Db> => {
|
||||
const uri = 'mongodb://appuser:apppassword@10.10.2.13:27017/appdb';
|
||||
const client = new MongoClient(uri);
|
||||
await client.connect();
|
||||
return client.db('appdb');
|
||||
},
|
||||
};
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { MongoService } from './mongo.service';
|
||||
|
||||
describe('MongoService', () => {
|
||||
let service: MongoService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [MongoService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<MongoService>(MongoService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,294 @@
|
|||
import { Injectable, Inject } from '@nestjs/common';
|
||||
import { Db, Document, Collection, Filter, ObjectId, UpdateResult, Sort, SortDirection } from 'mongodb';
|
||||
|
||||
@Injectable()
|
||||
export class MongoService {
|
||||
|
||||
private collection: Collection<Document>;
|
||||
|
||||
constructor(@Inject('MONGO_DB') private readonly db: Db) { this.collection = this.db.collection('mongoCache') }
|
||||
|
||||
async set(collectionName: string) { this.collection = this.db.collection(collectionName) }
|
||||
|
||||
async getDb() { return this.collection }
|
||||
|
||||
async create(data: Record<string, any>): Promise<Document> {
|
||||
const insertResult = await this.collection.insertOne(data);
|
||||
if (!insertResult.acknowledged) { throw new Error('Failed to insert document') }
|
||||
return await this.getOne(insertResult.insertedId);
|
||||
}
|
||||
async createMany(data: Record<string, any>[]): Promise<number> {
|
||||
const insertResult = await this.collection.insertMany(data);
|
||||
if (!insertResult.acknowledged) { throw new Error('Failed to insert documents') }
|
||||
return insertResult.insertedCount;
|
||||
}
|
||||
|
||||
async findManyKeyWhere(value: string, limit?: number, skip?: number): Promise<Document[]> {
|
||||
const docs = await this.collection.find({
|
||||
$where: function () {
|
||||
return Object.keys(this).some(key => key.includes(value));
|
||||
}
|
||||
}).toArray();
|
||||
return docs;
|
||||
}
|
||||
|
||||
async findManyKeyWhereValue(value: string, limit?: number, skip?: number): Promise<Document[]> {
|
||||
const docs = await this.collection.find({
|
||||
$where: function () {
|
||||
return Object.keys(this).some(key => this[key] === value);
|
||||
}
|
||||
}).toArray();
|
||||
return docs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a document by UUID or create it if it doesn't exist
|
||||
* @param data Document data with UUID field
|
||||
* @returns The found or created document
|
||||
*
|
||||
* @example
|
||||
* Create a new user or retrieve existing one
|
||||
* const userData = { uuid: 'TOKEN:12345:user', name: 'John Doe', email: 'john@example.com' };
|
||||
* const user = await mongoService.findOrCreate(userData);
|
||||
*/
|
||||
async findOrCreate(data: Record<string, any>): Promise<{ data: Document, isCreated: boolean }> {
|
||||
if (!data.uuid) { throw new Error('UUID is required for findOrCreate operation') }
|
||||
// Use direct UUID lookup instead of regex for exact match
|
||||
const existingDoc = await this.collection.findOne({ uuid: data.uuid } as Filter<Document>);
|
||||
if (existingDoc) { return { data: existingDoc, isCreated: false } }
|
||||
const insertResult = await this.collection.insertOne(data);
|
||||
if (!insertResult.acknowledged) { throw new Error('Failed to insert document') }
|
||||
return { data: await this.getOne(insertResult.insertedId), isCreated: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all documents from the collection
|
||||
* @returns Array of all documents
|
||||
*
|
||||
* @example
|
||||
* Get all users in the collection
|
||||
* const allUsers = await mongoService.getAll();
|
||||
*/
|
||||
async getAll(): Promise<Document[]> { return await this.collection.find().toArray() }
|
||||
|
||||
/**
|
||||
* Find a document by ID key using regex pattern
|
||||
* @param idKey ID key to search for
|
||||
* @returns The found document
|
||||
* @throws Error if document is not found
|
||||
*
|
||||
* @example
|
||||
* Find a user by ID key
|
||||
* const user = await mongoService.findOne('12345');
|
||||
* This will search for documents with uuid matching pattern ^TOKEN:12345:
|
||||
*/
|
||||
async findOne(filter: Filter<Document>): Promise<Document | null> {
|
||||
const result = await this.collection.findOne(filter);
|
||||
return result ? result : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find multiple documents using a filter
|
||||
* @param filter MongoDB filter
|
||||
* @param limit Optional limit of results (default: no limit)
|
||||
* @param skip Optional number of documents to skip (default: 0)
|
||||
* @returns Array of matching documents
|
||||
*
|
||||
* @example
|
||||
* Find active users with pagination
|
||||
* const filter = { active: true } as Filter<Document>;
|
||||
* const activeUsers = await mongoService.findMany(filter, 10, 20); // limit 10, skip 20
|
||||
*
|
||||
* @example
|
||||
* Find users by role
|
||||
* const admins = await mongoService.findMany({ role: 'admin' } as Filter<Document>);
|
||||
* const documents = await mongoService.findMany(filter, limit, skip, ['name', 'createdAt'], ['asc', 'desc']);
|
||||
*/
|
||||
async findMany(filter: Filter<Document>, limit?: number, skip?: number, sortBys?: string[], sortDirections?: SortDirection[]): Promise<Document[]> {
|
||||
let query = this.collection.find(filter);
|
||||
if (typeof skip === 'number') { query = query.skip(skip) }
|
||||
if (typeof limit === 'number') { query = query.limit(limit) }
|
||||
if (sortBys && sortDirections && sortBys.length === sortDirections.length) {
|
||||
const sortOptions = sortBys.reduce<Record<string, SortDirection>>((acc, sortBy, index) => ({
|
||||
...acc,
|
||||
[sortBy]: sortDirections[index]
|
||||
}), {});
|
||||
query = query.sort(sortOptions);
|
||||
}
|
||||
return await query.toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a document by its MongoDB ObjectId
|
||||
* @param id MongoDB ObjectId
|
||||
* @returns The found document
|
||||
* @throws Error if document is not found
|
||||
*
|
||||
* @example
|
||||
* Get a user by ObjectId
|
||||
* const userId = new ObjectId('507f1f77bcf86cd799439011');
|
||||
* const user = await mongoService.getOne(userId);
|
||||
*/
|
||||
async getOne(id: ObjectId): Promise<Document> {
|
||||
const result = await this.collection.findOne({ _id: id });
|
||||
if (!result) { throw new Error(`Document with ID ${id.toString()} not found`) }
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find documents by regex pattern on UUID field
|
||||
* @param idKey ID key to search for
|
||||
* @returns Array of matching documents
|
||||
*
|
||||
* @example
|
||||
* Find all users with a specific ID key pattern
|
||||
* const users = await mongoService.findByRegex('12345');
|
||||
* This will return all documents with uuid matching pattern ^TOKEN:12345:
|
||||
*/
|
||||
async findByRegex(idKey: string): Promise<Document[]> {
|
||||
if (!idKey) { throw new Error('ID key is required for regex search') }
|
||||
const pattern = `^${idKey}`;
|
||||
return await this.collection.find({ uuid: { $regex: pattern } } as Filter<Document>).toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a single document by its MongoDB ObjectId
|
||||
* @param id MongoDB ObjectId
|
||||
* @param data Data to update
|
||||
* @returns The updated document
|
||||
* @throws Error if document is not found or update fails
|
||||
*
|
||||
* @example
|
||||
* Update a user's profile
|
||||
* const userId = new ObjectId('507f1f77bcf86cd799439011');
|
||||
* const updates = { name: 'Jane Doe', lastLogin: new Date() };
|
||||
* const updatedUser = await mongoService.updateOne(userId, updates);
|
||||
*/
|
||||
async updateOne(id: ObjectId, data: Record<string, any>): Promise<Document> {
|
||||
const updateResult = await this.collection.updateOne(
|
||||
{ _id: id },
|
||||
{ $set: data }
|
||||
);
|
||||
if (!updateResult.acknowledged) { throw new Error('Update operation failed') }
|
||||
if (updateResult.matchedCount === 0) { throw new Error(`Document with ID ${id.toString()} not found`) }
|
||||
return await this.getOne(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update multiple documents matching a filter
|
||||
* @param filter MongoDB filter
|
||||
* @param data Data to update
|
||||
* @returns Update result with count of modified documents
|
||||
* @throws Error if update fails
|
||||
*
|
||||
* @example
|
||||
* Mark all inactive users as archived
|
||||
* const filter = { active: false } as Filter<Document>;
|
||||
* const updates = { status: 'archived', archivedAt: new Date() };
|
||||
* const result = await mongoService.updateMany(filter, updates);
|
||||
* console.log(`${result.modifiedCount} users archived`);
|
||||
*/
|
||||
async updateMany(filter: Filter<Document>, data: Record<string, any>): Promise<UpdateResult> {
|
||||
const updateResult = await this.collection.updateMany(filter, { $set: data });
|
||||
if (!updateResult.acknowledged) { throw new Error('Update operation failed') }
|
||||
return updateResult;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a document by its MongoDB ObjectId
|
||||
* @param id MongoDB ObjectId
|
||||
* @returns True if document was deleted, false otherwise
|
||||
*
|
||||
* @example
|
||||
* Delete a user account
|
||||
* const userId = new ObjectId('507f1f77bcf86cd799439011');
|
||||
* const deleted = await mongoService.deleteOne(userId);
|
||||
* if (deleted) console.log('User successfully deleted');
|
||||
*/
|
||||
async deleteOne(id: ObjectId): Promise<boolean> {
|
||||
const deleteResult = await this.collection.deleteOne({ _id: id });
|
||||
return deleteResult.acknowledged && deleteResult.deletedCount > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete multiple documents matching a filter
|
||||
* @param filter MongoDB filter
|
||||
* @returns Number of deleted documents
|
||||
*
|
||||
* @example
|
||||
* Delete all expired sessions
|
||||
* const filter = { expiresAt: { $lt: new Date() } } as Filter<Document>;
|
||||
* const count = await mongoService.deleteMany(filter);
|
||||
* console.log(`${count} expired sessions deleted`);
|
||||
*/
|
||||
async deleteMany(filter: Filter<Document>): Promise<number> {
|
||||
const deleteResult = await this.collection.deleteMany(filter);
|
||||
return deleteResult.acknowledged ? deleteResult.deletedCount : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find documents by regex pattern on any specified field
|
||||
* @param field The field name to apply the regex filter on
|
||||
* @param value The value to search for in the field
|
||||
* @param options Optional regex options (e.g., 'i' for case-insensitive)
|
||||
* @param prefix Optional prefix to add before the value (default: '')
|
||||
* @param suffix Optional suffix to add after the value (default: '')
|
||||
* @returns Array of matching documents
|
||||
*
|
||||
* @example
|
||||
* Find users with email from a specific domain (case-insensitive)
|
||||
* const gmailUsers = await mongoService.findByFieldRegex('email', 'gmail.com', 'i');
|
||||
*
|
||||
* @example
|
||||
* Find users with names starting with 'J'
|
||||
* const usersStartingWithJ = await mongoService.findByFieldRegex('name', 'J', 'i', '^');
|
||||
*
|
||||
* @example
|
||||
* Find users with phone numbers ending in specific digits
|
||||
* const specificPhoneUsers = await mongoService.findByFieldRegex('phone', '5555', '', '', '$');
|
||||
*/
|
||||
async findByFieldRegex(field: string, value: string, options?: string, prefix: string = '', suffix: string = ''): Promise<Document[]> {
|
||||
if (!field || !value) { throw new Error('Field name and value are required for regex search') }
|
||||
const pattern = `${prefix}${value}${suffix}`;
|
||||
const query: Record<string, any> = {};
|
||||
query[field] = { $regex: pattern };
|
||||
if (options) { query[field].$options = options; }
|
||||
return await this.collection.find(query as unknown as Filter<Document>).toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Find documents by regex pattern across all fields (including nested)
|
||||
* @param value The value to search for
|
||||
* @param options Optional regex options (e.g., 'i' for case-insensitive)
|
||||
* @returns Array of matching documents
|
||||
*
|
||||
* @example
|
||||
* Find any document containing a specific value anywhere
|
||||
* const docs = await mongoService.findByRegexAcrossFields('someValue', 'i');
|
||||
*/
|
||||
async findByRegexAcrossFields(value: string, options?: string, searchType: 'value' | 'key' | 'both' = 'value'): Promise<Document[]> {
|
||||
if (!value) { throw new Error('Search value is required') }
|
||||
const query: any = { $or: [] };
|
||||
if (searchType === 'value' || searchType === 'both') {
|
||||
query.$or.push(
|
||||
{ '$expr': { $regexMatch: { input: { $toString: '$$ROOT' }, regex: value, options } } },
|
||||
{ 'data': { $type: 'object', $regex: value, $options: options } }
|
||||
);
|
||||
}
|
||||
|
||||
if (searchType === 'key' || searchType === 'both') {
|
||||
query.$where = function () {
|
||||
const searchRegex = new RegExp(value, options);
|
||||
function checkKeys(obj: Record<string, any>) {
|
||||
for (const key in obj) {
|
||||
if (searchRegex.test(key)) return true; if (obj[key] && typeof obj[key] === 'object') { if (checkKeys(obj[key])) return true }
|
||||
}
|
||||
return false;
|
||||
} return checkKeys(this)
|
||||
}.toString();
|
||||
}
|
||||
|
||||
return await this.collection.find(query as unknown as Filter<Document>).toArray();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
export const REDIS_CLIENT = 'REDIS_CLIENT';
|
||||
export const REDIS_OPTIONS = 'REDIS_OPTIONS';
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
import { ModuleMetadata, Type } from '@nestjs/common';
|
||||
|
||||
export interface RedisModuleOptions {
|
||||
config?: {
|
||||
host?: string;
|
||||
port?: number;
|
||||
password?: string;
|
||||
db?: number;
|
||||
keyPrefix?: string;
|
||||
[key: string]: any;
|
||||
};
|
||||
}
|
||||
|
||||
export interface RedisOptionsFactory {
|
||||
createRedisOptions(): Promise<RedisModuleOptions> | RedisModuleOptions;
|
||||
}
|
||||
|
||||
export interface RedisModuleAsyncOptions extends Pick<ModuleMetadata, 'imports'> {
|
||||
useExisting?: Type<RedisOptionsFactory>;
|
||||
useClass?: Type<RedisOptionsFactory>;
|
||||
useFactory?: (...args: any[]) => Promise<RedisModuleOptions> | RedisModuleOptions;
|
||||
inject?: any[];
|
||||
}
|
||||
|
|
@ -0,0 +1,91 @@
|
|||
import Redis from 'ioredis';
|
||||
|
||||
import { DynamicModule, Module, OnApplicationShutdown, Provider } from '@nestjs/common';
|
||||
import { ModuleRef } from '@nestjs/core';
|
||||
import { CacheService } from './redis.service';
|
||||
import { REDIS_CLIENT, REDIS_OPTIONS } from './redis.constants';
|
||||
import { RedisModuleOptions, RedisModuleAsyncOptions } from './redis.interfaces';
|
||||
|
||||
@Module({})
|
||||
export class RedisModule implements OnApplicationShutdown {
|
||||
constructor(private moduleRef: ModuleRef) { }
|
||||
|
||||
/**
|
||||
* Registers the module with default configuration.
|
||||
*
|
||||
* @param isGlobal - Register in the global scope
|
||||
* @returns A DynamicModule
|
||||
*/
|
||||
static forRootWithConfig(isGlobal = false): DynamicModule {
|
||||
const redisConfig = { host: '10.10.2.15', port: 6379, password: 'your_strong_password_here' };
|
||||
return RedisModule.forRoot({ config: redisConfig }, isGlobal);
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers the module synchronously.
|
||||
*
|
||||
* @param options - The module options
|
||||
* @param isGlobal - Register in the global scope
|
||||
* @returns A DynamicModule
|
||||
*/
|
||||
static forRoot(options?: RedisModuleOptions, isGlobal = false): DynamicModule {
|
||||
const redisOptionsProvider: Provider = {
|
||||
provide: REDIS_OPTIONS,
|
||||
useValue: options || {},
|
||||
};
|
||||
|
||||
const redisClientProvider: Provider = {
|
||||
provide: REDIS_CLIENT,
|
||||
useFactory: () => {
|
||||
if (!options || !options.config) { return new Redis() }
|
||||
const { host, port, password } = options.config;
|
||||
return new Redis({ host, port, password });
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
module: RedisModule,
|
||||
providers: [redisOptionsProvider, redisClientProvider, CacheService],
|
||||
exports: [CacheService],
|
||||
global: isGlobal,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers the module asynchronously.
|
||||
*
|
||||
* @param options - The async module options
|
||||
* @param isGlobal - Register in the global scope
|
||||
* @returns A DynamicModule
|
||||
*/
|
||||
static forRootAsync(options: RedisModuleAsyncOptions, isGlobal = false): DynamicModule {
|
||||
const redisOptionsProvider: Provider = {
|
||||
provide: REDIS_OPTIONS,
|
||||
useFactory: options.useFactory || (() => ({})),
|
||||
inject: options.inject || [],
|
||||
};
|
||||
|
||||
const redisClientProvider: Provider = {
|
||||
provide: REDIS_CLIENT,
|
||||
useFactory: (redisOptions: RedisModuleOptions) => {
|
||||
if (!redisOptions || !redisOptions.config) { return new Redis() }
|
||||
const { host, port, password } = redisOptions.config;
|
||||
return new Redis({ host, port, password })
|
||||
},
|
||||
inject: [REDIS_OPTIONS],
|
||||
};
|
||||
|
||||
return {
|
||||
module: RedisModule,
|
||||
imports: options.imports || [],
|
||||
providers: [redisOptionsProvider, redisClientProvider, CacheService],
|
||||
exports: [CacheService],
|
||||
global: isGlobal,
|
||||
};
|
||||
}
|
||||
|
||||
async onApplicationShutdown() {
|
||||
const client = this.moduleRef.get(REDIS_CLIENT, { strict: false });
|
||||
if (client && typeof client.quit === 'function') { await client.quit() }
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { CacheService } from './redis.service';
|
||||
import Redis from 'ioredis';
|
||||
import { REDIS_CLIENT } from './redis.constants';
|
||||
|
||||
describe('CacheService', () => {
|
||||
let service: CacheService;
|
||||
let mockRedisClient: Redis;
|
||||
|
||||
beforeEach(async () => {
|
||||
// Create a mock Redis client
|
||||
mockRedisClient = new Redis();
|
||||
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
CacheService,
|
||||
{
|
||||
provide: REDIS_CLIENT,
|
||||
useValue: mockRedisClient,
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
|
||||
service = module.get<CacheService>(CacheService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,88 @@
|
|||
import Redis from 'ioredis';
|
||||
import { Injectable, Inject } from '@nestjs/common';
|
||||
import { REDIS_CLIENT } from './redis.constants';
|
||||
|
||||
@Injectable()
|
||||
export class CacheService {
|
||||
private client: Redis;
|
||||
|
||||
constructor(@Inject(REDIS_CLIENT) private readonly redisClient: Redis) {
|
||||
this.client = redisClient;
|
||||
}
|
||||
|
||||
async set(key: string, value: any) {
|
||||
await this.client.set(key, JSON.stringify(value));
|
||||
}
|
||||
|
||||
async get(key: string): Promise<any | null> {
|
||||
const value = await this.client.get(key);
|
||||
if (!value) { return null }
|
||||
return { key, value: JSON.parse(value) }
|
||||
}
|
||||
|
||||
async set_with_ttl(key: string, value: any, ttl: number) {
|
||||
await this.client.set(key, JSON.stringify(value), 'EX', ttl);
|
||||
}
|
||||
|
||||
async check_ttl(key: string): Promise<number> {
|
||||
return this.client.ttl(key);
|
||||
}
|
||||
|
||||
async delete(key: string): Promise<boolean> {
|
||||
const deleted = await this.client.del(key);
|
||||
return deleted === 0 ? false : true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete multiple keys matching a pattern.
|
||||
* Simplified version that just returns the count of deleted keys.
|
||||
*
|
||||
* @param listKeys - List of key components to form pattern for deletion.
|
||||
* @returns Number of deleted keys
|
||||
*/
|
||||
async deleteMultiple(listKeys: (string | null)[]): Promise<number> {
|
||||
const regex = this.createRegexPattern(listKeys);
|
||||
const keys: string[] = [];
|
||||
let cursor = '0';
|
||||
|
||||
do {
|
||||
const [nextCursor, matchedKeys] = await this.client.scan(
|
||||
cursor,
|
||||
'MATCH',
|
||||
regex,
|
||||
);
|
||||
cursor = nextCursor;
|
||||
keys.push(...matchedKeys);
|
||||
} while (cursor !== '0');
|
||||
|
||||
if (keys.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let deletedCount = 0;
|
||||
for (const key of keys) {
|
||||
const result = await this.client.del(key);
|
||||
deletedCount += result;
|
||||
}
|
||||
return deletedCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a regex pattern from list of keys
|
||||
* This is a simplified implementation - adjust according to your needs
|
||||
*/
|
||||
/**
|
||||
* Create a regex pattern from list of keys
|
||||
* Replaces null/undefined values with '*' wildcards
|
||||
* @param listKeys Array of key components, can contain null/undefined values
|
||||
* @returns Redis pattern string with wildcards
|
||||
*/
|
||||
createRegexPattern(listKeys: (string | null)[]): string {
|
||||
return listKeys.map((key) => (key === null ? '*' : key)).join(':') + '*';
|
||||
}
|
||||
|
||||
async check(key: string): Promise<boolean> {
|
||||
const exists = await this.client.exists(key);
|
||||
return exists === 1;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
import { NestFactory } from '@nestjs/core';
|
||||
import { AppModule } from './app.module';
|
||||
import { extractAndPersistRoutes } from '@/src/utils/extract-routes';
|
||||
import { PrismaService } from './prisma.service';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule);
|
||||
await app.listen(process.env.PORT ?? 8001);
|
||||
console.log(`🚀 Uygulama çalışıyor: ${await app.getUrl()}`);
|
||||
extractAndPersistRoutes(app, app.get(PrismaService));
|
||||
}
|
||||
bootstrap();
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
ForbiddenException,
|
||||
} from '@nestjs/common';
|
||||
import { RedisHandlers } from '@/src/utils/store/redisHandlers';
|
||||
import { UrlHandler } from '@/src/utils/navigator/urlHandler';
|
||||
|
||||
@Injectable()
|
||||
export class AuthControlGuard implements CanActivate {
|
||||
constructor(private cacheService: RedisHandlers) { }
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest();
|
||||
const accessToken = this.cacheService.mergeLoginKey(req);
|
||||
if (!accessToken) { throw new ForbiddenException('Send to Login') }
|
||||
this.cacheService.renewTtlLoginFromRedis(req);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class EndpointControlGuard implements CanActivate {
|
||||
constructor(
|
||||
private cacheService: RedisHandlers,
|
||||
private urlHandler: UrlHandler,
|
||||
) { }
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest();
|
||||
const method = req.method;
|
||||
const path = req.route?.path;
|
||||
const keyUrl = `${path}:${method.toUpperCase()}`;
|
||||
const driveToken = await this.urlHandler.getSecureUrlToken(keyUrl);
|
||||
const accessObject = await this.cacheService.getSelectFromRedis(req);
|
||||
if (!accessObject) { throw new ForbiddenException('Access denied') }
|
||||
req.driveToken = `${driveToken}:${accessObject?.value.functionsRetriever}`;
|
||||
this.cacheService.renewTtlSelectFromRedis(req);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
import { Injectable, NestMiddleware } from '@nestjs/common';
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
|
||||
@Injectable()
|
||||
export class LoggerMiddleware implements NestMiddleware {
|
||||
use(req: Request, res: Response, next: NextFunction) {
|
||||
console.log(`[LoggerMiddleware] ${req.method} ${req.originalUrl}`);
|
||||
next();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
import { IsString, IsObject, IsOptional, IsNumber } from 'class-validator';
|
||||
|
||||
export class mongoSetValidator {
|
||||
@IsString()
|
||||
collectionName: string;
|
||||
|
||||
@IsObject()
|
||||
data: object;
|
||||
}
|
||||
|
||||
export class mongoGetValidator {
|
||||
@IsString()
|
||||
collectionName: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
regexKey: string;
|
||||
|
||||
@IsObject()
|
||||
@IsOptional()
|
||||
filter: object;
|
||||
|
||||
@IsNumber()
|
||||
@IsOptional()
|
||||
limit: number;
|
||||
|
||||
@IsNumber()
|
||||
@IsOptional()
|
||||
skip: number;
|
||||
}
|
||||
|
||||
|
||||
export class eventSetValidator {
|
||||
@IsString()
|
||||
usersUUID: string;
|
||||
|
||||
@IsObject()
|
||||
event: Record<string, Record<string, Record<string, string>>>;
|
||||
}
|
||||
|
||||
export class eventGetValidator {
|
||||
@IsString()
|
||||
usersUUID: string;
|
||||
|
||||
@IsString()
|
||||
typeToken: string;
|
||||
}
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
import { IsString, IsObject, IsOptional, IsNumber, ValidateNested } from 'class-validator';
|
||||
|
||||
// { # collection Events:Build-UUIDv4 | Events:Company-UUIDv4 : "userUUID" : { "userTypeToken" : { "siteUrlToken" : "eventKey" } } }
|
||||
// const jsonData = { 'USER-UUID(V4)': { 'j0adQOsJBR0xq24dxLKdDU9EQRmt4gzE05CmhA': { 'e6hewIe7YqbQZHO3': 'qt5P0xoeThjNT9EuWfwBgxsntHY5ydRtKFr1pgKGcgxx' } } };
|
||||
|
||||
export class EventsSetterValidator {
|
||||
|
||||
@IsObject()
|
||||
event: Record<string, Record<string, Record<string, string>>>;
|
||||
|
||||
@IsString()
|
||||
userUUID: string; // UUID of employee or occupant
|
||||
}
|
||||
|
||||
export class EventsGetterValidator {
|
||||
@IsString()
|
||||
collectionName: string;
|
||||
|
||||
@IsString()
|
||||
dutyUUID: string; // UUID of employee or occupant
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
regexKey?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
searchType?: 'value' | 'key' | 'both';
|
||||
|
||||
@IsObject()
|
||||
@IsOptional()
|
||||
filter?: object = {};
|
||||
|
||||
@IsNumber()
|
||||
@IsOptional()
|
||||
limit?: number = 1;
|
||||
|
||||
@IsNumber()
|
||||
@IsOptional()
|
||||
skip?: number = 0;
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { EventsService } from './events.service';
|
||||
|
||||
describe('EventsService', () => {
|
||||
let service: EventsService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [EventsService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<EventsService>(EventsService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,214 @@
|
|||
import { Body, Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { MongoService } from '@/src/database/mongo/mongo.service';
|
||||
import { PrismaService } from '@/src/prisma.service';
|
||||
import { EventsGetterValidator, EventsSetterValidator } from '@/src/navigator/events/dtoValidator';
|
||||
import { Document } from 'mongodb';
|
||||
|
||||
type SearchType = 'value' | 'key' | 'both';
|
||||
|
||||
@Injectable()
|
||||
export class EventsService {
|
||||
|
||||
// const result = await eventsService.getEventsOccupants({
|
||||
// collectionName: 'Events:Build-UUIDv4',
|
||||
// regexKey: 'qt5P0xoeThjNT9EuWfwBgxsntHY5ydRtKFr1pgKGcgxx'
|
||||
// });
|
||||
// const result = await eventsService.getEventsOccupants({
|
||||
// collectionName: 'Events:Build-UUIDv4',
|
||||
// regexKey: 'e6hewIe7YqbQZHO3',
|
||||
// searchType: 'key'
|
||||
// });
|
||||
// const result = await eventsService.getEventsOccupants({
|
||||
// collectionName: 'Events:Build-UUIDv4',
|
||||
// regexKey: 'e6hewIe7YqbQZHO3',
|
||||
// searchType: 'both'
|
||||
// });
|
||||
|
||||
constructor(private mongoService: MongoService, private prisma: PrismaService) { }
|
||||
seperator = "/"
|
||||
|
||||
private async getBuildUUID(uuid: string) {
|
||||
console.log('uuid', uuid)
|
||||
const livingSpace = await this.prisma.build_living_space.findFirstOrThrow({
|
||||
where: { uu_id: uuid },
|
||||
select: {
|
||||
people: {
|
||||
select: {
|
||||
users: {
|
||||
select: {
|
||||
uu_id: true
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
build_parts: {
|
||||
select: {
|
||||
build: {
|
||||
select: {
|
||||
uu_id: true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
const userUUID = livingSpace.people.users[0].uu_id
|
||||
const buildUUID = livingSpace.build_parts.build.uu_id
|
||||
return { userUUID, buildUUID }
|
||||
}
|
||||
|
||||
private async getCompanyUUID(uuid: string) {
|
||||
const employee = await this.prisma.employees.findFirstOrThrow({
|
||||
where: { uu_id: uuid },
|
||||
select: {
|
||||
people: {
|
||||
select: {
|
||||
users: {
|
||||
select: {
|
||||
uu_id: true
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
staff: {
|
||||
select: {
|
||||
duties: {
|
||||
select: {
|
||||
company_uu_id: true
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
const userUUID = employee.people?.users[0].uu_id
|
||||
const companyUUID = employee.staff?.duties.company_uu_id
|
||||
return { userUUID, companyUUID }
|
||||
}
|
||||
|
||||
private validateCollectionName(collectionName: string) {
|
||||
if (!collectionName) {
|
||||
throw new NotFoundException('Collection name is required')
|
||||
}
|
||||
}
|
||||
|
||||
private async setupMongoCollection(collectionName: string, buildUUID: string) {
|
||||
await this.mongoService.set(collectionName);
|
||||
await this.mongoService.set(`EVENTS${this.seperator}${buildUUID}`);
|
||||
}
|
||||
|
||||
private escapeRegex(text: string): string {
|
||||
return text.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
|
||||
}
|
||||
|
||||
async getAllEventsOccupants(userTypeToken: string): Promise<Document[] | null> {
|
||||
await this.mongoService.set(`Events`)
|
||||
return await this.mongoService.findManyKeyWhere(userTypeToken) || null;
|
||||
}
|
||||
|
||||
async getAllEventsEmployees(userTypeToken: string): Promise<Document[] | null> {
|
||||
await this.mongoService.set(`Events`)
|
||||
return await this.mongoService.findManyKeyWhere(userTypeToken) || null;
|
||||
}
|
||||
|
||||
async getEventsOccupants(livingSpaceUUID: string) {
|
||||
const eventsObject = {}
|
||||
const { userUUID, buildUUID } = await this.getBuildUUID(livingSpaceUUID);
|
||||
const collectionKey = `Events/${buildUUID}`
|
||||
this.validateCollectionName(collectionKey);
|
||||
await this.mongoService.set(collectionKey)
|
||||
const eventsResponse = await this.mongoService.findOne({ [userUUID]: { $exists: true } });
|
||||
if (eventsResponse && typeof eventsResponse === 'object') {
|
||||
const mapOfEvents = eventsResponse[userUUID];
|
||||
if (mapOfEvents && typeof mapOfEvents === 'object') {
|
||||
const userTypeTokenKey = Object.keys(mapOfEvents)[0];
|
||||
const userTypeTokenValue = mapOfEvents[userTypeTokenKey];
|
||||
if (userTypeTokenValue && typeof userTypeTokenValue === 'object') {
|
||||
for (const siteUrlTokenKey of Object.keys(userTypeTokenValue)) {
|
||||
const siteUrlTokenValue = userTypeTokenValue[siteUrlTokenKey];
|
||||
eventsObject[`${siteUrlTokenKey}:${userTypeTokenKey}`] = siteUrlTokenValue
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return eventsObject || null;
|
||||
}
|
||||
|
||||
async getEventsEmployees(employeeUUID: string) {
|
||||
const eventsObject = {}
|
||||
const companyUUID = await this.getCompanyUUID(employeeUUID);
|
||||
if (!companyUUID) { throw new NotFoundException('Company not found') }
|
||||
await this.mongoService.set(`EVENTS${this.seperator}${companyUUID}`);
|
||||
const eventsResponse = await this.mongoService.findOne({ [employeeUUID]: { $exists: true } });
|
||||
if (eventsResponse && typeof eventsResponse === 'object') {
|
||||
const mapOfEvents = eventsResponse[employeeUUID];
|
||||
if (mapOfEvents && typeof mapOfEvents === 'object') {
|
||||
const userTypeTokenKey = Object.keys(mapOfEvents)[0];
|
||||
const userTypeTokenValue = mapOfEvents[userTypeTokenKey];
|
||||
if (userTypeTokenValue && typeof userTypeTokenValue === 'object') {
|
||||
for (const siteUrlTokenKey of Object.keys(userTypeTokenValue)) {
|
||||
const siteUrlTokenValue = userTypeTokenValue[siteUrlTokenKey];
|
||||
eventsObject[`${siteUrlTokenKey}:${userTypeTokenKey}`] = siteUrlTokenValue
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return eventsObject || null;
|
||||
}
|
||||
|
||||
private async setSavedEventToMapper(data: any, useruuid: string) {
|
||||
await this.mongoService.set(`MAP${this.seperator}EVENTS`);
|
||||
const events = await this.mongoService.findOrCreate({ uuid: `EVENTS${this.seperator}${useruuid}:${data.uuid}`, data });
|
||||
}
|
||||
|
||||
private async deleteSavedEventFromMapper(data: any, useruuid: string) {
|
||||
await this.mongoService.set(`MAP${this.seperator}EVENTS`);
|
||||
const events = await this.mongoService.deleteMany({ uuid: `EVENTS${this.seperator}${useruuid}:${data.uuid}` });
|
||||
return events;
|
||||
}
|
||||
|
||||
|
||||
async setEventsEmployees(@Body() body: EventsSetterValidator) {
|
||||
const companyUUID = await this.getCompanyUUID(body.userUUID);
|
||||
if (!companyUUID) { throw new NotFoundException('Company not found') }
|
||||
await this.mongoService.set(`EVENTS${this.seperator}${companyUUID}`);
|
||||
const events = await this.mongoService.findOrCreate(body.event);
|
||||
// await this.setSavedEventToMapper(events, body.dutyUUID);
|
||||
return events;
|
||||
}
|
||||
|
||||
async setEventsOccupants(@Body() body: EventsSetterValidator) {
|
||||
const buildUUID = await this.getBuildUUID(body.userUUID);
|
||||
if (!buildUUID) { throw new NotFoundException('Build not found') }
|
||||
await this.mongoService.set(`EVENTS${this.seperator}${buildUUID}`);
|
||||
const events = await this.mongoService.findOrCreate(body.event);
|
||||
return events;
|
||||
}
|
||||
|
||||
async setEvents(events: any, serviceName: string) {
|
||||
await this.mongoService.set(`Events`);
|
||||
for (const [key, value] of Object.entries(events)) {
|
||||
const description = (value as Array<any>)[0].endpoint || "";
|
||||
console.log(`Setting events for ${serviceName} ${description} is carried to nosql database store.`)
|
||||
await this.mongoService.deleteMany({ [key]: { $exists: true } });
|
||||
await this.mongoService.create({ [key]: value });
|
||||
}
|
||||
}
|
||||
|
||||
async deleteEventsEmployees(@Body() body: EventsGetterValidator) {
|
||||
const companyUUID = await this.getCompanyUUID(body.dutyUUID);
|
||||
if (!companyUUID) { throw new NotFoundException('Company not found') }
|
||||
await this.mongoService.set(`EVENTS${this.seperator}${companyUUID}`);
|
||||
const events = await this.mongoService.deleteMany({ uuid: { $regex: body.regexKey, $options: 'i' } });
|
||||
return events;
|
||||
}
|
||||
|
||||
async deleteEventsOccupants(@Body() body: EventsGetterValidator) {
|
||||
const buildUUID = await this.getBuildUUID(body.dutyUUID);
|
||||
if (!buildUUID) { throw new NotFoundException('Build not found') }
|
||||
await this.mongoService.set(`EVENTS${this.seperator}${buildUUID}`);
|
||||
const events = await this.mongoService.deleteMany({ uuid: { $regex: body.regexKey, $options: 'i' } });
|
||||
return events;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
import { validate } from 'class-validator';
|
||||
import { plainToClass } from 'class-transformer';
|
||||
import { EventsSetterValidator } from './dtoValidator';
|
||||
|
||||
// Example JSON data to validate
|
||||
const jsonData = {
|
||||
collectionName: 'Events:Build-UUIDv4',
|
||||
data: {
|
||||
'USER-UUID(V4)': {
|
||||
'j0adQOsJBR0xq24dxLKdDU9EQRmt4gzE05CmhA': {
|
||||
'e6hewIe7YqbQZHO3': 'qt5P0xoeThjNT9EuWfwBgxsntHY5ydRtKFr1pgKGcgxx'
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
async function validateEventData() {
|
||||
const eventData = plainToClass(EventsSetterValidator, jsonData);
|
||||
const errors = await validate(eventData, {
|
||||
whitelist: true,
|
||||
forbidNonWhitelisted: true,
|
||||
validationError: { target: false }
|
||||
});
|
||||
|
||||
if (errors.length > 0) {
|
||||
console.log('Validation failed. Errors:', JSON.stringify(errors, null, 2));
|
||||
return false;
|
||||
} else {
|
||||
console.log('Validation successful!');
|
||||
console.log('Validated data:', JSON.stringify(eventData, null, 2));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
validateEventData()
|
||||
.then(isValid => console.log('Is valid:', isValid))
|
||||
.catch(err => console.error('Error during validation:', err));
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
import { interfaceMenu, interfaceMapper, interfaceMenus } from "@/src/utils/types/menus";
|
||||
import { menuForEmployeeDefinition } from "./menuItems/employee";
|
||||
import { menuForOccupantDefinition } from "./menuItems/occupant";
|
||||
|
||||
const config = {
|
||||
FirstLayerColor: "#ebc334",
|
||||
SecondLayerColor: "#18910d",
|
||||
ThirdLayerColor: "#2825c4",
|
||||
employeePrefix: "/office",
|
||||
occupantPrefix: "/venue"
|
||||
}
|
||||
|
||||
function generateMapperKey(keys: string[]): string { return keys.join(':') + ':' }
|
||||
|
||||
function generateMapper(menu: interfaceMenu[], parentKeys: string[] = []): interfaceMapper {
|
||||
let mapper: interfaceMapper = {};
|
||||
for (const item of menu) {
|
||||
const currentKeys = [...parentKeys, item.key];
|
||||
if (item.page) { mapper[item.page] = generateMapperKey(currentKeys) }
|
||||
if (item.subs) { const subMapper = generateMapper(item.subs, currentKeys); mapper = { ...mapper, ...subMapper } }
|
||||
}
|
||||
return mapper;
|
||||
}
|
||||
|
||||
function generateDynamicMapper(menus: interfaceMenu[]): interfaceMapper { return generateMapper(menus) }
|
||||
|
||||
function applyColorsAndPrefixes(menu: interfaceMenu[], isEmployee: boolean, config: any, layer: number = 1): interfaceMenu[] {
|
||||
return menu.map(item => {
|
||||
const newItem = { ...item };
|
||||
if (layer === 1) newItem.color = config.FirstLayerColor;
|
||||
else if (layer === 2) newItem.color = config.SecondLayerColor;
|
||||
else if (layer >= 3) newItem.color = config.ThirdLayerColor;
|
||||
if (newItem.page) { newItem.page = `${isEmployee ? config.employeePrefix : config.occupantPrefix}${newItem.page}` }
|
||||
if (newItem.subs) { newItem.subs = applyColorsAndPrefixes(newItem.subs, isEmployee, layer + 1) }
|
||||
return newItem;
|
||||
});
|
||||
}
|
||||
|
||||
export const occupantMenus: interfaceMenus = {
|
||||
Menu: applyColorsAndPrefixes(menuForOccupantDefinition, false, config),
|
||||
Mapper: generateDynamicMapper(applyColorsAndPrefixes(menuForOccupantDefinition, false, config))
|
||||
};
|
||||
|
||||
export const employeeMenus: interfaceMenus = {
|
||||
Menu: applyColorsAndPrefixes(menuForEmployeeDefinition, true, config),
|
||||
Mapper: generateDynamicMapper(applyColorsAndPrefixes(menuForEmployeeDefinition, true, config))
|
||||
};
|
||||
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { ServicesService } from './menu.service';
|
||||
|
||||
describe('ServicesService', () => {
|
||||
let service: ServicesService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [ServicesService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<ServicesService>(ServicesService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
import { Injectable } from '@nestjs/common';
|
||||
import { employeeMenus, occupantMenus } from "./main";
|
||||
import { interfaceMenu } from "@/src/utils/types/menus";
|
||||
|
||||
// backend_service | Occupant pages
|
||||
// backend_service | {
|
||||
// backend_service | IbGpchaw3muiY7y9rnV0EJYoPy5XoOOrITT9JlfIbqwE: 'IbGpchaw3muiY7y9rnV0EJYoPy5XoOOrITT9JlfIbqwE:hES1KfaPRZeadmmjdryShA'
|
||||
// backend_service | }
|
||||
// backend_service | Occupant Menu Structure
|
||||
// backend_service | Occupant pages
|
||||
// backend_service | [
|
||||
// backend_service | {
|
||||
// backend_service | key: 'dzFGPzZJRgmft4HrrTeBtQ',
|
||||
// backend_service | icon: '',
|
||||
// backend_service | text: { tr: 'Pano', en: 'Dashboard' },
|
||||
// backend_service | page: '/venue/dashboard',
|
||||
// backend_service | token: 'IbGpchaw3muiY7y9rnV0EJYoPy5XoOOrITT9JlfIbqwE',
|
||||
// backend_service | color: '#ebc334',
|
||||
// backend_service | subs: []
|
||||
// backend_service | }
|
||||
// backend_service | ]
|
||||
// backend_service | [
|
||||
// backend_service | {
|
||||
// backend_service | key: 'dzFGPzZJRgmft4HrrTeBtQ',
|
||||
// backend_service | icon: '',
|
||||
// backend_service | text: { tr: 'Pano', en: 'Dashboard' },
|
||||
// backend_service | page: '/venue/dashboard',
|
||||
// backend_service | token: 'IbGpchaw3muiY7y9rnV0EJYoPy5XoOOrITT9JlfIbqwE',
|
||||
// backend_service | color: '#ebc334',
|
||||
// backend_service | subs: []
|
||||
// backend_service | }
|
||||
// backend_service | ]
|
||||
|
||||
|
||||
@Injectable()
|
||||
export class MenusService {
|
||||
|
||||
constructor() { }
|
||||
|
||||
async renderOccupantMenu(pages: any) {
|
||||
const defaultMenu: interfaceMenu[] = occupantMenus.Menu;
|
||||
const userHasUrls = Object.keys(pages)
|
||||
const renderedMenu: interfaceMenu[] = [];
|
||||
defaultMenu.map((value) => { if (value.token && userHasUrls.includes(value.token)) { renderedMenu.push(value as interfaceMenu) } });
|
||||
return renderedMenu || [];
|
||||
}
|
||||
|
||||
async renderEmployeeMenu(pages: Record<string, string>) {
|
||||
const defaultMenu = employeeMenus.Menu;
|
||||
console.log('Employee pages');
|
||||
console.dir(pages);
|
||||
console.log('Employee Menu Structure');
|
||||
console.dir(defaultMenu);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,301 @@
|
|||
export const menuForEmployeeDefinition = [
|
||||
{
|
||||
key: "a6EoBlTPSgGbUQELbyRwMA",
|
||||
icon: "",
|
||||
text: { "tr": "Dashboard", "en": "Dashboard" },
|
||||
page: "/dashboard",
|
||||
token: "qY56XMEr08wJkNvOR6EYQZKMVdTQEfHdLXGzzxcKU24E",
|
||||
color: "",
|
||||
subs: null,
|
||||
},
|
||||
{
|
||||
key: "NV2kI8NERmqrNgIeiUYojQ",
|
||||
icon: "",
|
||||
text: { "tr": "Bireysel", "en": "Individual" },
|
||||
page: null,
|
||||
token: null,
|
||||
color: "",
|
||||
subs: [
|
||||
{
|
||||
key: "xnhFAyi3Sp2qVWcVcR6m9w",
|
||||
icon: "",
|
||||
text: { "tr": "Birey", "en": "Person" },
|
||||
page: "/person",
|
||||
token: null,
|
||||
color: "",
|
||||
subs: [
|
||||
{
|
||||
key: "7wdsqwCQSmXRsRPC9GSgwx",
|
||||
icon: "",
|
||||
text: { "tr": "Oluştur", "en": "Create" },
|
||||
page: "/person/create",
|
||||
token: null,
|
||||
color: "",
|
||||
subs: null
|
||||
},
|
||||
{
|
||||
key: "56O8WRP4TyC7F8bc1vjXgx",
|
||||
icon: "",
|
||||
text: { "tr": "Güncelle", "en": "Update" },
|
||||
page: "/person/update",
|
||||
token: null,
|
||||
color: "",
|
||||
subs: null
|
||||
},
|
||||
{
|
||||
key: "RPaESp64SUmjNyEY1WUE8Q",
|
||||
icon: "",
|
||||
text: { "tr": "Sil", "en": "Delete" },
|
||||
page: "/person/delete",
|
||||
token: null,
|
||||
color: "",
|
||||
subs: null
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
key: "qcRK3EPQSoLSWkJFhtWOwx",
|
||||
icon: "",
|
||||
text: { "tr": "Kullanıcı", "en": "User" },
|
||||
page: "/users",
|
||||
token: null,
|
||||
color: "",
|
||||
subs: [
|
||||
{
|
||||
key: "PqNGe0SaQKeyUGyzJoSLwx",
|
||||
icon: "",
|
||||
text: { "tr": "Oluştur", "en": "Create" },
|
||||
page: "/users/create",
|
||||
token: null,
|
||||
color: "",
|
||||
subs: null
|
||||
},
|
||||
{
|
||||
key: "ruvQlE7wQzqHqUvCNIoUnA",
|
||||
icon: "",
|
||||
text: { "tr": "Güncelle", "en": "Update" },
|
||||
page: "/users/update",
|
||||
token: null,
|
||||
color: "",
|
||||
subs: null
|
||||
},
|
||||
{
|
||||
key: "DfDStf1dTBCRShNQeb5pZA",
|
||||
icon: "",
|
||||
text: { "tr": "Sil", "en": "Delete" },
|
||||
page: "/users/delete",
|
||||
token: null,
|
||||
color: "",
|
||||
subs: null
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
key: "ALV19bQ8S7q8LpOkdRDMwx",
|
||||
icon: "",
|
||||
text: { "tr": "Bina", "en": "Build" },
|
||||
page: null,
|
||||
token: null,
|
||||
color: "",
|
||||
subs: [
|
||||
{
|
||||
key: "eToBYS4DTEKseVYMJLNZwx",
|
||||
icon: "",
|
||||
text: { "tr": "Binalar", "en": "Building" },
|
||||
page: null,
|
||||
token: null,
|
||||
color: "",
|
||||
subs: [
|
||||
{
|
||||
key: "EkR7p6qmRN2Wb1GLsH5aEQ",
|
||||
icon: "",
|
||||
text: { "tr": "Oluştur", "en": "Create" },
|
||||
page: "/building/build/create",
|
||||
token: null,
|
||||
color: "",
|
||||
subs: null
|
||||
},
|
||||
{
|
||||
key: "qcoHwABjSli04D7xeWGOHQ",
|
||||
icon: "",
|
||||
text: { "tr": "Güncelle", "en": "Update" },
|
||||
page: "/building/build/update",
|
||||
token: null,
|
||||
color: "",
|
||||
subs: null
|
||||
},
|
||||
{
|
||||
key: "vC2oPkjRfudvBDlNReeRAx",
|
||||
icon: "",
|
||||
text: { "tr": "Sil", "en": "Delete" },
|
||||
page: "/building/build/delete",
|
||||
token: null,
|
||||
color: "",
|
||||
subs: null
|
||||
}
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "NFte61RnTHGPWlnoUItHAx",
|
||||
icon: "",
|
||||
text: { "tr": "Daireler", "en": "Parts" },
|
||||
page: null,
|
||||
token: null,
|
||||
color: "",
|
||||
subs: [
|
||||
{
|
||||
key: "7o6QNpelSpmxpJxTedEj4w",
|
||||
icon: "",
|
||||
text: { "tr": "Oluştur", "en": "Create" },
|
||||
page: "/building/parts/create",
|
||||
token: null,
|
||||
color: "",
|
||||
subs: null
|
||||
},
|
||||
{
|
||||
key: "rP6idRkyToLcxwpalCxgxx",
|
||||
icon: "OBKPalaMQwWhQmQ9Ni0y6Q",
|
||||
text: { "tr": "Güncelle", "en": "Update" },
|
||||
page: "/building/parts/update",
|
||||
token: null,
|
||||
color: "",
|
||||
subs: null
|
||||
},
|
||||
{
|
||||
key: "CBNaWzVqRaSpWaPTM54PbA",
|
||||
icon: "",
|
||||
text: { "tr": "Sil", "en": "Delete" },
|
||||
page: "/building/parts/delete",
|
||||
token: null,
|
||||
color: "",
|
||||
subs: null
|
||||
}
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "NFte61RnTHGPWlnoUItHAx",
|
||||
icon: "",
|
||||
text: { "tr": "Alanlar", "en": "Area" },
|
||||
page: null,
|
||||
token: null,
|
||||
color: "",
|
||||
subs: []
|
||||
}
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "yzvyvqMhQ06TdC9paOw4Ax",
|
||||
icon: "",
|
||||
text: { "tr": "Yönetim", "en": "Management" },
|
||||
page: null,
|
||||
token: null,
|
||||
color: "",
|
||||
subs: [
|
||||
{
|
||||
key: "DEumSZtaTSKiDsD1VJPQxx",
|
||||
icon: "",
|
||||
text: { "tr": "Bütçe", "en": "Budget" },
|
||||
page: "/management/budget",
|
||||
token: null,
|
||||
color: "",
|
||||
subs: [
|
||||
{
|
||||
key: "PIPD61aZRveFZ6GGfK3VYw",
|
||||
icon: "",
|
||||
text: { "tr": "Eylemler", "en": "Actions" },
|
||||
page: "/management/budget/actions",
|
||||
token: null,
|
||||
color: "",
|
||||
subs: null,
|
||||
},
|
||||
{
|
||||
key: "",
|
||||
icon: "",
|
||||
text: { "tr": "Durum", "en": "Status" },
|
||||
page: "/management/budget/status",
|
||||
token: null,
|
||||
color: "",
|
||||
subs: null,
|
||||
}
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "RHI0bthYRjWWf4tBaPBdgx",
|
||||
icon: "",
|
||||
text: { "tr": "Toplantılar", "en": "Meetings" },
|
||||
page: "/meetings",
|
||||
token: null,
|
||||
color: "",
|
||||
subs: [
|
||||
{
|
||||
key: "OESxDOI6S4eNcdeRCrKIjQ",
|
||||
icon: "",
|
||||
text: { "tr": "Yıllık", "en": "Annual" },
|
||||
page: "/meetings/annual",
|
||||
token: null,
|
||||
color: "",
|
||||
subs: [
|
||||
{
|
||||
key: "MhEHidsRWyHdCqtHJOcvAx",
|
||||
icon: "",
|
||||
text: { "tr": "Oluştur", "en": "Create" },
|
||||
page: "/meetings/annual/create",
|
||||
token: null,
|
||||
color: "",
|
||||
subs: null,
|
||||
},
|
||||
{
|
||||
key: "xhnSW4hWSDuJyREMjXOivA",
|
||||
icon: "",
|
||||
text: { "tr": "Kapat", "en": "Close" },
|
||||
page: "/meetings/annual/close",
|
||||
token: null,
|
||||
color: "",
|
||||
subs: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "A4raUDNFTpZ7mPfqJBGSwx",
|
||||
icon: "",
|
||||
text: { "tr": "Acil", "en": "Emergency" },
|
||||
page: "/meetings/emergency",
|
||||
token: null,
|
||||
color: "",
|
||||
subs: [
|
||||
{
|
||||
key: "T3Fd0C5Tf2V1dZhiZuNQxx",
|
||||
icon: "",
|
||||
text: { "tr": "Oluştur", "en": "Create" },
|
||||
page: "/meetings/emergency/create",
|
||||
token: null,
|
||||
color: "",
|
||||
subs: null,
|
||||
},
|
||||
{
|
||||
key: "L1ogOYhSl6BDPstufiSwxx",
|
||||
icon: "",
|
||||
text: { "tr": "Kapat", "en": "Close" },
|
||||
page: "/meetings/emergency/close",
|
||||
token: null,
|
||||
color: "",
|
||||
subs: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "vwzmxtBoQFW62YHes5OZAg",
|
||||
icon: "",
|
||||
text: { "tr": "Katılımlar", "en": "Participations" },
|
||||
page: "/meetings/participations",
|
||||
token: null,
|
||||
color: "",
|
||||
subs: [],
|
||||
}
|
||||
],
|
||||
}
|
||||
];
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
import { interfaceMenu } from "@/src/utils/types/menus";
|
||||
|
||||
export const menuForOccupantDefinition: interfaceMenu[] = [
|
||||
{
|
||||
key: "dzFGPzZJRgmft4HrrTeBtQ",
|
||||
icon: "",
|
||||
text: { "tr": "Pano", "en": "Dashboard" },
|
||||
page: "/dashboard",
|
||||
token: "IbGpchaw3muiY7y9rnV0EJYoPy5XoOOrITT9JlfIbqwE",
|
||||
color: "",
|
||||
subs: [],
|
||||
},
|
||||
]
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
import { employeeMenus, occupantMenus } from './main';
|
||||
|
||||
console.log('Employee Menu Mapper:');
|
||||
console.log(JSON.stringify(employeeMenus.Mapper, null, 2));
|
||||
|
||||
console.log('\nEmployee Menu Structure (with colors):');
|
||||
console.log(JSON.stringify(employeeMenus.Menu, null, 2));
|
||||
|
||||
console.log('\nOccupant Menu Mapper:');
|
||||
console.log(JSON.stringify(occupantMenus.Mapper, null, 2));
|
||||
|
||||
console.log('\nOccupant Menu Structure (with colors):');
|
||||
console.log(JSON.stringify(occupantMenus.Menu, null, 2));
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { NavigatorController } from './navigator.controller';
|
||||
|
||||
describe('NavigatorController', () => {
|
||||
let controller: NavigatorController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [NavigatorController],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<NavigatorController>(NavigatorController);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,73 @@
|
|||
import { Controller, Post, NotFoundException, Body } from '@nestjs/common';
|
||||
import { PrismaService } from '@/src/prisma.service';
|
||||
import { EventsService } from '@/src/navigator/events/events.service';
|
||||
import { MongoService } from '@/src/database/mongo/mongo.service';
|
||||
import { UrlHandler } from '@/src/utils/navigator/urlHandler';
|
||||
import { eventSetValidator, eventGetValidator } from './dtoValidator';
|
||||
import { PagesService } from './pages/pages.service';
|
||||
|
||||
const tokens = { employeeTypeToken: "L9wBdwV9OlxsLAgh", occupantTypeToken: "j0adQOsJBR0xq24d" }
|
||||
|
||||
@Controller('navigator')
|
||||
export class NavigatorController {
|
||||
constructor(
|
||||
private prismaService: PrismaService,
|
||||
private eventService: EventsService,
|
||||
private mongoService: MongoService,
|
||||
private urlHandler: UrlHandler,
|
||||
private pagesService: PagesService
|
||||
) { }
|
||||
|
||||
@Post('event/set')
|
||||
async setEvent(@Body() body: eventSetValidator) {
|
||||
const user = await this.prismaService.users.findFirst({ where: { uu_id: body.usersUUID }, include: { people: true } });
|
||||
if (!user) { throw new NotFoundException('User not found') }
|
||||
const userType = await this.prismaService.user_types.findFirstOrThrow({ where: { token: body.event.token } })
|
||||
const person = user.people[0]
|
||||
const people2userType = await this.prismaService.employees.findFirstOrThrow({ where: { uu_id: person.uu_id, staff: { user_type_uu_id: userType.uu_id } } })
|
||||
if (!people2userType) { throw new NotFoundException('User type not found') }
|
||||
if (userType.type_token == tokens.employeeTypeToken) { await this.eventService.setEventsEmployees({ event: body.event, userUUID: body.usersUUID }) }
|
||||
else if (userType.type_token == tokens.occupantTypeToken) { await this.eventService.setEventsOccupants({ event: body.event, userUUID: body.usersUUID }) }
|
||||
else { throw new NotFoundException('User type not found') }
|
||||
return body.event;
|
||||
}
|
||||
|
||||
@Post('event/get')
|
||||
async getEvent(@Body() body: eventGetValidator) {
|
||||
const { typeToken, usersUUID } = body
|
||||
const userType = await this.prismaService.user_types.findFirstOrThrow({ where: { token: typeToken } })
|
||||
if (userType.type_token == tokens.employeeTypeToken) {
|
||||
const allEvents = await this.eventService.getAllEventsEmployees(typeToken);
|
||||
if (!allEvents) { throw new NotFoundException('Events not found') }
|
||||
const selectedEvents = await this.eventService.getEventsEmployees(usersUUID);
|
||||
const selectedEventsKeys = Object.values(selectedEvents || {}).map((value: any) => value.key) || [];
|
||||
for (const event of allEvents) { if (selectedEventsKeys.includes(event.key)) { event.isSelected = true } else { event.isSelected = false } }
|
||||
return { events: allEvents }
|
||||
}
|
||||
else if (userType.type_token == tokens.occupantTypeToken) {
|
||||
const allEvents = await this.eventService.getAllEventsOccupants(typeToken);
|
||||
if (!allEvents) { throw new NotFoundException('Events not found') }
|
||||
const selectedEvents = await this.eventService.getEventsOccupants(usersUUID);
|
||||
const selectedEventsKeys = Object.values(selectedEvents || {}).map((value: any) => value.key) || [];
|
||||
for (const event of allEvents) { if (selectedEventsKeys.includes(event.key)) { event.isSelected = true } else { event.isSelected = false } }
|
||||
return { events: allEvents }
|
||||
} else { throw new NotFoundException('User type not found') }
|
||||
}
|
||||
|
||||
@Post('page/set')
|
||||
async setPage(@Body() body: { usersUUID: string, usersToken: string, url: string, page: Record<string, any> }) {
|
||||
return await this.pagesService.setPageViaToken(body.usersUUID, body.usersToken, body.url, body.page)
|
||||
}
|
||||
|
||||
@Post('page/get')
|
||||
async getPage(@Body() body: { usersUUID: string, token: string, url?: string, skip?: number, limit?: number }) {
|
||||
const pages = await this.pagesService.getPageViaToken(body.usersUUID, body.token, body.url, body.skip, body.limit)
|
||||
return { pages }
|
||||
}
|
||||
|
||||
@Post('page/configure')
|
||||
async setPages(@Body() body: { chunkIndex: number; chunkCount: number; data: Record<string, any> }) {
|
||||
return await this.pagesService.configurePages(body.data, body.chunkIndex, body.chunkCount)
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
import { Module } from '@nestjs/common';
|
||||
import { MongoModule } from '@/src/database/mongo/mongo.module';
|
||||
import { PrismaService } from '@/src/prisma.service';
|
||||
import { MenusService } from '@/src/navigator/menus/menu.service';
|
||||
import { NavigatorController } from '@/src/navigator/navigator.controller';
|
||||
import { EventsService } from '@/src/navigator/events/events.service';
|
||||
import { UrlHandler } from '@/src/utils/navigator/urlHandler';
|
||||
import { PagesService } from '@/src/navigator/pages/pages.service';
|
||||
|
||||
@Module({
|
||||
controllers: [NavigatorController],
|
||||
imports: [MongoModule],
|
||||
providers: [MenusService, EventsService, PagesService, PrismaService, UrlHandler],
|
||||
exports: [MenusService, EventsService, PagesService, PrismaService]
|
||||
})
|
||||
export class NavigatorModule {
|
||||
constructor() { }
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { PagesService } from './pages.service';
|
||||
|
||||
describe('PagesService', () => {
|
||||
let service: PagesService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [PagesService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<PagesService>(PagesService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,172 @@
|
|||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { PrismaService } from '@/src/prisma.service';
|
||||
import { MongoService } from '@/src/database/mongo/mongo.service';
|
||||
import { UrlHandler } from '@/src/utils/navigator/urlHandler';
|
||||
|
||||
@Injectable()
|
||||
export class PagesService {
|
||||
constructor(
|
||||
private readonly prismaService: PrismaService,
|
||||
private readonly mongoService: MongoService,
|
||||
private readonly urlHandler: UrlHandler
|
||||
) { }
|
||||
|
||||
tokens = { employeeTypeToken: "L9wBdwV9OlxsLAgh", occupantTypeToken: "j0adQOsJBR0xq24d" }
|
||||
|
||||
private async saveChunkToDB(data: Record<string, any>, chunkIndex: number) {
|
||||
await this.mongoService.set("Pages");
|
||||
if (chunkIndex == 1) { await this.mongoService.deleteMany({}) }
|
||||
await this.mongoService.createMany(Object.values(data));
|
||||
}
|
||||
|
||||
async getPagesOccupants(userUUID: string, usersToken: string) {
|
||||
const user = await this.prismaService.users.findFirstOrThrow({ where: { uu_id: userUUID }, include: { people: true } });
|
||||
const userType = await this.prismaService.user_types.findFirstOrThrow({ where: { token: usersToken } })
|
||||
if (userType.type_token == this.tokens.occupantTypeToken) {
|
||||
const person = user.people
|
||||
const livingSpace = await this.prismaService.build_living_space.findFirstOrThrow({
|
||||
where: { person_id: person.id, occupant_types: { user_types: { id: userType.id } } },
|
||||
select: { build_parts_id: true }
|
||||
})
|
||||
const buildUUID = await this.prismaService.build.findFirstOrThrow({
|
||||
where: { build_parts: { some: { id: livingSpace.build_parts_id } } }, select: { uu_id: true }
|
||||
})
|
||||
this.mongoService.set(`Pages/${buildUUID.uu_id}`);
|
||||
console.log('usersToken', usersToken)
|
||||
console.log('user.uu_id', user.uu_id)
|
||||
const userPage = await this.mongoService.findOne({ [user.uu_id]: { $exists: true } })
|
||||
console.log('userPage', userPage)
|
||||
if (!userPage) { throw new NotFoundException('Users slot not found') }
|
||||
const userPageSlot = userPage[user.uu_id][usersToken]
|
||||
if (!userPageSlot) { throw new NotFoundException('Users slot not found') }
|
||||
console.log('userPageSlot', userPageSlot)
|
||||
const writeObject = {}
|
||||
for (const [key, value] of Object.entries(userPageSlot)) {
|
||||
writeObject[key] = `${key}:${value}`
|
||||
}
|
||||
console.log('writeObject', writeObject)
|
||||
return writeObject
|
||||
}
|
||||
else { throw new NotFoundException('User type not found') }
|
||||
}
|
||||
|
||||
async getPagesEmployee(userUUID: string, usersToken: string) {
|
||||
const user = await this.prismaService.users.findFirstOrThrow({ where: { uu_id: userUUID }, include: { people: true } });
|
||||
const userType = await this.prismaService.user_types.findFirstOrThrow({ where: { token: usersToken } })
|
||||
if (userType.type_token == this.tokens.employeeTypeToken) {
|
||||
const person = user.people[0]
|
||||
const employee = await this.prismaService.employees.findFirstOrThrow({ where: { people_id: person.id, staff: { user_type_id: userType.id } } })
|
||||
const companyUUID = await this.prismaService.companies.findFirstOrThrow({
|
||||
where: { departments: { some: { duties: { some: { staff: { some: { uu_id: employee.staff_uu_id } } } } } } }, select: { uu_id: true }
|
||||
})
|
||||
this.mongoService.set(`Pages/${companyUUID.uu_id}`);
|
||||
const userPage = await this.mongoService.findOne({ [user.uu_id]: { [usersToken]: { $exists: true } } })
|
||||
if (!userPage) { throw new NotFoundException('Users slot not found') }
|
||||
return userPage
|
||||
}
|
||||
else { throw new NotFoundException('User type not found') }
|
||||
}
|
||||
|
||||
async setPageViaToken(userUUID: string, usersToken: string, url: string, page: Record<string, any>) {
|
||||
const user = await this.prismaService.users.findFirstOrThrow({ where: { uu_id: userUUID }, include: { people: true } });
|
||||
const userType = await this.prismaService.user_types.findFirstOrThrow({ where: { token: usersToken } })
|
||||
const urlToken = await this.urlHandler.getSecureUrlToken(url)
|
||||
if (userType.type_token == this.tokens.employeeTypeToken) {
|
||||
const person = user.people[0]
|
||||
const employee = await this.prismaService.employees.findFirstOrThrow({ where: { people_id: person.id, staff: { user_type_id: userType.id } } })
|
||||
const companyUUID = await this.prismaService.companies.findFirstOrThrow({
|
||||
where: { departments: { some: { duties: { some: { staff: { some: { uu_id: employee.staff_uu_id } } } } } } }, select: { uu_id: true }
|
||||
})
|
||||
this.mongoService.set(`Pages/${companyUUID.uu_id}`);
|
||||
const userPage = await this.mongoService.findOne({ [employee.uu_id]: { $exists: true } });
|
||||
if (!userPage) {
|
||||
console.log('urlToken', urlToken)
|
||||
} else { console.log('urlToken', urlToken) }
|
||||
} else if (userType.type_token == this.tokens.occupantTypeToken) {
|
||||
const person = user.people
|
||||
const livingSpace = await this.prismaService.build_living_space.findFirstOrThrow({
|
||||
where: { person_id: person.id, occupant_types: { user_types: { id: userType.id } } },
|
||||
select: { uu_id: true, build_parts_id: true }
|
||||
})
|
||||
const buildUUID = await this.prismaService.build.findFirstOrThrow({
|
||||
where: { build_parts: { some: { id: livingSpace.build_parts_id } } }, select: { uu_id: true }
|
||||
})
|
||||
this.mongoService.set(`Pages/${buildUUID.uu_id}`);
|
||||
const userPage = await this.mongoService.findOne({ [user.uu_id]: { $exists: true } });
|
||||
if (!userPage) {
|
||||
const newUserPageSlot = await this.mongoService.create({ [user.uu_id]: { [`${usersToken}`]: { [`${urlToken}`]: `${page.key}` } } })
|
||||
return newUserPageSlot
|
||||
} else {
|
||||
const updatedUserPageSlot = await this.mongoService.updateOne(userPage._id, { [`${user.uu_id}.${usersToken}.${urlToken}`]: `${page.key}` })
|
||||
return updatedUserPageSlot ? { status: "success", data: updatedUserPageSlot } : { status: "error", data: null }
|
||||
}
|
||||
// console.log('urlToken', { [user.uu_id]: { [`${body.usersToken}`]: { [`${urlToken}`]: `${body.page.key}` } } })
|
||||
}
|
||||
else { throw new NotFoundException('User type not found') }
|
||||
}
|
||||
|
||||
async getPageViaToken(usersUUID: string, token: string, url?: string, skip?: number, limit?: number) {
|
||||
this.mongoService.set("Pages");
|
||||
const addUrlQuery = url ? { url: url } : {};
|
||||
const user = await this.prismaService.users.findFirstOrThrow({ where: { uu_id: usersUUID }, include: { people: true } });
|
||||
const userType = await this.prismaService.user_types.findFirstOrThrow({ where: { token: token } })
|
||||
if (userType.type_token == this.tokens.employeeTypeToken) {
|
||||
const person = user.people[0]
|
||||
const pages = await this.mongoService.findMany({
|
||||
$and: [
|
||||
{ $or: [{ includeTokens: { $in: ['*'] } }, { includeTokens: { $in: [token] } }] },
|
||||
{ $nor: [{ excludeTokens: { $in: ['*'] } }, { excludeTokens: { $in: [token] } }] },
|
||||
addUrlQuery,
|
||||
{ typeToken: this.tokens.employeeTypeToken },
|
||||
],
|
||||
}, limit || 50, skip || 0, ['url'], ['asc'])
|
||||
if (!pages) { throw new NotFoundException(`Pages not found. User type: ${userType.type_token}`) }
|
||||
const employee = await this.prismaService.employees.findFirstOrThrow({
|
||||
where: { people_id: person.id, staff: { user_type_id: userType.id } },
|
||||
select: { uu_id: true, staff_uu_id: true }
|
||||
})
|
||||
const companyUUID = await this.prismaService.companies.findFirstOrThrow({
|
||||
where: { departments: { some: { duties: { some: { staff: { some: { uu_id: employee.staff_uu_id } } } } } } }, select: { uu_id: true }
|
||||
})
|
||||
this.mongoService.set(`Pages/${companyUUID.uu_id}`);
|
||||
const usersPages = await this.mongoService.findMany({ [employee.uu_id]: { $exists: true } });
|
||||
return pages;
|
||||
}
|
||||
else if (userType.type_token == this.tokens.occupantTypeToken) {
|
||||
const person = user.people
|
||||
const pages = await this.mongoService.findMany({
|
||||
$and: [
|
||||
{ $or: [{ includeTokens: { $in: ['*'] } }, { includeTokens: { $in: [token] } }] },
|
||||
{ $nor: [{ excludeTokens: { $in: ['*'] } }, { excludeTokens: { $in: [token] } }] },
|
||||
addUrlQuery,
|
||||
{ typeToken: this.tokens.occupantTypeToken },
|
||||
],
|
||||
}, limit || 50, skip || 0, ['url'], ['asc'])
|
||||
console.log('pages', pages)
|
||||
if (!pages) { throw new NotFoundException(`Pages not found. User type: ${userType.type_token}`) }
|
||||
const livingSpace = await this.prismaService.build_living_space.findFirstOrThrow({
|
||||
where: { person_id: person.id, occupant_types: { user_types: { id: userType.id } } },
|
||||
select: { uu_id: true, build_parts_id: true }
|
||||
})
|
||||
console.log('livingSpace', livingSpace)
|
||||
const buildUUID = await this.prismaService.build.findFirstOrThrow({
|
||||
where: { build_parts: { some: { id: livingSpace.build_parts_id } } }, select: { uu_id: true }
|
||||
})
|
||||
this.mongoService.set(`Pages/${buildUUID.uu_id}`);
|
||||
const usersPages = await this.mongoService.findMany({ [livingSpace.uu_id]: { $exists: true } });
|
||||
console.log('usersPages', usersPages)
|
||||
return Object.entries(pages).map(([key, value]: [string, any]) => {
|
||||
if (usersPages.some((page: any) => page[key])) { value.isSelected = true } else { value.isSelected = false }
|
||||
return value;
|
||||
})
|
||||
}
|
||||
else { throw new NotFoundException('User type not found') }
|
||||
}
|
||||
|
||||
async configurePages(data: Record<string, any>, chunkIndex: number, chunkCount: number) {
|
||||
const count = Object.keys(data).length;
|
||||
console.log(`🧩 Chunk [${chunkIndex}/${chunkCount}] alındı. Kayıt sayısı: ${count}`);
|
||||
await this.saveChunkToDB(data, chunkIndex);
|
||||
return { message: 'Chunk işlendi', count };
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
@Injectable()
|
||||
export class PrismaService
|
||||
extends PrismaClient
|
||||
implements OnModuleInit, OnModuleDestroy
|
||||
{
|
||||
async onModuleInit() {
|
||||
await this.$connect();
|
||||
}
|
||||
|
||||
async onModuleDestroy() {
|
||||
await this.$disconnect();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,90 @@
|
|||
// Token type redis base TOKEN object
|
||||
|
||||
enum UserType {
|
||||
employee = 1,
|
||||
occupant = 2,
|
||||
}
|
||||
|
||||
interface Credentials {
|
||||
person_id: number;
|
||||
person_name: string;
|
||||
}
|
||||
|
||||
interface ApplicationToken {
|
||||
// Application Token Object -> is the main object for the user
|
||||
user_type: number;
|
||||
credential_token: string;
|
||||
user_uu_id: string;
|
||||
user_id: number;
|
||||
person_id: number;
|
||||
person_uu_id: string;
|
||||
request?: Record<string, any>; // Request Info of Client
|
||||
expires_at?: number; // Expiry timestamp
|
||||
reachable_event_codes?: Record<string, any>; // ID list of reachable event codes as "endpoint_code": ["UUID", "UUID"]
|
||||
reachable_app_codes?: Record<string, any>; // ID list of reachable applications as "page_url": ["UUID", "UUID"]
|
||||
}
|
||||
|
||||
interface OccupantToken {
|
||||
// Selection of the occupant type for a build part is made by the user
|
||||
living_space_id: number; // Internal use
|
||||
living_space_uu_id: string; // Outer use
|
||||
occupant_type_id: number;
|
||||
occupant_type_uu_id: string;
|
||||
occupant_type: string;
|
||||
build_id: number;
|
||||
build_uuid: string;
|
||||
build_part_id: number;
|
||||
build_part_uuid: string;
|
||||
responsible_company_id?: number;
|
||||
responsible_company_uuid?: string;
|
||||
responsible_employee_id?: number;
|
||||
responsible_employee_uuid?: string;
|
||||
}
|
||||
|
||||
interface CompanyToken {
|
||||
// Selection of the company for an employee is made by the user
|
||||
company_id: number;
|
||||
company_uu_id: string;
|
||||
department_id: number; // ID list of departments
|
||||
department_uu_id: string; // UUID list of departments
|
||||
duty_id: number;
|
||||
duty_uu_id: string;
|
||||
staff_id: number;
|
||||
staff_uu_id: string;
|
||||
employee_id: number;
|
||||
employee_uu_id: string;
|
||||
bulk_duties_id: number;
|
||||
}
|
||||
|
||||
interface OccupantTokenObject extends ApplicationToken {
|
||||
// Occupant Token Object -> Requires selection of the occupant type for a specific build part
|
||||
available_occupants: Record<string, any> | null;
|
||||
selected?: Record<string, any>; // Selected Occupant Type
|
||||
is_employee: boolean; // Always false
|
||||
is_occupant: boolean; // Always true
|
||||
}
|
||||
|
||||
interface EmployeeTokenObject extends ApplicationToken {
|
||||
// Full hierarchy Employee[staff_id] -> Staff -> Duty -> Department -> Company
|
||||
companies_id_list: number[]; // List of company objects
|
||||
companies_uu_id_list: string[]; // UUID list of company objects
|
||||
duty_id_list: number[]; // List of duty objects
|
||||
duty_uu_id_list: string[]; // UUID list of duty objects
|
||||
selected?: Record<string, any>; // Selected Company Object
|
||||
is_employee: boolean; // Always true
|
||||
is_occupant: boolean; // Always false
|
||||
}
|
||||
|
||||
// Union type for token objects
|
||||
type TokenDictType = EmployeeTokenObject | OccupantTokenObject;
|
||||
|
||||
export {
|
||||
UserType,
|
||||
Credentials,
|
||||
ApplicationToken,
|
||||
OccupantToken,
|
||||
CompanyToken,
|
||||
OccupantTokenObject,
|
||||
EmployeeTokenObject,
|
||||
TokenDictType,
|
||||
};
|
||||
|
|
@ -0,0 +1,279 @@
|
|||
import { uuid, z } from 'zod';
|
||||
|
||||
// ENUM
|
||||
export const UserType = {
|
||||
employee: 1,
|
||||
occupant: 2,
|
||||
} as const;
|
||||
export type UserType = (typeof UserType)[keyof typeof UserType];
|
||||
|
||||
// Credentials
|
||||
export const CredentialsSchema = z.object({
|
||||
uuid: z.string(),
|
||||
fullName: z.string(),
|
||||
});
|
||||
export type Credentials = z.infer<typeof CredentialsSchema>;
|
||||
|
||||
export const AuthTokenSchema = z.object({
|
||||
people: z.object({
|
||||
firstname: z.string(),
|
||||
surname: z.string(),
|
||||
middle_name: z.string(),
|
||||
birthname: z.string().nullable(),
|
||||
sex_code: z.string(),
|
||||
person_ref: z.string().nullable(),
|
||||
person_tag: z.string(),
|
||||
father_name: z.string(),
|
||||
mother_name: z.string(),
|
||||
country_code: z.string(),
|
||||
// national_identity_id: z.string(),
|
||||
birth_place: z.string(),
|
||||
birth_date: z.date(),
|
||||
tax_no: z.string(),
|
||||
ref_id: z.string().nullable(),
|
||||
replication_id: z.number().nullable(),
|
||||
cryp_uu_id: z.string().nullable(),
|
||||
created_credentials_token: z.string().nullable(),
|
||||
updated_credentials_token: z.string().nullable(),
|
||||
confirmed_credentials_token: z.string().nullable(),
|
||||
ref_int: z.number().nullable(),
|
||||
is_confirmed: z.boolean(),
|
||||
deleted: z.boolean(),
|
||||
active: z.boolean(),
|
||||
is_notification_send: z.boolean(),
|
||||
is_email_send: z.boolean(),
|
||||
// id: z.number(),
|
||||
uu_id: z.string(),
|
||||
expiry_starts: z.date(),
|
||||
expiry_ends: z.date(),
|
||||
created_at: z.date(),
|
||||
updated_at: z.date(),
|
||||
}),
|
||||
users: z.object({
|
||||
user_tag: z.string(),
|
||||
email: z.string(),
|
||||
user_type: z.string(),
|
||||
phone_number: z.string(),
|
||||
via: z.string(),
|
||||
avatar: z.string(),
|
||||
// hash_password: z.string(),
|
||||
password_token: z.string(),
|
||||
remember_me: z.boolean(),
|
||||
password_expires_day: z.number(),
|
||||
password_expiry_begins: z.date(),
|
||||
related_company: z.string(),
|
||||
person_id: z.number(),
|
||||
person_uu_id: z.string(),
|
||||
local_timezone: z.string(),
|
||||
ref_id: z.string().nullable(),
|
||||
ref_int: z.number().nullable(),
|
||||
replication_id: z.number().nullable(),
|
||||
cryp_uu_id: z.string().nullable(),
|
||||
created_credentials_token: z.string().nullable(),
|
||||
updated_credentials_token: z.string().nullable(),
|
||||
confirmed_credentials_token: z.string().nullable(),
|
||||
is_confirmed: z.boolean(),
|
||||
deleted: z.boolean(),
|
||||
active: z.boolean(),
|
||||
is_notification_send: z.boolean(),
|
||||
is_email_send: z.boolean(),
|
||||
// id: z.number(),
|
||||
uu_id: z.string(),
|
||||
expiry_starts: z.date(),
|
||||
expiry_ends: z.date(),
|
||||
created_at: z.date(),
|
||||
updated_at: z.date(),
|
||||
default_language: z.string(),
|
||||
}),
|
||||
credentials: CredentialsSchema,
|
||||
selectionList: z
|
||||
.object({
|
||||
type: z.string(),
|
||||
list: z.array(z.any()).optional().default([]),
|
||||
})
|
||||
.optional()
|
||||
.default({
|
||||
type: '',
|
||||
list: [],
|
||||
}),
|
||||
});
|
||||
|
||||
export type AuthToken = z.infer<typeof AuthTokenSchema>;
|
||||
|
||||
export const EmployeeTokenSchema = z.object({
|
||||
uuid: z.string(),
|
||||
company: z.object({
|
||||
// id: z.number(),
|
||||
uu_id: z.string(),
|
||||
formal_name: z.string(),
|
||||
company_type: z.string(),
|
||||
commercial_type: z.string(),
|
||||
tax_no: z.string(),
|
||||
public_name: z.string(),
|
||||
company_tag: z.string(),
|
||||
default_lang_type: z.string(),
|
||||
default_money_type: z.string(),
|
||||
is_commercial: z.boolean(),
|
||||
is_blacklist: z.boolean(),
|
||||
parent_id: z.number().nullable(),
|
||||
workplace_no: z.string().nullable(),
|
||||
// official_address_id: z.number().nullable(),
|
||||
official_address_uu_id: z.string().nullable(),
|
||||
top_responsible_company_id: z.number().nullable(),
|
||||
top_responsible_company_uu_id: z.string().nullable(),
|
||||
ref_id: z.string().nullable(),
|
||||
// replication_id: z.number(),
|
||||
// cryp_uu_id: z.string().nullable(),
|
||||
created_credentials_token: z.string().nullable(),
|
||||
updated_credentials_token: z.string().nullable(),
|
||||
confirmed_credentials_token: z.string().nullable(),
|
||||
is_confirmed: z.boolean(),
|
||||
deleted: z.boolean(),
|
||||
active: z.boolean(),
|
||||
is_notification_send: z.boolean(),
|
||||
is_email_send: z.boolean(),
|
||||
expiry_starts: z.date(),
|
||||
expiry_ends: z.date(),
|
||||
created_at: z.date(),
|
||||
updated_at: z.date(),
|
||||
ref_int: z.number().nullable(),
|
||||
}),
|
||||
department: z.object({
|
||||
// id: z.number(),
|
||||
uu_id: z.string(),
|
||||
parent_department_id: z.number().nullable(),
|
||||
department_code: z.string(),
|
||||
department_name: z.string(),
|
||||
department_description: z.string(),
|
||||
// company_id: z.number(),
|
||||
company_uu_id: z.string(),
|
||||
// ref_id: z.string().nullable(),
|
||||
// replication_id: z.number(),
|
||||
// cryp_uu_id: z.string().nullable(),
|
||||
created_credentials_token: z.string().nullable(),
|
||||
updated_credentials_token: z.string().nullable(),
|
||||
confirmed_credentials_token: z.string().nullable(),
|
||||
is_confirmed: z.boolean(),
|
||||
deleted: z.boolean(),
|
||||
active: z.boolean(),
|
||||
is_notification_send: z.boolean(),
|
||||
is_email_send: z.boolean(),
|
||||
expiry_starts: z.date(),
|
||||
expiry_ends: z.date(),
|
||||
created_at: z.date(),
|
||||
updated_at: z.date(),
|
||||
ref_int: z.number().nullable(),
|
||||
}),
|
||||
duty: z.object({
|
||||
// id: z.number(),
|
||||
uu_id: z.string(),
|
||||
duty_name: z.string(),
|
||||
duty_code: z.string(),
|
||||
duty_description: z.string(),
|
||||
// ref_id: z.string().nullable(),
|
||||
// replication_id: z.number(),
|
||||
// cryp_uu_id: z.string().nullable(),
|
||||
created_credentials_token: z.string().nullable(),
|
||||
updated_credentials_token: z.string().nullable(),
|
||||
confirmed_credentials_token: z.string().nullable(),
|
||||
is_confirmed: z.boolean(),
|
||||
deleted: z.boolean(),
|
||||
active: z.boolean(),
|
||||
is_notification_send: z.boolean(),
|
||||
is_email_send: z.boolean(),
|
||||
expiry_starts: z.date(),
|
||||
expiry_ends: z.date(),
|
||||
created_at: z.date(),
|
||||
updated_at: z.date(),
|
||||
ref_int: z.number().nullable(),
|
||||
}),
|
||||
employee: z.object({
|
||||
// id: z.number(),
|
||||
uu_id: z.string(),
|
||||
staff_id: z.number(),
|
||||
staff_uu_id: z.string(),
|
||||
people_id: z.number(),
|
||||
people_uu_id: z.string(),
|
||||
// ref_id: z.string().nullable(),
|
||||
// replication_id: z.number(),
|
||||
// cryp_uu_id: z.string().nullable(),
|
||||
created_credentials_token: z.string().nullable(),
|
||||
updated_credentials_token: z.string().nullable(),
|
||||
confirmed_credentials_token: z.string().nullable(),
|
||||
is_confirmed: z.boolean(),
|
||||
deleted: z.boolean(),
|
||||
active: z.boolean(),
|
||||
is_notification_send: z.boolean(),
|
||||
is_email_send: z.boolean(),
|
||||
expiry_starts: z.date(),
|
||||
expiry_ends: z.date(),
|
||||
created_at: z.date(),
|
||||
updated_at: z.date(),
|
||||
ref_int: z.number().nullable(),
|
||||
}),
|
||||
staff: z.object({
|
||||
// id: z.number(),
|
||||
uu_id: z.string(),
|
||||
staff_description: z.string(),
|
||||
staff_name: z.string(),
|
||||
staff_code: z.string(),
|
||||
// duties_id: z.number(),
|
||||
duties_uu_id: z.string(),
|
||||
// function_retriever: z.string().nullable(),
|
||||
// ref_id: z.string().nullable(),
|
||||
// replication_id: z.number(),
|
||||
// cryp_uu_id: z.string().nullable(),
|
||||
created_credentials_token: z.string().nullable(),
|
||||
updated_credentials_token: z.string().nullable(),
|
||||
confirmed_credentials_token: z.string().nullable(),
|
||||
is_confirmed: z.boolean(),
|
||||
deleted: z.boolean(),
|
||||
active: z.boolean(),
|
||||
is_notification_send: z.boolean(),
|
||||
is_email_send: z.boolean(),
|
||||
expiry_starts: z.date(),
|
||||
expiry_ends: z.date(),
|
||||
created_at: z.date(),
|
||||
updated_at: z.date(),
|
||||
ref_int: z.number().nullable(),
|
||||
}),
|
||||
|
||||
menu: z.array(z.object({})).nullable(),
|
||||
pages: z.array(z.string()).nullable(),
|
||||
events: z.record(z.string(), z.string()).nullable(),
|
||||
|
||||
selection: z.record(z.string(), z.unknown()).nullable(),
|
||||
typeToken: z.string(),
|
||||
functionsRetriever: z.string(),
|
||||
kind: z.literal(UserType.employee),
|
||||
});
|
||||
|
||||
export const OccupantTokenSchema = z.object({
|
||||
uuid: z.string(),
|
||||
livingSpace: z.object({}),
|
||||
occupant: z.object({}),
|
||||
build: z.object({}),
|
||||
part: z.object({}),
|
||||
company: z.object({}).optional(),
|
||||
|
||||
menu: z.array(z.object({
|
||||
key: z.string(),
|
||||
icon: z.string(),
|
||||
text: z.object({ tr: z.string(), en: z.string() }),
|
||||
page: z.string().nullable(),
|
||||
token: z.string().nullable(),
|
||||
color: z.string(),
|
||||
subs: z.array(z.lazy(() => OccupantTokenSchema.shape.menu.element)).nullable()
|
||||
})).nullable(),
|
||||
pages: z.record(z.string(), z.string()).nullable(),
|
||||
events: z.record(z.string(), z.string()).nullable(),
|
||||
|
||||
selection: z.record(z.string(), z.unknown()).nullable(),
|
||||
typeToken: z.string(),
|
||||
functionsRetriever: z.string(),
|
||||
kind: z.literal(UserType.occupant),
|
||||
});
|
||||
|
||||
export const TokenDictTypes = z.discriminatedUnion('kind', [EmployeeTokenSchema, OccupantTokenSchema]);
|
||||
|
||||
export type TokenDictInterface = z.infer<typeof TokenDictTypes>;
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
export function processUsers(): void {
|
||||
console.log('Processing users New...');
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { UsersController } from './users.controller';
|
||||
|
||||
describe('UsersController', () => {
|
||||
let controller: UsersController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [UsersController],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<UsersController>(UsersController);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Put,
|
||||
Delete,
|
||||
Param,
|
||||
Body,
|
||||
HttpCode,
|
||||
} from '@nestjs/common';
|
||||
import { UsersService } from './users.service';
|
||||
|
||||
/**
|
||||
* USER TYPE CODE = BM BLD OCC ...
|
||||
* class Func
|
||||
* code = "uuid4"
|
||||
* TYPE = "build_manager"
|
||||
*/
|
||||
|
||||
@Controller('users')
|
||||
export class UsersController {
|
||||
constructor(private usersService: UsersService) {}
|
||||
|
||||
@Post('filter')
|
||||
@HttpCode(200)
|
||||
async filterUsers(@Body() query: any) {
|
||||
return this.usersService.findWithPagination(query);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
import { Module } from '@nestjs/common';
|
||||
import { UsersService } from './users.service';
|
||||
import { UsersController } from './users.controller';
|
||||
import { PrismaModule } from '@/prisma/prisma.module';
|
||||
import { CacheService } from '../database/redis/redis.service';
|
||||
import { UtilsModule } from '../utils/utils.module';
|
||||
import { RedisModule } from '../database/redis/redis.module';
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule, UtilsModule, RedisModule],
|
||||
providers: [UsersService],
|
||||
controllers: [UsersController],
|
||||
exports: [UsersService],
|
||||
})
|
||||
export class UsersModule { }
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
import { Injectable } from '@nestjs/common';
|
||||
import { PrismaService } from '@/src/prisma.service';
|
||||
import { users } from '@prisma/client';
|
||||
|
||||
@Injectable()
|
||||
export class UsersService {
|
||||
constructor(private prisma: PrismaService) {}
|
||||
|
||||
async findAll(): Promise<users[]> {
|
||||
return this.prisma.users.findMany();
|
||||
}
|
||||
|
||||
async findOne(id: number): Promise<users | null> {
|
||||
return this.prisma.users.findUnique({ where: { id } });
|
||||
}
|
||||
|
||||
async create(data: any): Promise<users> {
|
||||
return this.prisma.users.create({ data });
|
||||
}
|
||||
|
||||
async update(id: number, data: any): Promise<users> {
|
||||
return this.prisma.users.update({ where: { id }, data });
|
||||
}
|
||||
|
||||
async remove(id: number): Promise<users> {
|
||||
return this.prisma.users.delete({ where: { id } });
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
import { Injectable } from '@nestjs/common';
|
||||
import { PrismaService } from '@/src/prisma.service';
|
||||
import { Prisma, users } from '@prisma/client';
|
||||
import { CacheService } from '../database/redis/redis.service';
|
||||
import { PaginationHelper, PaginationInfo } from '../utils/pagination-helper';
|
||||
|
||||
@Injectable()
|
||||
export class UsersService {
|
||||
constructor(
|
||||
private prisma: PrismaService,
|
||||
private cacheService: CacheService,
|
||||
private paginationHelper: PaginationHelper,
|
||||
) { }
|
||||
|
||||
async findAll(filter: any): Promise<Partial<users>[]> {
|
||||
return this.prisma.users.findMany({
|
||||
where: { ...filter },
|
||||
});
|
||||
}
|
||||
|
||||
async findDynamic(
|
||||
query: Prisma.usersFindManyArgs,
|
||||
): Promise<{ totalCount: number; result: Partial<users>[] }> {
|
||||
const totalCount = await this.prisma.users.count({
|
||||
where: query.where,
|
||||
});
|
||||
const result = await this.prisma.users.findMany(query);
|
||||
return { totalCount, result };
|
||||
}
|
||||
|
||||
async findWithPagination(
|
||||
query: any & { page?: number; pageSize?: number },
|
||||
): Promise<{ data: any[]; pagination: PaginationInfo }> {
|
||||
return this.paginationHelper.paginate(this.prisma.users, query);
|
||||
}
|
||||
|
||||
async findOne(uuid: string): Promise<Partial<users> | null> {
|
||||
return this.prisma.users.findUnique({
|
||||
where: { uu_id: uuid },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,95 @@
|
|||
import { INestApplication, RequestMethod } from '@nestjs/common';
|
||||
import { ModulesContainer, Reflector } from '@nestjs/core';
|
||||
import { PATH_METADATA, METHOD_METADATA } from '@nestjs/common/constants';
|
||||
import { PrismaService } from '@/src/prisma.service';
|
||||
|
||||
/**
|
||||
* Helper: Method string'i döndür
|
||||
*/
|
||||
function getMethodString(requestMethod: RequestMethod): string {
|
||||
return RequestMethod[requestMethod];
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper: Path'leri normalize et (iki tane slash varsa düzelt)
|
||||
*/
|
||||
function normalizePath(...paths: string[]): string {
|
||||
const normalized =
|
||||
'/' +
|
||||
paths
|
||||
.filter(Boolean)
|
||||
.map((p) => p.replace(/^\/|\/$/g, ''))
|
||||
.filter((p) => p.length > 0)
|
||||
.join('/');
|
||||
|
||||
return normalized === '/' ? '' : normalized; // Home route'ı dışla
|
||||
}
|
||||
|
||||
export async function extractAndPersistRoutes(
|
||||
app: INestApplication,
|
||||
prisma: PrismaService,
|
||||
): Promise<{ method: string; url: string }[]> {
|
||||
const modulesContainer = app.get(ModulesContainer);
|
||||
const reflector = app.get(Reflector);
|
||||
const routes: { method: string; url: string }[] = [];
|
||||
|
||||
modulesContainer.forEach((moduleRef) => {
|
||||
const controllers = [...moduleRef.controllers.values()];
|
||||
controllers.forEach(({ metatype }) => {
|
||||
if (!metatype || typeof metatype !== 'function') return;
|
||||
|
||||
const controllerPath =
|
||||
reflector.get<string>(PATH_METADATA, metatype) ?? '';
|
||||
const prototype = metatype.prototype;
|
||||
|
||||
const methodNames = Object.getOwnPropertyNames(prototype).filter(
|
||||
(m) => m !== 'constructor',
|
||||
);
|
||||
|
||||
methodNames.forEach((methodName) => {
|
||||
const methodRef = prototype[methodName];
|
||||
const routePath = reflector.get<string>(PATH_METADATA, methodRef);
|
||||
const requestMethod = reflector.get<RequestMethod>(
|
||||
METHOD_METADATA,
|
||||
methodRef,
|
||||
);
|
||||
|
||||
if (routePath !== undefined && requestMethod !== undefined) {
|
||||
const method = getMethodString(requestMethod);
|
||||
const fullPath = normalizePath(controllerPath, routePath);
|
||||
if (fullPath !== '') {
|
||||
routes.push({ method, url: fullPath });
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const existing = await prisma.endpoint_restriction.findMany({
|
||||
select: { endpoint_name: true, endpoint_method: true },
|
||||
});
|
||||
|
||||
const existingSet = new Set(
|
||||
existing.map((r) => `${r.endpoint_method}_${r.endpoint_name}`),
|
||||
);
|
||||
|
||||
const newOnes = routes.filter(
|
||||
(r) => !existingSet.has(`${r.method}_${r.url}`),
|
||||
);
|
||||
|
||||
// İsteğe bağlı: veritabanına kaydet
|
||||
// for (const route of newOnes) {
|
||||
// await prisma.endpoint_restriction.create({
|
||||
// data: {
|
||||
// endpoint_method: route.method,
|
||||
// endpoint_name: route.url,
|
||||
// is_active: true,
|
||||
// },
|
||||
// });
|
||||
// }
|
||||
|
||||
console.log('🧭 Route JSON Listesi:');
|
||||
console.dir(routes, { depth: null });
|
||||
|
||||
return routes;
|
||||
}
|
||||
|
|
@ -0,0 +1,63 @@
|
|||
import { ForbiddenException, MisdirectedException, Injectable } from "@nestjs/common";
|
||||
import { RedisHandlers } from "../store/redisHandlers";
|
||||
|
||||
@Injectable()
|
||||
export class Navigator {
|
||||
|
||||
constructor(private redisHandler: RedisHandlers) { }
|
||||
|
||||
async getAllInfos(mainService: any) {
|
||||
const mainServiceMapper = mainService?.mapper
|
||||
if (!mainServiceMapper) { throw new ForbiddenException(`Mapper in ${mainService.constructor.name} is missing or null`) }
|
||||
const allInfos = Object.entries(mainServiceMapper).map(([key, value]) => {
|
||||
return {
|
||||
key,
|
||||
value
|
||||
}
|
||||
})
|
||||
return allInfos
|
||||
}
|
||||
|
||||
async getInfos(mainService: any, userToken: string) {
|
||||
// Get asked service by userToken
|
||||
const mainServiceMapper = mainService?.mapper
|
||||
if (!mainServiceMapper) { throw new ForbiddenException(`Mapper in ${mainService.constructor.name} is missing or null`) }
|
||||
// Get related events from mainServiceMapper by userToken
|
||||
const relatedService = mainServiceMapper?.[userToken]
|
||||
if (!relatedService) { throw new MisdirectedException(`No service found for drive token: ${userToken}`) }
|
||||
// Call event infos from relatedService
|
||||
return await relatedService.infoEvents(userToken);
|
||||
}
|
||||
|
||||
async getService(request: any, mapper: any) {
|
||||
// Get request drive token from acess control guard and retrieve related Service
|
||||
const driveToken = request.driveToken
|
||||
if (!driveToken) { throw new Error('Drive token is missing or null') }
|
||||
// Get second part of drive token which is user type token
|
||||
const secondPartOfDriveToken = driveToken.split(":")[1]
|
||||
if (!secondPartOfDriveToken) { throw new Error('Drive token is missing or null') }
|
||||
// Get related service from mapper which function maps registered events to functions
|
||||
return mapper[secondPartOfDriveToken];
|
||||
}
|
||||
|
||||
async getFunction(request: any, mapper: any, query: any) {
|
||||
const relatedService = await this.getService(request, mapper)
|
||||
if (!relatedService) { throw new Error(`No service found for drive token: ${request.driveToken}`) }
|
||||
try {
|
||||
// Get function mapper from related service
|
||||
if (!relatedService.mapper) { throw new Error(`Mapper in ${relatedService.constructor.name} is missing or null`) }
|
||||
// Get redis select token object from redis
|
||||
const selectObject = await this.redisHandler.getSelectFromRedis(request);
|
||||
if (!selectObject) { throw new Error(`Select object is missing or null`) }
|
||||
if (!selectObject.value.events) { throw new Error(`Events in select object is missing or null`) }
|
||||
const eventKey = Object.entries(selectObject.value.events).filter((key) => key.includes(request.driveToken))[0]
|
||||
if (!eventKey) { throw new Error(`No event is registered for this user ${request.driveToken}`) }
|
||||
// Get function to call from related service mapper
|
||||
const functionToCall = relatedService.mapper[eventKey.join(":")];
|
||||
if (!functionToCall || typeof functionToCall !== 'function') {
|
||||
throw new Error(`No function found for drive token: ${request.driveToken}`);
|
||||
}
|
||||
return await functionToCall(query);
|
||||
} catch (error) { throw new ForbiddenException(`This user is not allowed to access this endpoint. Please contact your system administrator.`) }
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,67 @@
|
|||
import { Injectable } from "@nestjs/common";
|
||||
import { Events, Mapper } from "@/src/utils/types/url";
|
||||
import { createHash } from 'crypto';
|
||||
|
||||
@Injectable()
|
||||
export class UrlHandler {
|
||||
private createSecureKeyWithoutLib(url: string): string {
|
||||
const subString = createHash('sha256').update(url).digest().toString('base64').substring(0, 48)
|
||||
return subString.replace(/=/g, 'E').replace(/-/g, 'M').replace(/_/g, 'N').replace(/\+/g, 'P').replace(/\//g, 'Q')
|
||||
}
|
||||
|
||||
async getSecureUrlToken(url: string): Promise<string> {
|
||||
return this.createSecureKeyWithoutLib(url);
|
||||
}
|
||||
|
||||
async getEvents(events: Events, mapper: Mapper) {
|
||||
for (const keyUrl of Object.keys(mapper)) {
|
||||
const splittedMapper = keyUrl.split(':')
|
||||
const eToken = splittedMapper[0]
|
||||
const token = splittedMapper[1]
|
||||
const key = splittedMapper[2]
|
||||
const eventKey = `${eToken}:${token}`
|
||||
|
||||
if (Object.keys(events).includes(eventKey)) {
|
||||
// Check if the event contains an item with the matching key
|
||||
const eventArray = events[eventKey]
|
||||
const foundEvent = eventArray.find(item => item.key === key)
|
||||
|
||||
if (!foundEvent) {
|
||||
throw new Error(`Event key ${key} not found in event ${eventKey}`)
|
||||
}
|
||||
} else {
|
||||
throw new Error(`Event ${eventKey} not found in events`)
|
||||
}
|
||||
}
|
||||
return mapper;
|
||||
}
|
||||
|
||||
async infoEvents(events: Events, urlRetriever: string | null = null, functionRetriever: string | null = null) {
|
||||
if (urlRetriever && !functionRetriever) {
|
||||
console.log("urlRetriever", urlRetriever)
|
||||
if (events[urlRetriever]) {
|
||||
return [[urlRetriever, events[urlRetriever]]];
|
||||
}
|
||||
return [];
|
||||
} else if (urlRetriever && functionRetriever) {
|
||||
if (events[urlRetriever]) {
|
||||
const eventItem = events[urlRetriever].find(item => item.key === functionRetriever);
|
||||
if (eventItem) {
|
||||
return [[urlRetriever, { [functionRetriever]: eventItem }]];
|
||||
}
|
||||
}
|
||||
return [];
|
||||
} else if (!urlRetriever && functionRetriever) {
|
||||
const filteredEvents: [string, any][] = [];
|
||||
Object.entries(events).forEach(([url, eventArray]) => {
|
||||
const eventItem = eventArray.find(item => item.key === functionRetriever);
|
||||
if (eventItem) {
|
||||
filteredEvents.push([url, { [functionRetriever]: eventItem }]);
|
||||
}
|
||||
});
|
||||
return filteredEvents;
|
||||
} else {
|
||||
return Object.entries(events);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,65 @@
|
|||
import { Injectable } from '@nestjs/common';
|
||||
import { PrismaService } from '@/src/prisma.service';
|
||||
|
||||
export interface PaginationInfo {
|
||||
totalCount: number;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
totalPages: number;
|
||||
hasNextPage: boolean;
|
||||
hasPreviousPage: boolean;
|
||||
pageCount: number;
|
||||
}
|
||||
|
||||
type ModelDelegate = {
|
||||
count: (args: any) => Promise<number>;
|
||||
findMany: (args: any) => Promise<any[]>;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class PaginationHelper {
|
||||
constructor(private prisma: PrismaService) { }
|
||||
|
||||
/**
|
||||
* Sayfalama destekli sorgu yapar
|
||||
*
|
||||
* @param modelDelegate Prisma model delegesi (ör. prisma.users)
|
||||
* @param query Prisma findMany argümanları + opsiyonel page, pageSize
|
||||
* @returns { data, pagination } sonuç ve sayfalama bilgisi
|
||||
*/
|
||||
async paginate(
|
||||
modelDelegate: ModelDelegate,
|
||||
query: any & { page?: number; pageSize?: number },
|
||||
): Promise<{ data: any[]; pagination: PaginationInfo }> {
|
||||
const { page = 1, pageSize = 10, ...prismaQuery } = query;
|
||||
const totalCount = await modelDelegate.count({ where: prismaQuery.where });
|
||||
const totalPages = Math.max(Math.ceil(totalCount / pageSize), 1);
|
||||
const pageNumber = page < 1 ? 1 : page > totalPages ? totalPages : page;
|
||||
const pageSizeNumber = pageSize > 0 ? pageSize : 10;
|
||||
const data = await modelDelegate.findMany({
|
||||
...prismaQuery,
|
||||
skip: (pageNumber - 1) * pageSizeNumber,
|
||||
take: pageSizeNumber,
|
||||
});
|
||||
const pageCount = data.length;
|
||||
return {
|
||||
data,
|
||||
pagination: {
|
||||
totalCount,
|
||||
page: pageNumber,
|
||||
pageSize: pageSizeNumber,
|
||||
totalPages,
|
||||
hasNextPage: pageNumber < totalPages,
|
||||
hasPreviousPage: pageNumber > 1,
|
||||
pageCount,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async findWithPagination(
|
||||
query: any & { page?: number; pageSize?: number },
|
||||
service: ModelDelegate,
|
||||
): Promise<{ data: any[]; pagination: PaginationInfo }> {
|
||||
return this.paginate(service, query);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,64 @@
|
|||
import * as crypto from 'crypto';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
interface TokenConfig {
|
||||
ACCESS_TOKEN_LENGTH: number;
|
||||
REFRESHER_TOKEN_LENGTH: number;
|
||||
}
|
||||
|
||||
const tokenConfig: TokenConfig = {
|
||||
ACCESS_TOKEN_LENGTH: 64,
|
||||
REFRESHER_TOKEN_LENGTH: 128,
|
||||
};
|
||||
|
||||
class PasswordHandlers {
|
||||
generateRandomUUID(is_string: boolean = true): string {
|
||||
return is_string ? uuidv4().toString() : uuidv4();
|
||||
}
|
||||
|
||||
create_hashed_password(uuid: string, password: string): string {
|
||||
const data = `${uuid}:${password}`;
|
||||
return crypto.createHash('sha256').update(data).digest('hex');
|
||||
}
|
||||
|
||||
createSelectToken(accessToken: string, userUUID: string) {
|
||||
const data = `${accessToken}:${userUUID}`;
|
||||
return crypto.createHash('sha256').update(data).digest('hex');
|
||||
}
|
||||
|
||||
check_password(
|
||||
uuid: string,
|
||||
password: string,
|
||||
hashed_password: string,
|
||||
): boolean {
|
||||
const created_hashed_password = this.create_hashed_password(uuid, password);
|
||||
return created_hashed_password === hashed_password;
|
||||
}
|
||||
|
||||
generateAccessToken(): string {
|
||||
return this.generateToken(tokenConfig.ACCESS_TOKEN_LENGTH);
|
||||
}
|
||||
|
||||
generateRefreshToken(): string {
|
||||
return this.generateToken(tokenConfig.REFRESHER_TOKEN_LENGTH);
|
||||
}
|
||||
|
||||
generateToken(length: number): string {
|
||||
const letters = 'abcdefghijklmnopqrstuvwxyz';
|
||||
const mergedLetters = [...letters, ...letters.toUpperCase().split('')];
|
||||
let token = crypto.randomBytes(length).toString('base64url');
|
||||
|
||||
token = token
|
||||
.split('')
|
||||
.map((char) =>
|
||||
mergedLetters.includes(char)
|
||||
? char
|
||||
: mergedLetters[Math.floor(Math.random() * mergedLetters.length)],
|
||||
)
|
||||
.join('');
|
||||
|
||||
return token;
|
||||
}
|
||||
}
|
||||
|
||||
export { PasswordHandlers };
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
@Injectable()
|
||||
export class MongoHandler {
|
||||
constructor() { }
|
||||
}
|
||||
|
|
@ -0,0 +1,256 @@
|
|||
import {
|
||||
TokenDictTypes,
|
||||
TokenDictInterface,
|
||||
AuthToken,
|
||||
AuthTokenSchema,
|
||||
} from '../../types/auth/token';
|
||||
import { CacheService } from '../../database/redis/redis.service';
|
||||
import { PasswordHandlers } from './loginHandler';
|
||||
import { Injectable, ForbiddenException } from '@nestjs/common';
|
||||
|
||||
interface LoginFromRedis {
|
||||
key: string;
|
||||
value: AuthToken;
|
||||
}
|
||||
|
||||
interface SelectFromRedis {
|
||||
key: string;
|
||||
value: TokenDictInterface;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class RedisHandlers {
|
||||
AUTH_TOKEN = 'AUTH_TOKEN';
|
||||
SELECT_TOKEN = 'SELECT_TOKEN';
|
||||
constructor(
|
||||
private readonly cacheService: CacheService,
|
||||
private readonly passwordService: PasswordHandlers,
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Validates that a Redis key follows the expected format
|
||||
* Format: AUTH_TOKEN:token:token:UUID or AUTH_TOKEN:token:token:*:*
|
||||
this.AUTH_TOKEN:token:token:UUID:UUID
|
||||
*/
|
||||
private validateRedisKey(redisKey: string, type: string): boolean {
|
||||
if (!redisKey.startsWith(type + ':')) {
|
||||
throw new ForbiddenException(
|
||||
`Invalid Redis key format. Must start with ${type}:`,
|
||||
);
|
||||
}
|
||||
const colonCount = (redisKey.match(/:/g) || []).length;
|
||||
if (colonCount !== 4) {
|
||||
throw new ForbiddenException(
|
||||
`Invalid Redis key format. Must have exactly 5 colons. Found: ${colonCount}`,
|
||||
);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public mergeLoginKey(req: Request): string {
|
||||
const acsToken = req.headers['acs'];
|
||||
if (!acsToken) {
|
||||
throw new ForbiddenException('Access token header is missing');
|
||||
}
|
||||
const mergedRedisKey = `${this.AUTH_TOKEN}:${acsToken}:${acsToken}:*:*`;
|
||||
this.validateRedisKey(mergedRedisKey, this.AUTH_TOKEN);
|
||||
return mergedRedisKey;
|
||||
}
|
||||
|
||||
public mergeSelectKey(req: Request): string {
|
||||
const acsToken = req.headers['acs'];
|
||||
if (!acsToken) {
|
||||
throw new ForbiddenException('Access token header is missing');
|
||||
}
|
||||
const slcToken = req.headers['slc'];
|
||||
if (!slcToken) {
|
||||
throw new ForbiddenException('Select token header is missing');
|
||||
}
|
||||
const mergedRedisKey = `${this.SELECT_TOKEN}:${acsToken}:${slcToken}:*:*`;
|
||||
this.validateRedisKey(mergedRedisKey, this.SELECT_TOKEN);
|
||||
return mergedRedisKey;
|
||||
}
|
||||
|
||||
public mergeLoginUser(userUUID: string) {
|
||||
const mergedRedisKey = `${this.AUTH_TOKEN}:*:*:${userUUID}:${userUUID}`;
|
||||
this.validateRedisKey(mergedRedisKey, this.AUTH_TOKEN);
|
||||
return mergedRedisKey;
|
||||
}
|
||||
|
||||
public mergeSelectUser(userUUID: string, livingUUID: string) {
|
||||
const mergedRedisKey = `${this.SELECT_TOKEN}:*:*:${userUUID}:${livingUUID}`;
|
||||
this.validateRedisKey(mergedRedisKey, this.SELECT_TOKEN);
|
||||
return mergedRedisKey;
|
||||
}
|
||||
|
||||
generateSelectToken(accessToken: string, userUUID: string) {
|
||||
return this.passwordService.createSelectToken(accessToken, userUUID);
|
||||
}
|
||||
|
||||
generateAccessToken() {
|
||||
return this.passwordService.generateAccessToken();
|
||||
}
|
||||
|
||||
private async scanKeys(pattern: string, type: string): Promise<string[]> {
|
||||
this.validateRedisKey(pattern, type);
|
||||
const client = (this.cacheService as any).client;
|
||||
if (!client) throw new Error('Redis client not available');
|
||||
|
||||
const keys: string[] = [];
|
||||
let cursor = '0';
|
||||
|
||||
do {
|
||||
const [nextCursor, matchedKeys] = await client.scan(
|
||||
cursor,
|
||||
'MATCH',
|
||||
pattern,
|
||||
);
|
||||
cursor = nextCursor;
|
||||
keys.push(...matchedKeys);
|
||||
} while (cursor !== '0');
|
||||
|
||||
return keys;
|
||||
}
|
||||
|
||||
async getLoginFromRedis(req: Request): Promise<LoginFromRedis | null> {
|
||||
const mergedKey = this.mergeLoginKey(req);
|
||||
if (mergedKey.includes('*')) {
|
||||
const keys = await this.scanKeys(mergedKey, this.AUTH_TOKEN);
|
||||
if (keys.length === 0) {
|
||||
throw new ForbiddenException('Authorization failed - No matching keys');
|
||||
}
|
||||
for (const key of keys) {
|
||||
const parts = key.split(':');
|
||||
if (parts.length >= 3) {
|
||||
if (parts[1] === parts[2]) {
|
||||
const value = await this.cacheService.get(key);
|
||||
if (value) {
|
||||
return { key: value.key, value: value.value };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new ForbiddenException('Authorization failed - No valid keys');
|
||||
}
|
||||
|
||||
const value = await this.cacheService.get(mergedKey);
|
||||
return value
|
||||
? { key: mergedKey, value: AuthTokenSchema.parse(value) }
|
||||
: null;
|
||||
}
|
||||
|
||||
async getSelectFromRedis(req: Request): Promise<SelectFromRedis | null> {
|
||||
const mergedKey = this.mergeSelectKey(req);
|
||||
if (mergedKey.includes('*')) {
|
||||
const keys = await this.scanKeys(mergedKey, this.SELECT_TOKEN);
|
||||
|
||||
if (keys.length === 0) {
|
||||
throw new ForbiddenException(
|
||||
'Authorization failed - No matching select keys',
|
||||
);
|
||||
}
|
||||
for (const key of keys) {
|
||||
const value = await this.cacheService.get(key);
|
||||
if (value) {
|
||||
return { key: value.key, value: value.value };
|
||||
}
|
||||
}
|
||||
throw new ForbiddenException(
|
||||
'Authorization failed - No valid select keys',
|
||||
);
|
||||
}
|
||||
|
||||
const value = await this.cacheService.get(mergedKey);
|
||||
return value
|
||||
? { key: mergedKey, value: TokenDictTypes.parse(value) }
|
||||
: null;
|
||||
}
|
||||
|
||||
async callExistingLoginToken(userUUID: string): Promise<string | null> {
|
||||
const mergedKey = this.mergeLoginUser(userUUID);
|
||||
if (!mergedKey.includes('*')) {
|
||||
throw new ForbiddenException(
|
||||
'Authorization failed - No valid select keys',
|
||||
);
|
||||
}
|
||||
const keys = await this.scanKeys(mergedKey, this.AUTH_TOKEN);
|
||||
if (keys.length === 0) {
|
||||
return null;
|
||||
}
|
||||
for (const key of keys) {
|
||||
const value = await this.cacheService.get(key);
|
||||
if (value) {
|
||||
this.cacheService.set_with_ttl(value.key, value.value, 60 * 30);
|
||||
const token = value.key.split(':')[1];
|
||||
return token;
|
||||
}
|
||||
}
|
||||
throw new ForbiddenException('Authorization failed - No valid login keys');
|
||||
}
|
||||
|
||||
async callExistingSelectToken(
|
||||
userUUID: string,
|
||||
uuid: string,
|
||||
): Promise<string | null> {
|
||||
const mergedKey = this.mergeSelectUser(userUUID, uuid);
|
||||
if (!mergedKey.includes('*')) {
|
||||
throw new ForbiddenException(
|
||||
'Authorization failed - No valid select keys',
|
||||
);
|
||||
}
|
||||
const keys = await this.scanKeys(mergedKey, this.SELECT_TOKEN);
|
||||
if (keys.length === 0) {
|
||||
return null;
|
||||
}
|
||||
for (const key of keys) {
|
||||
const value = await this.cacheService.get(key);
|
||||
if (value) {
|
||||
this.cacheService.set_with_ttl(value.key, value.value, 60 * 30);
|
||||
const token = value.key.split(':')[2];
|
||||
return token;
|
||||
}
|
||||
}
|
||||
throw new ForbiddenException('Authorization failed - No valid select keys');
|
||||
}
|
||||
|
||||
async deleteLoginFromRedis(req: Request): Promise<any> {
|
||||
const mergedKey = this.mergeLoginKey(req);
|
||||
return this.cacheService.delete(mergedKey);
|
||||
}
|
||||
|
||||
async deleteSelectFromRedis(req: Request): Promise<any> {
|
||||
const mergedKey = this.mergeSelectKey(req);
|
||||
return this.cacheService.delete(mergedKey);
|
||||
}
|
||||
|
||||
async renewTtlLoginFromRedis(req: Request): Promise<any> {
|
||||
const loginToken = await this.getLoginFromRedis(req);
|
||||
if (!loginToken) { throw new ForbiddenException('Login token not found') }
|
||||
return this.cacheService.set_with_ttl(loginToken.key, loginToken.value, 60 * 30);
|
||||
}
|
||||
|
||||
async renewTtlSelectFromRedis(req: Request): Promise<any> {
|
||||
const selectToken = await this.getSelectFromRedis(req);
|
||||
if (!selectToken) { throw new ForbiddenException('Select token not found') }
|
||||
return this.cacheService.set_with_ttl(selectToken.key, selectToken.value, 60 * 30);
|
||||
}
|
||||
|
||||
async setLoginToRedis(token: AuthToken, userUUID: string): Promise<any> {
|
||||
const accessToken = this.generateAccessToken();
|
||||
const redisKey = `${this.AUTH_TOKEN}:${accessToken}:${accessToken}:${userUUID}:${userUUID}`;
|
||||
await this.cacheService.set_with_ttl(redisKey, token, 60 * 30);
|
||||
return accessToken;
|
||||
}
|
||||
|
||||
async setSelectToRedis(
|
||||
accessToken: string,
|
||||
token: TokenDictInterface,
|
||||
userUUID: string,
|
||||
livingUUID: string,
|
||||
): Promise<any> {
|
||||
const selectToken = this.generateSelectToken(accessToken, userUUID);
|
||||
const redisKey = `${this.SELECT_TOKEN}:${accessToken}:${selectToken}:${userUUID}:${livingUUID}`;
|
||||
await this.cacheService.set_with_ttl(redisKey, token, 60 * 30);
|
||||
return selectToken;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
export interface interfaceMenu {
|
||||
key: string;
|
||||
icon: string;
|
||||
text: { tr: string, en: string };
|
||||
page: string | null;
|
||||
token: string | null;
|
||||
color: string;
|
||||
subs: interfaceMenu[] | null;
|
||||
}
|
||||
|
||||
export interface interfaceMapper {
|
||||
[key: string]: string;
|
||||
}
|
||||
|
||||
export interface interfaceMenus {
|
||||
Menu: interfaceMenu[];
|
||||
Mapper: interfaceMapper;
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue