Compare commits

...

10 Commits

154 changed files with 24062 additions and 2 deletions

7
.dockerignore Normal file
View File

@@ -0,0 +1,7 @@
node_modules
dist
.dockerignore
.git
.env
npm-debug.log
api_env.env

56
.gitignore vendored Normal file
View File

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

View File

@@ -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

56
ServicesApi/.gitignore vendored Normal file
View File

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

4
ServicesApi/.prettierrc Normal file
View File

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

28
ServicesApi/Dockerfile Normal file
View File

@@ -0,0 +1,28 @@
# --- 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
USER node
EXPOSE 3000
CMD ["node", "dist/main.js"]

View File

@@ -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

98
ServicesApi/README.md Normal file
View File

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

42
ServicesApi/api_env.env Normal file
View File

@@ -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

View File

@@ -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'
},
},
);

View File

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

11906
ServicesApi/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

84
ServicesApi/package.json Normal file
View File

@@ -0,0 +1,84 @@
{
"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",
"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.16.5",
"@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"
}
}

View File

@@ -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

View File

@@ -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();
});
});

View File

@@ -0,0 +1,42 @@
import {
Controller,
Get,
Post,
Put,
Delete,
Param,
Body,
HttpCode,
UseGuards,
} from '@nestjs/common';
import { AccountsService } from './accounts.service';
import { AuthControlGuard, EndpointControlGuard } from '../middleware/access-control.guard';
@Controller('accounts')
export class AccountsController {
constructor(private accountsService: AccountsService) {}
@Post('filter')
@HttpCode(200)
@UseGuards(AuthControlGuard, EndpointControlGuard)
async filterAccounts(@Body() query: any) {
const result = await this.accountsService.findWithPagination(query);
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 };
}
}

View File

@@ -0,0 +1,22 @@
import { Module } from '@nestjs/common';
import { AccountsService } from './accounts.service';
import { AccountsController } from './accounts.controller';
import { PrismaModule } from '@/prisma/prisma.module';
import { CacheService } from '../cache.service';
import { UtilsModule } from '../utils/utils.module';
import {
AuthControlGuard,
EndpointControlGuard,
} from '@/src/middleware/access-control.guard';
@Module({
imports: [PrismaModule, UtilsModule],
providers: [
AccountsService,
CacheService,
AuthControlGuard,
EndpointControlGuard,
],
controllers: [AccountsController],
})
export class AccountsModule {}

View File

@@ -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();
});
});

View File

@@ -0,0 +1,42 @@
import { Injectable } from '@nestjs/common';
import { PrismaService } from '@/src/prisma.service';
import { Prisma, account_records } from '@prisma/client';
import { CacheService } from '../cache.service';
import { PaginationHelper, PaginationInfo } from '../utils/pagination-helper';
@Injectable()
export class AccountsService {
constructor(
private prisma: PrismaService,
private cacheService: CacheService,
private paginationHelper: PaginationHelper,
) {}
async findAll(filter: any): Promise<Partial<account_records>[]> {
return this.prisma.account_records.findMany({
where: { ...filter },
});
}
async findDynamic(
query: Prisma.account_recordsFindManyArgs,
): Promise<{ totalCount: number; result: Partial<account_records>[] }> {
const totalCount = await this.prisma.account_records.count({
where: query.where,
});
const result = await this.prisma.account_records.findMany(query);
return { totalCount, result };
}
async findWithPagination(
query: any & { page?: number; pageSize?: number },
): Promise<{ data: any[]; pagination: PaginationInfo }> {
return this.paginationHelper.paginate(this.prisma.account_records, query);
}
async findOne(uuid: string): Promise<Partial<account_records> | null> {
return this.prisma.account_records.findUnique({
where: { uu_id: uuid },
});
}
}

View File

@@ -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
}

View File

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

View File

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

View File

@@ -0,0 +1,52 @@
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 '@liaoliaots/nestjs-redis';
import { CacheService } from './cache.service';
import { LoggerMiddleware } from '@/src/middleware/logger.middleware';
import { DiscoveryModule } from '@nestjs/core';
const redisConfig = {
host: '10.10.2.15',
port: 6379,
password: 'your_strong_password_here',
};
const modulesList = [UsersModule, AccountsModule, AuthModule];
const serviceModuleList = [
PrismaModule,
RedisModule.forRoot({
config: redisConfig,
}),
DiscoveryModule,
];
const controllersList = [AppController];
const providersList = [AppService, CacheService];
const exportsList = [CacheService];
@Module({
imports: [...serviceModuleList, ...modulesList],
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('*');
}
}

View File

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

View File

@@ -0,0 +1,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' };
}
}

View File

@@ -0,0 +1,32 @@
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';
@Module({
imports: [UtilsModule],
controllers: [AuthController],
providers: [
AuthService,
LoginService,
LogoutService,
SelectService,
CreatePasswordService,
ChangePasswordService,
ResetPasswordService,
VerifyOtpService,
DisconnectService,
PrismaService,
],
exports: [AuthService],
})
export class AuthModule {}

View File

@@ -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();
}
}

View File

@@ -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();
});
});

View File

@@ -0,0 +1,8 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class DisconnectService {
async run() {
return { message: 'Disconnect successful' };
}
}

View File

@@ -0,0 +1,13 @@
import { IsOptional, IsString, IsBoolean } from 'class-validator';
export class userLoginValidator {
@IsString()
accessKey: string;
@IsString()
password: string;
@IsBoolean()
@IsOptional()
rememberMe?: boolean;
}

View File

@@ -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();
});
});

View File

@@ -0,0 +1,165 @@
import { Injectable } from '@nestjs/common';
import { userLoginValidator } from '@/src/auth/login/dtoValidator';
import { RedisHandlers } from '@/src/utils/auth/redis_handlers';
import { PasswordHandlers } from '@/src/utils/auth/login_handler';
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;
}
const redisData = AuthTokenSchema.parse({
people: foundPerson,
users: foundUser,
credentials: {
person_uu_id: foundPerson.uu_id,
person_name: foundPerson.firstname,
person_full_name: `${foundPerson.firstname} ${foundPerson.middle_name || ''} | ${foundPerson.birthname || ''} | ${foundPerson.surname}`,
},
selectionList: {
type: foundUser.user_type,
list: selectList,
},
});
const accessToken = await this.redis.setLoginToRedis(
redisData,
foundUser.uu_id,
);
return {
token: accessToken,
message: 'Login successful',
};
}
}
}

View File

@@ -0,0 +1,6 @@
import { IsString } from 'class-validator';
export class userLogoutValidator {
@IsString()
selected_uu_id: string;
}

View File

@@ -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();
});
});

View File

@@ -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;
}
}

View File

@@ -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();
});
});

View File

@@ -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/auth/redis_handlers';
import { PasswordHandlers } from '@/src/utils/auth/login_handler';
@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' };
}
}

View File

@@ -0,0 +1,14 @@
import { IsString } from 'class-validator';
export class userChangePasswordValidator {
@IsString()
oldPassword: string;
@IsString()
password: string;
@IsString()
rePassword: string;
}

View File

@@ -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();
});
});

View File

@@ -0,0 +1,70 @@
import { userCreatePasswordValidator } from './dtoValidator';
import { PrismaService } from '@/src/prisma.service';
import { PasswordHandlers } from '@/src/utils/auth/login_handler';
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' };
}
}

View File

