feat(environment): add environment CRUD module and wire into auth login
This commit is contained in:
+1
-5
@@ -7,8 +7,4 @@ APP_VERSION=1.0.0
|
||||
KEYS_DIR=keys
|
||||
|
||||
# SQLite database path
|
||||
DB_PATH=data/sessions.db
|
||||
|
||||
# Login automation targets
|
||||
ID_LOGIN_URL=https://id-liquio-diia-stg.kitsoft.ua/
|
||||
CABINET_URL=https://cabinet-liquio-diia-stg.kitsoft.ua/messages
|
||||
DB_PATH=data/sessions.db
|
||||
+4
-1
@@ -5,6 +5,8 @@ import { HealthController } from './health/health.controller';
|
||||
import { AuthModule } from './auth/auth.module';
|
||||
import { BrowserModule } from './browser/browser.module';
|
||||
import { SessionEntity } from './session/session.entity';
|
||||
import { EnvironmentEntity } from './environment/environment.entity';
|
||||
import { EnvironmentModule } from './environment/environment.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -17,12 +19,13 @@ import { SessionEntity } from './session/session.entity';
|
||||
useFactory: (config: ConfigService) => ({
|
||||
type: 'better-sqlite3',
|
||||
database: config.get<string>('DB_PATH', 'data/sessions.db'),
|
||||
entities: [SessionEntity],
|
||||
entities: [SessionEntity, EnvironmentEntity],
|
||||
synchronize: true,
|
||||
}),
|
||||
}),
|
||||
AuthModule,
|
||||
BrowserModule,
|
||||
EnvironmentModule,
|
||||
],
|
||||
controllers: [HealthController],
|
||||
})
|
||||
|
||||
@@ -21,6 +21,6 @@ export class AuthController {
|
||||
@ApiResponse({ status: 400, description: 'Key not found or invalid' })
|
||||
@ApiResponse({ status: 500, description: 'Automation failed' })
|
||||
login(@Body() dto: LoginDto): Promise<{ token: string; sessionName: string }> {
|
||||
return this.authService.login(dto.key, dto.sessionName);
|
||||
return this.authService.login(dto.key, dto.environmentName, dto.sessionName);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,9 +2,10 @@ import { Module } from '@nestjs/common';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { AuthService } from './auth.service';
|
||||
import { SessionModule } from '../session/session.module';
|
||||
import { EnvironmentModule } from '../environment/environment.module';
|
||||
|
||||
@Module({
|
||||
imports: [SessionModule],
|
||||
imports: [SessionModule, EnvironmentModule],
|
||||
controllers: [AuthController],
|
||||
providers: [AuthService],
|
||||
exports: [AuthService],
|
||||
|
||||
+16
-15
@@ -3,6 +3,7 @@ import {
|
||||
BadRequestException,
|
||||
InternalServerErrorException,
|
||||
Logger,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { chromium } from 'playwright';
|
||||
@@ -10,6 +11,7 @@ import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import * as crypto from 'crypto';
|
||||
import { SessionService } from '../session/session.service';
|
||||
import { EnvironmentService } from '../environment/environment.service';
|
||||
|
||||
interface KeyDescriptor {
|
||||
keyFile: string;
|
||||
@@ -20,24 +22,15 @@ interface KeyDescriptor {
|
||||
export class AuthService {
|
||||
private readonly logger = new Logger(AuthService.name);
|
||||
private readonly keysDir: string;
|
||||
private readonly loginUrl: string;
|
||||
private readonly cabinetUrl: string;
|
||||
|
||||
constructor(
|
||||
private readonly config: ConfigService,
|
||||
private readonly sessionService: SessionService,
|
||||
private readonly environmentService: EnvironmentService,
|
||||
) {
|
||||
this.keysDir = path.resolve(
|
||||
this.config.get<string>('KEYS_DIR', 'keys'),
|
||||
);
|
||||
this.loginUrl = this.config.get<string>(
|
||||
'ID_LOGIN_URL',
|
||||
'https://id-liquio-diia-stg.kitsoft.ua/',
|
||||
);
|
||||
this.cabinetUrl = this.config.get<string>(
|
||||
'CABINET_URL',
|
||||
'https://cabinet-liquio-diia-stg.kitsoft.ua/messages',
|
||||
);
|
||||
}
|
||||
|
||||
listKeys(): string[] {
|
||||
@@ -47,9 +40,17 @@ export class AuthService {
|
||||
.map(f => path.basename(f, '.json'));
|
||||
}
|
||||
|
||||
async login(keyId: string, sessionName?: string): Promise<{ token: string; sessionName: string }> {
|
||||
async login(keyId: string, environmentName: string, sessionName?: string): Promise<{ token: string; sessionName: string }> {
|
||||
const resolvedSession = sessionName ?? crypto.randomUUID();
|
||||
|
||||
const env = await this.environmentService.findAll().then(all => all.find(e => e.name === environmentName));
|
||||
if (!env) throw new NotFoundException(`Environment "${environmentName}" not found`);
|
||||
|
||||
const loginUrl = env.urls.id_url;
|
||||
const cabinetUrl = env.urls.cabinet_url;
|
||||
if (!loginUrl) throw new BadRequestException(`Environment "${environmentName}" is missing id_url`);
|
||||
if (!cabinetUrl) throw new BadRequestException(`Environment "${environmentName}" is missing cabinet_url`);
|
||||
|
||||
const keyJsonPath = path.join(this.keysDir, `${keyId}.json`);
|
||||
|
||||
if (!fs.existsSync(keyJsonPath)) {
|
||||
@@ -73,8 +74,8 @@ export class AuthService {
|
||||
const context = await browser.newContext();
|
||||
const page = await context.newPage();
|
||||
|
||||
this.logger.log(`Navigating to ${this.loginUrl}`);
|
||||
await page.goto(this.loginUrl, { waitUntil: 'networkidle' });
|
||||
this.logger.log(`Navigating to ${loginUrl}`);
|
||||
await page.goto(loginUrl, { waitUntil: 'networkidle' });
|
||||
|
||||
// Click "Файловий ключ" button
|
||||
await page.getByText('Файловий ключ').click();
|
||||
@@ -92,8 +93,8 @@ export class AuthService {
|
||||
await page.locator('#id-app-login-file-key-sign-button').click();
|
||||
|
||||
// Wait until redirected to cabinet
|
||||
this.logger.log(`Waiting for redirect to ${this.cabinetUrl}`);
|
||||
await page.waitForURL(this.cabinetUrl, { timeout: 30000 });
|
||||
this.logger.log(`Waiting for redirect to ${cabinetUrl}`);
|
||||
await page.waitForURL(cabinetUrl, { timeout: 30000 });
|
||||
|
||||
// Extract token from localStorage
|
||||
const token = await page.evaluate(() => localStorage.getItem('token'));
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsOptional, IsString } from 'class-validator';
|
||||
import { IsNotEmpty, IsOptional, IsString } from 'class-validator';
|
||||
|
||||
export class LoginDto {
|
||||
@ApiProperty({
|
||||
@@ -7,8 +7,17 @@ export class LoginDto {
|
||||
example: '3273334361',
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
key: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'Environment name to resolve login/cabinet URLs from',
|
||||
example: 'liquio-diia-stg',
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
environmentName: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: 'Session name to store credentials under. Auto-generated UUID if omitted.',
|
||||
example: 'my-test-session',
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsObject, IsString } from 'class-validator';
|
||||
import { EnvironmentUrls } from '../environment.entity';
|
||||
|
||||
export class CreateEnvironmentDto {
|
||||
@ApiProperty({ example: 'liquio-diia-stg' })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
name: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'Map of URL identifiers to URL strings',
|
||||
example: {
|
||||
id_url: 'https://id-liquio-diia-stg.kitsoft.ua/',
|
||||
cabinet_url: 'https://cabinet-liquio-diia-stg.kitsoft.ua/',
|
||||
admin_url: 'https://admin-liquio-diia-stg.kitsoft.ua/',
|
||||
},
|
||||
})
|
||||
@IsObject()
|
||||
urls: EnvironmentUrls;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { PartialType } from '@nestjs/swagger';
|
||||
import { CreateEnvironmentDto } from './create-environment.dto';
|
||||
|
||||
export class UpdateEnvironmentDto extends PartialType(CreateEnvironmentDto) {}
|
||||
@@ -0,0 +1,61 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
HttpCode,
|
||||
Param,
|
||||
ParseIntPipe,
|
||||
Patch,
|
||||
Post,
|
||||
} from '@nestjs/common';
|
||||
import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
|
||||
import { EnvironmentService } from './environment.service';
|
||||
import { CreateEnvironmentDto } from './dto/create-environment.dto';
|
||||
import { UpdateEnvironmentDto } from './dto/update-environment.dto';
|
||||
|
||||
@ApiTags('environments')
|
||||
@Controller('environments')
|
||||
export class EnvironmentController {
|
||||
constructor(private readonly environmentService: EnvironmentService) {}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: 'Create a new environment' })
|
||||
@ApiResponse({ status: 201, description: 'Environment created' })
|
||||
@ApiResponse({ status: 409, description: 'Environment name already exists' })
|
||||
create(@Body() dto: CreateEnvironmentDto) {
|
||||
return this.environmentService.create(dto);
|
||||
}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: 'List all environments' })
|
||||
@ApiResponse({ status: 200, description: 'Array of environments' })
|
||||
findAll() {
|
||||
return this.environmentService.findAll();
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
@ApiOperation({ summary: 'Get environment by ID' })
|
||||
@ApiResponse({ status: 200, description: 'Environment record' })
|
||||
@ApiResponse({ status: 404, description: 'Environment not found' })
|
||||
findOne(@Param('id', ParseIntPipe) id: number) {
|
||||
return this.environmentService.findOne(id);
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
@ApiOperation({ summary: 'Update an environment' })
|
||||
@ApiResponse({ status: 200, description: 'Environment updated' })
|
||||
@ApiResponse({ status: 404, description: 'Environment not found' })
|
||||
update(@Param('id', ParseIntPipe) id: number, @Body() dto: UpdateEnvironmentDto) {
|
||||
return this.environmentService.update(id, dto);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@HttpCode(204)
|
||||
@ApiOperation({ summary: 'Delete an environment' })
|
||||
@ApiResponse({ status: 204, description: 'Environment deleted' })
|
||||
@ApiResponse({ status: 404, description: 'Environment not found' })
|
||||
remove(@Param('id', ParseIntPipe) id: number) {
|
||||
return this.environmentService.remove(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import {
|
||||
Entity,
|
||||
PrimaryGeneratedColumn,
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
|
||||
export interface EnvironmentUrls {
|
||||
id_url?: string;
|
||||
cabinet_url?: string;
|
||||
admin_url?: string;
|
||||
[key: string]: string | undefined;
|
||||
}
|
||||
|
||||
@Entity('environments')
|
||||
export class EnvironmentEntity {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Column({ unique: true })
|
||||
name: string;
|
||||
|
||||
@Column('simple-json')
|
||||
urls: EnvironmentUrls;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn()
|
||||
updatedAt: Date;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { EnvironmentEntity } from './environment.entity';
|
||||
import { EnvironmentService } from './environment.service';
|
||||
import { EnvironmentController } from './environment.controller';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([EnvironmentEntity])],
|
||||
controllers: [EnvironmentController],
|
||||
providers: [EnvironmentService],
|
||||
exports: [EnvironmentService],
|
||||
})
|
||||
export class EnvironmentModule {}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { ConflictException, Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { EnvironmentEntity } from './environment.entity';
|
||||
import { CreateEnvironmentDto } from './dto/create-environment.dto';
|
||||
import { UpdateEnvironmentDto } from './dto/update-environment.dto';
|
||||
|
||||
@Injectable()
|
||||
export class EnvironmentService {
|
||||
constructor(
|
||||
@InjectRepository(EnvironmentEntity)
|
||||
private readonly repo: Repository<EnvironmentEntity>,
|
||||
) {}
|
||||
|
||||
async create(dto: CreateEnvironmentDto): Promise<EnvironmentEntity> {
|
||||
const existing = await this.repo.findOneBy({ name: dto.name });
|
||||
if (existing) {
|
||||
throw new ConflictException(`Environment "${dto.name}" already exists`);
|
||||
}
|
||||
return this.repo.save(this.repo.create(dto));
|
||||
}
|
||||
|
||||
findAll(): Promise<EnvironmentEntity[]> {
|
||||
return this.repo.find();
|
||||
}
|
||||
|
||||
async findOne(id: number): Promise<EnvironmentEntity> {
|
||||
const env = await this.repo.findOneBy({ id });
|
||||
if (!env) throw new NotFoundException(`Environment ${id} not found`);
|
||||
return env;
|
||||
}
|
||||
|
||||
async update(id: number, dto: UpdateEnvironmentDto): Promise<EnvironmentEntity> {
|
||||
const env = await this.findOne(id);
|
||||
Object.assign(env, dto);
|
||||
return this.repo.save(env);
|
||||
}
|
||||
|
||||
async remove(id: number): Promise<void> {
|
||||
await this.findOne(id);
|
||||
await this.repo.delete(id);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user