@@ -0,0 +1,12 @@
import { IsString } from 'class-validator';
export class userCreatePasswordValidator {
@IsString()
passwordToken: string;
@IsString()
password: string;
@IsString()
rePassword: string;
}

View File

@@ -0,0 +1,6 @@
import { IsString } from 'class-validator';
export class userResetPasswordValidator {
@IsString()
accessKey: string;
}

View File

@@ -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();
});
});

View File

@@ -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/auth/login_handler';
@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',
};
}
}

View File

@@ -0,0 +1,8 @@
import { IsNumber, Max, Min } from 'class-validator';
export class userVerifyOtpValidator {
@IsNumber()
@Min(6)
@Max(6)
otp: number;
}

View File

@@ -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();
});
});

View File

@@ -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 → frontende gönder, <img src="data:image/png;base64,..."> diye gösterilebilir

View File

@@ -0,0 +1,6 @@
import { IsString } from 'class-validator';
export class userSelectValidator {
@IsString()
uuid: string;
}

View File

@@ -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();
});
});

View File

@@ -0,0 +1,254 @@
import {
Injectable,
BadRequestException,
UnauthorizedException,
NotAcceptableException,
} from '@nestjs/common';
import { userSelectValidator } from '@/src/auth/select/dtoValidator';
import { RedisHandlers } from '@/src/utils/auth/redis_handlers';
import {
EmployeeTokenSchema,
OccupantTokenSchema,
TokenDictInterface,
UserType,
} from '@/src/types/auth/token';
import { PrismaService } from '@/src/prisma.service';
@Injectable()
export class SelectService {
constructor(
private readonly redis: RedisHandlers,
private readonly prisma: PrismaService,
) {}
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: { id: employee.staff_id },
omit: {
id: 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 employeeToken = EmployeeTokenSchema.parse({
company: company,
department: department,
duty: duty,
employee: employee,
staff: staff,
menu: null,
pages: null,
selection: await this.prisma.employees.findFirstOrThrow({
where: { uu_id: dto.uuid },
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,
},
},
},
},
},
},
},
},
},
},
},
}),
functionsRetriever: staff.function_retriever,
kind: UserType.employee,
});
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 },
omit: {
id: true,
person_id: true,
build_parts_id: true,
occupant_type_id: true,
ref_id: true,
replication_id: true,
cryp_uu_id: true,
},
},
);
const occupantType = await this.prisma.occupant_types.findFirstOrThrow({
where: { uu_id: livingSpace.occupant_type_uu_id },
omit: {
id: true,
cryp_uu_id: true,
ref_id: true,
replication_id: true,
},
});
const part = await this.prisma.build_parts.findFirstOrThrow({
where: { uu_id: livingSpace.build_parts_uu_id },
omit: {
id: true,
cryp_uu_id: true,
ref_id: true,
replication_id: true,
},
});
const build = await this.prisma.build.findFirstOrThrow({
where: { uu_id: part.build_uu_id },
omit: {
id: true,
cryp_uu_id: true,
ref_id: true,
replication_id: true,
},
});
const company = await this.prisma.companies.findFirstOrThrow({
where: { uu_id: accessObject.value.users.related_company },
omit: {
id: true,
cryp_uu_id: true,
ref_id: true,
replication_id: true,
},
});
const occupantToken = OccupantTokenSchema.parse({
livingSpace: livingSpace,
occupant: occupantType,
build: build,
part: part,
company: company,
menu: null,
pages: null,
config: null,
caches: null,
selection: await this.prisma.build_living_space.findFirstOrThrow({
where: { uu_id: dto.uuid },
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,
},
},
},
},
},
}),
functionsRetriever: occupantType.function_retriever,
kind: UserType.occupant,
});
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');
}
}
}

View File

@@ -0,0 +1,93 @@
import { Injectable } from '@nestjs/common';
import { RedisService } from '@liaoliaots/nestjs-redis';
import Redis from 'ioredis';
@Injectable()
export class CacheService {
private client: Redis;
constructor(private readonly redisService: RedisService) {
this.client = this.redisService.getOrThrow();
}
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);
if (deleted === 0) {
return false;
}
return 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;
}
}

12
ServicesApi/src/main.ts Normal file
View File

@@ -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();

View File

@@ -0,0 +1,34 @@
import {
CanActivate,
ExecutionContext,
Injectable,
ForbiddenException,
} from '@nestjs/common';
import { RedisHandlers } from '@/src/utils/auth/redis_handlers';
@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);
console.log('AuthControlGuard', accessToken);
return true;
}
}
@Injectable()
export class EndpointControlGuard implements CanActivate {
constructor(private cacheService: RedisHandlers) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const req = context.switchToHttp().getRequest();
// const selectToken = this.cacheService.mergeSelectKey(req);
// const method = req.method;
// const path = req.route?.path;
const accessObject = await this.cacheService.getSelectFromRedis(req);
console.log('EndpointControlGuard', accessObject);
return true;
}
}

View File

@@ -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();
}
}

View File

@@ -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();
}
}

View File

@@ -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,
};

View File

@@ -0,0 +1,269 @@
import { 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({
person_uu_id: z.string(),
person_name: z.string(),
full_name: 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({
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(),
selection: z.record(z.string(), z.unknown()).nullable(),
functionsRetriever: z.string(),
kind: z.literal(UserType.employee),
});
export const OccupantTokenSchema = z.object({
livingSpace: z.object({}),
occupant: z.object({}),
build: z.object({}),
part: z.object({}),
company: z.object({}).optional(),
menu: z.array(z.object({})).nullable(),
pages: z.array(z.string()).nullable(),
selection: z.record(z.string(), z.unknown()).nullable(),
functionsRetriever: z.string(),
kind: z.literal(UserType.occupant),
});
export const TokenDictTypes = z.discriminatedUnion('kind', [
EmployeeTokenSchema,
OccupantTokenSchema,
]);
export type TokenDictInterface = z.infer<typeof TokenDictTypes>;

View File

@@ -0,0 +1,3 @@
export function processUsers(): void {
console.log('Processing users New...');
}

View File

@@ -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();
});
});

View File

@@ -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);
}
}

View File

@@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { UsersService } from './users.service';
import { UsersController } from './users.controller';
import { PrismaModule } from '@/prisma/prisma.module';
import { CacheService } from '../cache.service';
import { UtilsModule } from '../utils/utils.module';
@Module({
imports: [PrismaModule, UtilsModule],
providers: [UsersService, CacheService],
controllers: [UsersController],
exports: [UsersService],
})
export class UsersModule {}

View File

@@ -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 } });
}
}

View File

@@ -0,0 +1,42 @@
import { Injectable } from '@nestjs/common';
import { PrismaService } from '@/src/prisma.service';
import { Prisma, users } from '@prisma/client';
import { CacheService } from '../cache.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 },
});
}
}

View File

@@ -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 };

View File

@@ -0,0 +1,256 @@
import {
TokenDictTypes,
TokenDictInterface,
AuthToken,
AuthTokenSchema,
} from '@/src/types/auth/token';
import { CacheService } from '@/src/cache.service';
import { PasswordHandlers } from './login_handler';
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 };
}
}
}
}
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 };
}
}
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 mergedKey = this.mergeLoginKey(req);
const value = await this.cacheService.get(mergedKey);
return this.cacheService.set_with_ttl(mergedKey, value, 86400);
}
async renewTtlSelectFromRedis(req: Request): Promise<any> {
const mergedKey = this.mergeSelectKey(req);
const value = await this.cacheService.get(mergedKey);
return this.cacheService.set_with_ttl(mergedKey, 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;
}
}

View File

@@ -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;
}

View File

@@ -0,0 +1,58 @@
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,
},
};
}
}

View File

@@ -0,0 +1,18 @@
import { Module } from '@nestjs/common';
import { PaginationHelper } from './pagination-helper';
import { PrismaService } from '@/src/prisma.service';
import { RedisHandlers } from './auth/redis_handlers';
import { PasswordHandlers } from './auth/login_handler';
import { CacheService } from '@/src/cache.service';
@Module({
providers: [
PaginationHelper,
PrismaService,
RedisHandlers,
PasswordHandlers,
CacheService,
],
exports: [PaginationHelper, RedisHandlers, PasswordHandlers, CacheService],
})
export class UtilsModule {}

View File

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

View File

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

View File

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

27
ServicesApi/tsconfig.json Normal file
View File

@@ -0,0 +1,27 @@
{
"compilerOptions": {
"types": ["node"],
"typeRoots": ["./node_modules/@types"],
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2023",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": true,
"forceConsistentCasingInFileNames": true,
"noImplicitAny": false,
"strictBindCallApply": false,
"noFallthroughCasesInSwitch": false,
// "baseUrl": "./src",
"paths": {
"@/*": ["*"]
}
}
}

0
ServicesFrontEnd/a.txt Normal file
View File

41
ServicesFrontEnd/frontend/.gitignore vendored Normal file
View File

@@ -0,0 +1,41 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts

View File

@@ -0,0 +1,36 @@
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.

View File

@@ -0,0 +1,46 @@
{
"Index": {
"title": "Welcome to the Application",
"description": "This is a sample application with internationalization support.",
"navigation": {
"title": "Navigation",
"home": "Home",
"about": "About",
"contact": "Contact"
},
"auth": {
"title": "Authentication",
"login": "Login",
"register": "Register"
}
},
"LocaleLayout": {
"title": "Next.js i18n Application"
},
"Select": {
"title": "Select Your Option",
"description": "Please select one of the following options to continue",
"employee": "Employee",
"staff": "Staff",
"uuid": "UUID",
"department": "Department",
"name": "Name",
"code": "Code",
"company": "Company",
"occupant": "Occupant",
"occupant_code": "Occupant Code",
"building": "Building",
"type": "Type",
"part_details": "Part Details",
"no": "No",
"level": "Level",
"status": "Status",
"livable": "Livable",
"not_livable": "Not Livable",
"selection": "Selection",
"id": "ID",
"processing": "Processing...",
"continue": "Continue",
"select_option": "Select an option to continue"
}
}

View File

@@ -0,0 +1,46 @@
{
"Index": {
"title": "Uygulamaya Hoş Geldiniz",
"description": "Bu, uluslararasılaştırma desteği olan örnek bir uygulamadır.",
"navigation": {
"title": "Navigasyon",
"home": "Ana Sayfa",
"about": "Hakkında",
"contact": "İletişim"
},
"auth": {
"title": "Kimlik Doğrulama",
"login": "Giriş Yap",
"register": "Kayıt Ol"
}
},
"LocaleLayout": {
"title": "Next.js i18n Uygulaması"
},
"Select": {
"title": "Seçeneğinizi Seçin",
"description": "Devam etmek için lütfen aşağıdaki seçeneklerden birini seçin",
"employee": "Çalışan",
"staff": "Personel",
"uuid": "UUID",
"department": "Departman",
"name": "İsim",
"code": "Kod",
"company": "Şirket",
"occupant": "Oturak",
"occupant_code": "Oturak Kodu",
"building": "Bina",
"type": "Tip",
"part_details": "Parça Detayları",
"no": "No",
"level": "Seviye",
"status": "Durum",
"livable": "Yaşanabilir",
"not_livable": "Yaşanamaz",
"selection": "Seçim",
"id": "ID",
"processing": "İşleniyor...",
"continue": "Devam Et",
"select_option": "Devam etmek için bir seçenek seçin"
}
}

View File

@@ -0,0 +1,33 @@
import createMiddleware from "next-intl/middleware";
import { routing } from "@/i18n/routing";
export default createMiddleware({
// A list of all locales that are supported
locales: routing.locales,
// Used when no locale matches
defaultLocale: routing.defaultLocale,
// Locale detection strategies
localeDetection: true,
// Uncomment to use domains for language-specific subdomains
// domains: [
// {
// domain: 'example.com',
// defaultLocale: 'en'
// },
// {
// domain: 'example.fr',
// defaultLocale: 'fr'
// }
// ]
});
export const config = {
// Match all pathnames except for
// - API routes
// - Static files
// - _next internal paths
matcher: ["/((?!api|_next|.*\\..*).*)"],
};

View File

@@ -0,0 +1,8 @@
import createNextIntlPlugin from 'next-intl/plugin';
const withNextIntl = createNextIntlPlugin('./src/i18n/messages.ts');
/** @type {import('next').NextConfig} */
const nextConfig = {};
export default withNextIntl(nextConfig);

View File

@@ -0,0 +1,10 @@
import createNextIntlPlugin from "next-intl/plugin";
const withNextIntl = createNextIntlPlugin("./src/i18n/request.ts");
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
};
export default withNextIntl(nextConfig);

2052
ServicesFrontEnd/frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,32 @@
{
"name": "frontend",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"clsx": "^2.1.1",
"cookies-next": "^6.1.0",
"ioredis": "^5.6.1",
"lucide-react": "^0.533.0",
"next": "15.4.4",
"next-crypto": "^1.0.8",
"next-intl": "^4.3.4",
"react": "19.1.0",
"react-dom": "19.1.0",
"zod": "^4.0.10"
},
"devDependencies": {
"@tailwindcss/postcss": "^4.1.11",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"daisyui": "^5.0.50",
"tailwindcss": "^4.1.11",
"typescript": "^5"
}
}

View File

@@ -0,0 +1,5 @@
const config = {
plugins: ["@tailwindcss/postcss"],
};
export default config;

View File

@@ -0,0 +1 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 391 B

View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

After

Width:  |  Height:  |  Size: 128 B

View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

After

Width:  |  Height:  |  Size: 385 B

View File

@@ -0,0 +1,5 @@
import { ReactNode } from 'react';
export default function AuthLayout({ children }: { children: ReactNode }) {
return <>{children}</>;
}

View File

@@ -0,0 +1,193 @@
'use client';
import Link from 'next/link';
import { useState } from 'react';
import { useTranslations } from 'next-intl';
import { z } from 'zod';
import { Eye, EyeOff, Lock, Mail } from "lucide-react";
import { apiPostFetcher } from '@/lib/fetcher';
import { useRouter } from '@/i18n/routing';
export default function LoginPage() {
const t = useTranslations('Login');
const loginSchema = z.object({
accessKey: z.string().email(t('emailWrong')),
password: z.string().min(6, t('passwordWrong')),
rememberMe: z.boolean().default(false),
});
type LoginInterface = z.infer<typeof loginSchema>;
interface LoginFormErrors {
accessKey?: boolean;
password?: boolean;
rememberMe?: boolean;
}
const [errors, setErrors] = useState<LoginFormErrors>({});
const [showPassword, setShowPassword] = useState(false);
const router = useRouter();
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const form = e.currentTarget;
const formData = new FormData(form);
const loginData: LoginInterface = {
accessKey: formData.get('email') as string,
password: formData.get('password') as string,
rememberMe: formData.get('rememberMe') === 'on'
};
const result = loginSchema.safeParse(loginData);
if (!result.success) {
const fieldErrors: LoginFormErrors = {};
if (result.error.issues.some(issue => issue.path.includes('email'))) {
fieldErrors.accessKey = true;
}
if (result.error.issues.some(issue => issue.path.includes('password'))) {
fieldErrors.password = true;
}
setErrors(fieldErrors);
} else {
setErrors({})
console.log('Form submitted successfully:', loginData);
apiPostFetcher({ url: '/api/auth/login', body: loginData, isNoCache: true }).then((res) => {
if (res.success) {
console.log('Login successful, redirecting to select page');
router.push('/select');
}
}).catch((error) => { console.error('Login failed:', error) });
}
};
return (
<div className="min-h-screen bg-gradient-to-br from-indigo-50 via-white to-cyan-50 flex items-center justify-center p-2 sm:p-4">
<div className="w-full max-w-7xl mx-auto">
<div className="flex flex-col lg:flex-row gap-4 sm:gap-6 md:gap-8 items-center justify-center w-full min-h-[60vh] md:min-h-[70vh] lg:min-h-[80vh]">
{/* Left side - Login form (now takes full width) */}
<div className="card bg-white/90 backdrop-blur-sm shadow-xl border border-indigo-100 rounded-2xl w-full overflow-auto">
<div className="card-body p-4 sm:p-6 md:p-8 lg:p-10 xl:p-12">
<form onSubmit={handleSubmit} className="space-y-4 sm:space-y-5 md:space-y-6 max-w-md mx-auto w-full">
<div className="text-center mb-4 sm:mb-6 md:mb-8">
<h1 className="text-xl sm:text-2xl md:text-3xl font-bold text-gray-800 mb-1 sm:mb-2">{t('welcomeBack')}</h1>
<p className="text-sm sm:text-base text-gray-600">{t('continueJourney')}</p>
</div>
<div className="form-control w-full">
<label className="label p-0 mb-1 sm:mb-1.5 md:mb-2">
<span className="label-text font-medium text-gray-700 text-sm sm:text-base">{t('email')}</span>
</label>
<div className="relative">
<input
type="text"
name="email"
className={`input input-bordered rounded-2xl text-black h-14 bg-white w-full pl-8 sm:pl-10 md:pl-12 py-3 sm:py-4 transition-all
duration-300 border-gray-200 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 ${errors.accessKey ? 'border-red-500 focus:border-red-500 focus:ring-red-200' : ''}`}
placeholder={t('email')}
// style={{
// WebkitBackgroundClip: 'text',
// WebkitTextFillColor: 'black',
// }}
/>
<Mail className="absolute left-2 sm:left-3 md:left-4 top-1/2 transform -translate-y-1/2 w-3 h-3 sm:w-4 sm:h-4 md:w-5 md:h-5 text-gray-400 pointer-events-none z-10" />
</div>
{errors.accessKey && (
<div className="label p-0 pt-1">
<span className="label-text-alt text-red-500 flex items-center gap-1 text-xs sm:text-sm">
<svg className="w-2.5 h-2.5 sm:w-3 sm:h-3 md:w-4 md:h-4" fill="currentColor" viewBox="0 0 20 20">
<path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
</svg>
{t('emailWrong')}
</span>
</div>
)}
</div>
<div className="form-control w-full">
<label className="label p-0 mb-1 sm:mb-1.5 md:mb-2">
<span className="label-text font-medium text-gray-700 text-sm sm:text-base">{t('password')}</span>
</label>
<div className="relative">
<input
type={showPassword ? 'text' : 'password'}
name="password"
className={`input input-bordered rounded-2xl text-black h-14 bg-white w-full pl-8 sm:pl-10 md:pl-12 pr-8 sm:pr-10 md:pr-12 py-3 sm:py-4 transition-all duration-300 border-gray-200 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 ${errors.password ? 'border-red-500 focus:border-red-500 focus:ring-red-200' : ''}`}
placeholder="••••••••"
// style={{
// WebkitBackgroundClip: 'text',
// WebkitTextFillColor: 'black',
// }}
/>
<Lock className="absolute left-2 sm:left-3 md:left-4 top-1/2 transform -translate-y-1/2 w-3 h-3 sm:w-4 sm:h-4 md:w-5 md:h-5 text-gray-400 pointer-events-none z-10" />
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute right-2 sm:right-3 md:right-4 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 transition-colors z-10"
aria-label={showPassword ? "Hide password" : "Show password"}
>
{showPassword ? <EyeOff size={14} className="sm:w-4 sm:h-4 md:w-5 md:h-5" /> : <Eye size={14} className="sm:w-4 sm:h-4 md:w-5 md:h-5" />}
</button>
</div>
{errors.password && (
<div className="label p-0 pt-1">
<span className="label-text-alt text-red-500 flex items-center gap-1 text-xs sm:text-sm">
<svg className="w-2.5 h-2.5 sm:w-3 sm:h-3 md:w-4 md:h-4" fill="currentColor" viewBox="0 0 20 20">
<path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
</svg>
{t('passwordWrong')}
</span>
</div>
)}
</div>
<div className="flex items-center justify-between flex-wrap gap-2">
<label className="label cursor-pointer flex items-center gap-1.5 sm:gap-2 p-0">
<input name="rememberMe" type="checkbox" className="checkbox checkbox-primary checkbox-sm [--chkbg:theme(colors.indigo.500)] [--chkfg:theme(colors.white)] border-indigo-300" />
<span className="label-text text-gray-700 text-xs sm:text-sm">{t('rememberMe')}</span>
</label>
<Link href="/forgot-password" className="text-indigo-600 hover:text-indigo-800 text-xs sm:text-sm font-medium transition-colors">
{t('forgotPassword')}
</Link>
</div>
<button
type="submit"
className="btn bg-indigo-600 hover:bg-indigo-700 border-0 w-full mt-2 sm:mt-3 md:mt-4 py-2 sm:py-2.5 md:py-3 shadow-md hover:shadow-lg transition-all duration-300 text-white font-medium text-sm sm:text-base"
>
{t('login')}
</button>
<div className="divider my-3 sm:my-4 md:my-6 text-gray-400 before:bg-gray-200 after:bg-gray-200 text-xs sm:text-sm">{t('orContinueWith')}</div>
<div className="grid grid-cols gap-3 sm:gap-3 md:gap-6">
<button
type="button"
className="btn btn-outline border-gray-300 text-gray-700 hover:bg-gray-50 py-2 sm:py-2.5 md:py-3 flex items-center justify-center gap-1.5 sm:gap-2 text-xs sm:text-sm"
>
<svg className="w-3 h-3 sm:w-4 sm:h-4 md:w-5 md:h-5" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4" />
<path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853" />
<path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05" />
<path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335" />
</svg>
Google
</button>
<button
type="button"
className="btn btn-outline border-gray-300 text-gray-700 hover:bg-gray-50 py-2 sm:py-2.5 md:py-3 flex items-center justify-center gap-1.5 sm:gap-2 text-xs sm:text-sm"
>
<svg className="w-3 h-3 sm:w-4 sm:h-4 md:w-5 md:h-5" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path d="M24 12.073c0-5.8-4.702-10.5-10.5-10.5s-10.5 4.7-10.5 10.5c0 5.24 3.84 9.584 8.86 10.373v-7.337h-2.666v-3.037h2.666V9.458c0-2.63 1.568-4.085 3.966-4.085 1.15 0 2.35.205 2.35.205v2.584h-1.322c-1.304 0-1.71.81-1.71 1.64v1.97h2.912l-.465 3.036H15.14v7.337c5.02-.788 8.859-5.131 8.859-10.372z" fill="#1877F2" />
</svg>
Facebook
</button>
</div>
</form>
</div>
</div>
</div>
<div className="text-center mt-4 sm:mt-6 md:mt-8 text-gray-500 text-xs sm:text-sm">
<p>{t('copyright')}</p>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,77 @@
"use client";
export default function FromFigma() {
return (
<div className="min-h-screen bg-[#f6f6f6] flex flex-col">
<div className="flex-1 flex justify-center items-center">
<div className="w-full max-w-6xl bg-white rounded-xl shadow-none flex flex-col md:flex-row gap-12 p-12 mx-4">
{/* Left: Recent logins */}
<div className="flex-1 flex flex-col items-start justify-center">
<div className="w-14 h-14 rounded-full bg-gray-300 mb-8" />
<h2 className="text-3xl font-semibold text-gray-800 mb-2">Recent logins</h2>
<div className="text-gray-500 text-sm mb-7">Click your picture or add an account</div>
<div className="flex gap-5">
{/* User card */}
<div className="flex flex-col items-center bg-white rounded-lg border border-gray-200 w-40 shadow-sm">
<div className="relative w-full aspect-square rounded-t-lg overflow-hidden">
<img src="https://images.unsplash.com/photo-1494790108377-be9c29b29330?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=256&q=80" alt="Mika Lee" className="w-full h-full object-cover" />
<button className="absolute top-2 left-2 w-4 h-4 bg-white rounded-full flex items-center justify-center text-xs text-gray-400">×</button>
</div>
<div className="w-full text-center text-sm text-gray-700 py-2 border-t border-gray-200">Mika Lee</div>
</div>
{/* Add account card */}
<div className="flex flex-col items-center bg-white rounded-lg border border-gray-200 w-40 shadow-sm cursor-pointer">
<div className="flex flex-col justify-center items-center w-full aspect-square rounded-t-lg">
<span className="text-3xl text-gray-400"></span>
</div>
<div className="w-full text-center text-sm text-gray-500 py-2 border-t border-gray-200">Add an account</div>
</div>
</div>
</div>
{/* Right: Login form */}
<div className="flex-1 flex flex-col justify-center">
<div className="bg-white rounded-xl border border-gray-200 px-8 py-8 shadow-none">
<form className="space-y-6">
<div>
<label className="block text-sm text-gray-500 mb-1">Your email</label>
<input type="email" className="w-full border border-gray-300 rounded-md px-4 py-3 text-gray-700 bg-white focus:outline-none focus:ring-2 focus:ring-gray-200" />
</div>
<div>
<div className="flex items-center justify-between mb-1">
<label className="block text-sm text-gray-500">Your password</label>
<div className="flex items-center gap-1 text-gray-400 text-sm cursor-pointer select-none">
<svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M13.875 18.825A10.05 10.05 0 0 1 12 19c-5.523 0-10-4.477-10-10 0-1.657.403-3.22 1.125-4.575m1.35-2.025A9.959 9.959 0 0 1 12 3c5.523 0 10 4.477 10 10 0 1.657-.403 3.22-1.125 4.575" /></svg>
Hide
</div>
</div>
<input type="password" className="w-full border border-gray-300 rounded-md px-4 py-3 text-gray-700 bg-white focus:outline-none focus:ring-2 focus:ring-gray-200" />
</div>
<button type="button" className="w-full bg-gray-300 text-gray-500 rounded-full py-3 text-lg font-medium cursor-not-allowed" disabled>Log in</button>
<div className="text-center mt-2">
<a href="#" className="text-gray-600 underline text-sm">Forget your password?</a>
</div>
</form>
</div>
<button className="w-full border border-gray-400 rounded-full py-3 mt-8 text-lg font-medium text-gray-700 bg-white hover:bg-gray-50 transition">Create an account</button>
</div>
</div>
</div>
{/* Footer */}
<footer className="w-full border-t border-gray-200 bg-white py-4 px-8 flex flex-wrap items-center justify-between text-xs text-gray-500 gap-2">
<div className="flex flex-wrap gap-6">
<a href="#" className="hover:underline">Sign up</a>
<a href="#" className="hover:underline">Log in</a>
<a href="#" className="hover:underline">Help Center</a>
<a href="#" className="hover:underline">Terms of Service</a>
<a href="#" className="hover:underline">Privacy Policy</a>
<a href="#" className="hover:underline">About</a>
<a href="#" className="hover:underline">Settings</a>
</div>
<div className="flex items-center gap-2">
English (united States)
<svg className="w-4 h-4 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 9l-7 7-7-7" /></svg>
</div>
</footer>
</div>
);
}

View File

@@ -0,0 +1,18 @@
'use server';
import LocaleSwitcherServer from '@/components/LocaleSwitcherServer';
import LoginPage from './LoginPage';
import { Locale } from 'next-intl';
import { checkAccessOnLoginPage } from '@/app/api/guards';
export default async function PageLogin({ params }: { params: Promise<{ locale: string }> }) {
const { locale } = await params;
await checkAccessOnLoginPage(locale as Locale);
return (
<div>
<div className='absolute top-2 right-2'>
<LocaleSwitcherServer locale={locale} pathname="/login" />
</div>
<LoginPage />
</div>
);
}

View File

@@ -0,0 +1,282 @@
'use client';
import { useEffect, useState } from 'react';
import { useTranslations } from 'next-intl';
import { useRouter } from 'next/navigation';
import { apiGetFetcher } from '@/lib/fetcher';
export default function PageSelect() {
const t = useTranslations('Select');
const router = useRouter();
const [selectionList, setSelectionList] = useState<{ type: string, list: any[] } | null>(null);
const [selectedOption, setSelectedOption] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
const fetchSelectionList = async () => {
setIsLoading(true);
try {
apiGetFetcher({ url: '/api/auth/selections', isNoCache: true }).then((res) => {
if (res.success) {
if (res.data && typeof res.data === 'object' && 'type' in res.data && 'list' in res.data) {
setSelectionList(res.data as { type: string, list: any[] });
}
}
})
} catch (error) {
console.error('Error fetching selection list:', error);
} finally {
setIsLoading(false);
}
};
fetchSelectionList();
}, []);
const handleSelection = (id: string) => { setSelectedOption(id) };
const handleContinue = async () => {
if (!selectedOption) return;
setIsLoading(true);
try {
console.log('Selected option:', selectedOption);
const payload = { uuid: selectedOption };
const response = await fetch('/api/auth/select', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload), });
const result = await response.json();
if (response.ok && result.status === 200) {
console.log('Selection successful, redirecting to venue page');
router.push('/venue');
} else {
console.error('Selection failed:', result.message);
alert(`Selection failed: ${result.message || 'Unknown error'}`);
}
} catch (error) {
console.error('Error submitting selection:', error);
alert('An error occurred while submitting your selection. Please try again.');
} finally { setIsLoading(false) }
};
return (
<div className="min-h-screen bg-gradient-to-br from-indigo-50 via-white to-cyan-50 p-4 sm:p-6 md:p-8">
<div className="max-w-6xl mx-auto w-full h-full flex flex-col">
<div className="text-center mb-8 sm:mb-10 mt-4 sm:mt-6">
<h1 className="text-2xl sm:text-3xl md:text-4xl font-bold text-gray-800 mb-2">{t('title')}</h1>
<p className="text-base sm:text-lg text-gray-600">{t('description')}</p>
</div>
<div className="flex-grow flex flex-col">
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6 flex-grow">
{selectionList?.list?.map((item: any) => {
if (selectionList.type === 'employee') {
const staff = item.staff;
const department = staff?.duties?.departments;
const company = department?.companies;
return (
<div
key={item.uu_id}
className={`rounded-2xl p-6 cursor-pointer transition-all duration-300 flex flex-col justify-between h-full shadow-lg border-2 ${selectedOption === item.uu_id
? 'bg-indigo-100 border-indigo-500 shadow-indigo-200 transform scale-[1.02]'
: 'bg-white/90 border-indigo-100 hover:bg-indigo-50 hover:border-indigo-300 hover:shadow-indigo-100'}`}
onClick={() => handleSelection(item.uu_id)}
>
<div>
<div className="flex items-center mb-4">
<div className="w-12 h-12 rounded-xl bg-gradient-to-r from-indigo-500 to-purple-600 flex items-center justify-center text-white font-bold text-lg mr-4">
{staff?.staff_code?.charAt(0) || 'E'}
</div>
<h3 className="text-lg font-bold text-gray-800">{t('staff')}: {staff?.staff_code || t('employee')}</h3>
</div>
<div className="space-y-2">
<div className="flex items-center">
<svg className="w-4 h-4 text-indigo-500 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
</svg>
<span className="font-medium text-xs text-gray-700">{t('uuid')}:</span>
<span className="ml-2 font-mono text-xs text-gray-600">{item?.uu_id}</span>
</div>
<div className="pt-2 border-t border-gray-100 mt-2">
<div className="flex items-center mb-1">
<svg className="w-4 h-4 text-indigo-500 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"></path>
</svg>
<span className="font-medium text-gray-700">{t('department')}</span>
</div>
<div className="ml-6 mt-1 space-y-1">
<div className="flex items-center">
<span className="text-xs text-gray-500 w-16">{t('name')}:</span>
<span className="text-sm text-gray-600">{department?.department_name || 'N/A'}</span>
</div>
<div className="flex items-center">
<span className="text-xs text-gray-500 w-16">{t('code')}:</span>
<span className="text-sm text-gray-600">{department?.department_code || 'N/A'}</span>
</div>
</div>
</div>
<div className="flex items-center">
<svg className="w-4 h-4 text-indigo-500 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M8 14v3m4-3v3m4-3v3M3 21h18M3 10h18M3 7l9-4 9 4M4 10h16v11H4V10z"></path>
</svg>
<span className="font-medium text-gray-700">{t('company')}:</span>
<span className="ml-2 text-sm text-gray-600">{company?.public_name || company?.formal_name || 'N/A'}</span>
</div>
</div>
</div>
{selectedOption === item.uu_id && (
<div className="mt-4 flex justify-end">
<div className="w-6 h-6 rounded-full bg-indigo-500 flex items-center justify-center">
<svg className="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 13l4 4L19 7"></path>
</svg>
</div>
</div>
)}
</div>
);
}
if (selectionList.type === 'occupant') {
const occupantType = item.occupant_types;
const buildPart = item.build_parts;
const build = buildPart?.build;
const enums = buildPart?.api_enum_dropdown_build_parts_part_type_idToapi_enum_dropdown;
return (
<div
key={item.uu_id}
className={`rounded-2xl p-6 cursor-pointer transition-all duration-300 flex flex-col justify-between h-full shadow-lg border-2 ${selectedOption === item.uu_id
? 'bg-indigo-100 border-indigo-500 shadow-indigo-200 transform scale-[1.02]'
: 'bg-white/90 border-indigo-100 hover:bg-indigo-50 hover:border-indigo-300 hover:shadow-indigo-100'}`}
onClick={() => handleSelection(item.uu_id)}
>
<div>
<div className="flex items-center mb-4">
<div className="w-12 h-12 rounded-xl bg-gradient-to-r from-indigo-500 to-purple-600 flex items-center justify-center text-white font-bold text-lg mr-4">
{occupantType?.occupant_code?.charAt(0) || 'O'}
</div>
<h3 className="text-lg font-bold text-gray-800">{t('occupant_type')}: {occupantType?.occupant_type}</h3>
</div>
<div className="space-y-2">
<div className="flex items-center">
<svg className="w-4 h-4 text-indigo-500 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
</svg>
<span className="font-medium text-xs text-gray-700">{t('uuid')}:</span>
<span className="ml-2 font-mono text-xs text-gray-600">{item?.uu_id}</span>
</div>
<div className="flex items-center">
<svg className="w-4 h-4 text-indigo-500 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
</svg>
<span className="font-medium text-gray-700">{t('occupant_code')}:</span>
<span className="ml-2 font-semibold text-indigo-600">{occupantType?.occupant_code}</span>
</div>
<div className="flex items-center">
<svg className="w-4 h-4 text-indigo-500 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"></path>
</svg>
<span className="font-medium text-gray-700">{t('building')}:</span>
<span className="ml-2 text-gray-600">{build?.build_name || 'Building'}</span>
</div>
<div className="flex items-center">
<svg className="w-4 h-4 text-indigo-500 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M21 13.255A23.931 23.931 0 0112 15c-3.183 0-6.22-.62-9-1.745M16 6V4a2 2 0 00-2-2h-4a2 2 0 00-2 2v2m4 6h.01M5 20h14a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path>
</svg>
<span className="font-medium text-gray-700">{t('type')}:</span>
<span className="ml-2 text-gray-600">{enums?.value}</span>
</div>
<div className="pt-2 border-t border-gray-100 mt-2">
<div className="flex items-center mb-1">
<svg className="w-4 h-4 text-indigo-500 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"></path>
</svg>
<span className="font-medium text-gray-700">{t('part_details')}</span>
</div>
<div className="grid grid-cols-2 gap-2 ml-6 mt-1">
<div className="flex items-center">
<span className="text-xs text-gray-500 w-12">{t('code')}:</span>
<span className="text-sm text-gray-600">{buildPart?.part_code}</span>
</div>
<div className="flex items-center">
<span className="text-xs text-gray-500 w-12">{t('no')}:</span>
<span className="text-sm text-gray-600">{buildPart?.part_no}</span>
</div>
<div className="flex items-center">
<span className="text-xs text-gray-500 w-12">{t('level')}:</span>
<span className="text-sm text-gray-600">{buildPart?.part_level}</span>
</div>
<div className="flex items-center">
<span className="text-xs text-gray-500 w-12">{t('status')}:</span>
<span className={`text-sm font-medium ${buildPart?.human_livable ? 'text-green-600' : 'text-red-600'}`}>
{buildPart?.human_livable ? t('livable') : t('not_livable')}
</span>
</div>
</div>
</div>
</div>
</div>
{selectedOption === item.uu_id && (
<div className="mt-4 flex justify-end">
<div className="w-6 h-6 rounded-full bg-indigo-500 flex items-center justify-center">
<svg className="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 13l4 4L19 7"></path>
</svg>
</div>
</div>
)}
</div>
);
}
return (
<div
key={item.uu_id}
className={`rounded-2xl p-6 cursor-pointer transition-all duration-300 flex flex-col justify-between h-full shadow-lg border-2 ${selectedOption === item.uu_id
? 'bg-indigo-100 border-indigo-500 shadow-indigo-200 transform scale-[1.02]'
: 'bg-white/90 border-indigo-100 hover:bg-indigo-50 hover:border-indigo-300 hover:shadow-indigo-100'}`}
onClick={() => handleSelection(item.uu_id)}
>
<div>
<div className="flex items-center mb-4">
<div className="w-12 h-12 rounded-xl bg-gradient-to-r from-indigo-500 to-purple-600 flex items-center justify-center text-white font-bold text-lg mr-4">
{item.uu_id?.charAt(0) || 'S'}
</div>
<h3 className="text-lg font-bold text-gray-800">{selectionList.type || t('selection')}</h3>
</div>
<p className="text-gray-600 text-sm">{item.uu_id || t('id')}</p>
</div>
{selectedOption === item.uu_id && (
<div className="mt-4 flex justify-end">
<div className="w-6 h-6 rounded-full bg-indigo-500 flex items-center justify-center">
<svg className="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 13l4 4L19 7"></path>
</svg>
</div>
</div>
)}
</div>
);
})}
</div>
<div className="mt-8 sm:mt-10 flex justify-center">
<button
className={`px-8 py-4 rounded-xl font-bold text-white transition-all duration-300 text-lg ${selectedOption
? 'bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700 shadow-lg shadow-indigo-200 hover:shadow-indigo-300 transform hover:scale-105'
: 'bg-gray-400 cursor-not-allowed'}`}
disabled={!selectedOption || isLoading}
onClick={handleContinue}
>
{isLoading ? t('processing') : selectedOption ? t('continue') : t('select_option')}
</button>
</div>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,11 @@
'use server';
import { Locale } from 'next-intl';
import { checkAccess, checkSelectionOnSelectPage } from '@/app/api/guards';
import SelectPageClient from './SelectPage';
export default async function PageSelect({ params }: { params: Promise<{ locale: string }> }) {
const { locale } = await params;
await checkAccess(locale as Locale);
await checkSelectionOnSelectPage(locale as Locale);
return <SelectPageClient />;
}

View File

@@ -0,0 +1,38 @@
import { ReactNode } from 'react';
import { headers } from 'next/headers';
import { removeLocaleFromPath } from '@/lib/helpers';
function removeSubStringFromPath(headersList: Headers) {
const host = headersList.get('host') || '';
const referer = headersList.get('referer') || '';
let currentRoute = '';
if (referer) {
const hostPart = `http://${host}`;
if (referer.startsWith(hostPart)) {
currentRoute = referer.substring(hostPart.length);
} else {
const secureHostPart = `https://${host}`;
if (referer.startsWith(secureHostPart)) {
currentRoute = referer.substring(secureHostPart.length);
}
}
}
return removeLocaleFromPath(currentRoute);
}
function getLocaleFromPath(path: string) {
const locale = path.split('/')[0];
return locale;
}
export default async function ProtectedLayout({
children,
}: {
children: ReactNode,
}) {
const headersList = await headers();
// const locale = getLocaleFromPath(removeSubStringFromPath(headersList));
const removedLocaleRoute = removeSubStringFromPath(headersList);
console.log('Removed locale route:', removedLocaleRoute);
return <>{children}</>;
}

View File

@@ -0,0 +1,3 @@
export default function OfficePage() {
return <div>Office Page</div>;
}

View File

@@ -0,0 +1,3 @@
export default function TrialPage() {
return <div>TrialPage</div>;
}

View File

@@ -0,0 +1,3 @@
export default function VenuePage() {
return <div>Venue Page</div>;
}

View File

@@ -0,0 +1,279 @@
'use client';
import { z } from 'zod';
import { usePathname } from "next/navigation";
import { castTextToTypeGiven, removeLocaleFromPath } from "@/lib/helpers";
import { useState } from 'react';
import { buildCacheKey } from "@/lib/helpers";
import { apiPostFetcher } from '@/lib/fetcher';
const createFormSchema = z.object({
inputSelectName: z.string().min(1, "Name is required"),
inputSelectNumber: z.string().refine((val: string) => !isNaN(Number(val)), {
message: "Number must be a valid number",
}),
});
const selectFormSchema = z.object({
inputSelectName: z.string().min(1, "Name is required"),
inputSelectNumber: z.string().refine((val: string) => !isNaN(Number(val)), {
message: "Number must be a valid number",
}),
});
const searchFormSchema = z.object({
inputSearchName: z.string().min(1, "Name is required"),
inputSearchNumber: z.string().refine((val: string) => !isNaN(Number(val)), {
message: "Number must be a valid number",
}),
});
type SelectFormData = z.infer<typeof selectFormSchema>;
type CreateFormData = z.infer<typeof createFormSchema>;
type SearchFormData = z.infer<typeof searchFormSchema>;
export default function TrialPage() {
const pathname = usePathname();
const cleanPathname = removeLocaleFromPath(pathname || '');
const cacheKeyCreateForm = buildCacheKey({ url: cleanPathname, form: 'trialCreateForm', field: 'trialCreateField' });
const cacheKeySelectForm = buildCacheKey({ url: cleanPathname, form: 'trialSelectForm', field: 'trialSelectField' });
const cacheKeySearchForm = buildCacheKey({ url: cleanPathname, form: 'trialSearchForm', field: 'trialSearchField' });
const [createFormErrors, setCreateFormErrors] = useState<Record<string, string>>({});
const [selectFormErrors, setSelectFormErrors] = useState<Record<string, string>>({});
const [searchFormErrors, setSearchFormErrors] = useState<Record<string, string>>({});
const submitCreateForm = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const form = e.currentTarget;
const formData = new FormData(form);
const formDataObj: Record<string, string> = {};
formData.forEach((value, key) => {
formDataObj[key] = value.toString();
});
const result: z.ZodSafeParseResult<CreateFormData> = createFormSchema.safeParse(formDataObj);
if (result.success) {
console.log('Form validation succeeded:', result.data);
setCreateFormErrors({});
try {
await apiPostFetcher({
url: 'http://localhost:3000/api/cache/delete',
isNoCache: true,
body: { key: cacheKeyCreateForm }
});
console.log('Form data saved to Redis');
} catch (error) {
console.error('Error saving form data:', error);
setCreateFormErrors({
error: "Error saving form data"
});
}
} else {
const errors: Record<string, string> = {};
result.error.issues.forEach((error: any) => {
const path = error.path.join('.');
errors[path] = error.message;
});
console.log('Form validation failed:', errors);
setCreateFormErrors(errors);
}
};
const submitSelectForm = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const form = e.currentTarget;
const formName = form.getAttribute('name');
console.log('Form name:', formName);
const formData = new FormData(form);
const formDataObj: Record<string, string> = {};
formData.forEach((value, key) => {
formDataObj[key] = value.toString();
});
const result: z.ZodSafeParseResult<SelectFormData> = selectFormSchema.safeParse(formDataObj);
if (result.success) {
console.log('Form validation succeeded:', result.data);
setSelectFormErrors({});
try {
await apiPostFetcher({
url: 'http://localhost:3000/api/cache/delete',
isNoCache: true,
body: { key: cacheKeySelectForm }
});
console.log('Form data saved to Redis');
} catch (error) {
console.error('Error saving form data:', error);
}
} else {
const errors: Record<string, string> = {};
result.error.issues.forEach((error: any) => {
const path = error.path.join('.');
errors[path] = error.message;
});
console.log('Form validation failed:', errors);
setSelectFormErrors(errors);
}
};
const submitSearchForm = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const form = e.currentTarget;
const formName = form.getAttribute('name');
console.log('Form name:', formName);
const formData = new FormData(form);
const formDataObj: Record<string, string> = {};
formData.forEach((value, key) => { formDataObj[key] = value.toString() });
const result: z.ZodSafeParseResult<SearchFormData> = searchFormSchema.safeParse(formDataObj);
if (result.success) {
console.log('Form validation succeeded:', result.data);
setSearchFormErrors({});
try {
await apiPostFetcher({
url: 'http://localhost:3000/api/cache/delete',
isNoCache: true,
body: { key: cacheKeySearchForm }
});
console.log('Form data saved to Redis');
} catch (error) {
console.error('Error saving form data:', error);
}
} else {
const errors: Record<string, string> = {};
result.error.issues.forEach((error: any) => {
const path = error.path.join('.');
errors[path] = error.message;
});
console.log('Form validation failed:', errors);
setSearchFormErrors(errors);
}
};
const handleOnBlurSelectForm = (e: React.FocusEvent<HTMLInputElement>) => {
const name = e.target.getAttribute('name');
const fieldType = e.target.getAttribute('type')?.toString()
const value = e.target.value;
if (!value) {
return;
}
const castedValue = castTextToTypeGiven(value, fieldType as string);
apiPostFetcher(
{
url: 'http://localhost:3000/api/cache/renew',
isNoCache: true,
body: { key: cacheKeySelectForm, value: castedValue, field: name }
}
).then((res) => {
console.log('Select form onBlur Response', res);
}).catch((err) => {
console.log('Select form onBlur Error', err);
});
};
const handleOnBlurSearchForm = (e: React.FocusEvent<HTMLInputElement>) => {
const name = e.target.getAttribute('name');
const fieldType = e.target.getAttribute('type')?.toString()
const value = e.target.value;
if (!value) {
return;
}
const castedValue = castTextToTypeGiven(value, fieldType as string);
apiPostFetcher(
{
url: 'http://localhost:3000/api/cache/renew',
isNoCache: true,
body: { key: cacheKeySearchForm, value: castedValue, field: name }
}
).then((res) => {
console.log('Search form onBlur Response', res);
}).catch((err) => {
console.log('Search form onBlur Error', err);
});
};
const handleOnBlurCreateForm = (e: React.FocusEvent<HTMLInputElement>) => {
const name = e.target.getAttribute('name');
const fieldType = e.target.getAttribute('type')?.toString()
const value = e.target.value;
if (!value) {
return;
}
const castedValue = castTextToTypeGiven(value, fieldType as string);
apiPostFetcher(
{
url: 'http://localhost:3000/api/cache/renew',
isNoCache: true,
body: { key: cacheKeyCreateForm, value: castedValue, field: name }
}
).then((res) => {
console.log('Create form onBlur Response', res);
}).catch((err) => {
console.log('Create form onBlur Error', err);
});
};
return <div className="flex flex-col gap-4">
<div className="flex flex-row gap-4">
<h1 className="text-2xl font-bold">Form Keys</h1>
</div>
<div className="flex justify-center gap-4">
<div className="flex flex-col align-center">
<div className="text-lg my-2">CreateForm: {cacheKeyCreateForm}</div>
<div className="text-lg my-2">SelectForm: {cacheKeySelectForm}</div>
<div className="text-lg my-2">SearchForm: {cacheKeySearchForm}</div>
</div>
</div>
{/* Create a simple Form */}
<div className="flex justify-center gap-4">
<form className="flex flex-col w-1/2 gap-2 p-4 border border-gray-300 rounded" name={cacheKeyCreateForm} onSubmit={submitCreateForm}>
<label className="input w-full my-1">
<p className="text-lg w-24">Name</p>
<input className="w-full h-24" onBlur={handleOnBlurCreateForm} name="inputSelectName" type="text" placeholder="Name Input here" />
<span className="badge badge-neutral badge-xs">Optional</span>
</label>
{createFormErrors.inputSelectName && <p className="text-red-500 text-sm">{createFormErrors.inputSelectName}</p>}
<label className="input w-full my-1 mb-2">
<p className="text-lg w-24">Number</p>
<input className="w-full h-24" onBlur={handleOnBlurCreateForm} name="inputSelectNumber" type="decimal" placeholder="Number Input here" />
<span className="badge badge-neutral badge-xs">Optional</span>
</label>
{createFormErrors.inputSelectNumber && <p className="text-red-500 text-sm">{createFormErrors.inputSelectNumber}</p>}
<button className="bg-blue-500 hover:bg-blue-600 text-white py-2 px-4 rounded" type="submit">Submit</button>
</form>
{/* Select a simple Form */}
<form className="flex flex-col gap-2 p-4 border border-gray-300 rounded w-1/2" name={cacheKeySelectForm} onSubmit={submitSelectForm}>
<label className="input w-full my-1 mb-2">
<p className="text-lg w-24">Name</p>
<input className="w-full h-24" onBlur={handleOnBlurSelectForm} name="inputSelectName" type="text" placeholder="Name Input here" />
<span className="badge badge-neutral badge-xs">Optional</span>
</label>
{selectFormErrors.inputSelectName && <p className="text-red-500 text-sm">{selectFormErrors.inputSelectName}</p>}
<label className="input w-full my-1 mb-2">
<p className="text-lg w-24">Number</p>
<input className="w-full h-24" onBlur={handleOnBlurSelectForm} name="inputSelectNumber" type="decimal" placeholder="Number Input here" />
<span className="badge badge-neutral badge-xs">Optional</span>
</label>
{selectFormErrors.inputSelectNumber && <p className="text-red-500 text-sm">{selectFormErrors.inputSelectNumber}</p>}
<button className="bg-blue-500 hover:bg-blue-600 text-white py-2 px-4 rounded" type="submit">Submit</button>
</form>
{/* Search a simple Form */}
<form className="flex flex-col gap-2 p-4 border border-gray-300 rounded w-1/2" name={cacheKeySearchForm} onSubmit={submitSearchForm}>
<label className="input w-full my-1 mb-2">
<p className="text-lg w-24">Name</p>
<input className="w-full h-24" onBlur={handleOnBlurSearchForm} name="inputSearchName" type="text" placeholder="Name Input here" />
<span className="badge badge-neutral badge-xs">Optional</span>
</label>
{searchFormErrors.inputSearchName && <p className="text-red-500 text-sm">{searchFormErrors.inputSearchName}</p>}
<label className="input w-full my-1 mb-2">
<p className="text-lg w-24">Number</p>
<input className="w-full h-24" onBlur={handleOnBlurSearchForm} name="inputSearchNumber" type="decimal" placeholder="Number Input here" />
<span className="badge badge-neutral badge-xs">Optional</span>
</label>
{searchFormErrors.inputSearchNumber && <p className="text-red-500 text-sm">{searchFormErrors.inputSearchNumber}</p>}
<button className="bg-blue-500 hover:bg-blue-600 text-white py-2 px-4 rounded" type="submit">Submit</button>
</form>
</div>
</div>;
}

Some files were not shown because too many files have changed in this diff Show More