Files
wiki-server/src/modules/page/page.service.ts
T
dahyeon bb992167d2 Adds comprehensive page management and temporary access tokens
Introduces the `PageModule` to provide full CRUD capabilities for pages within spaces.

Key features include:
-   API endpoints for creating, retrieving, updating, and soft-deleting pages.
-   Support for hierarchical page structures with validation to prevent circular references.
-   A mechanism to generate and manage temporary access tokens, allowing controlled public access to specific pages or entire spaces.
-   Integration with database repositories and comprehensive Swagger documentation for all new endpoints and DTOs.
-   Ensures proper authorization and validation for all page and token operations.
2025-11-10 15:42:02 +00:00

485 lines
15 KiB
TypeScript

import { Injectable, NotFoundException, BadRequestException, UnauthorizedException } from "@nestjs/common";
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { PageRepository, TokenRepository, SpaceRepository } from "../global/database/repositories";
import { randomBytes } from "crypto";
export class CreatePageDto {
@ApiProperty({
description: '페이지가 속할 스페이스 ID',
example: '550e8400-e29b-41d4-a716-446655440000',
format: 'uuid'
})
spaceId: string;
@ApiPropertyOptional({
description: '부모 페이지 ID (계층 구조)',
example: '550e8400-e29b-41d4-a716-446655440001',
format: 'uuid'
})
parentPageId?: string;
@ApiProperty({
description: '페이지 제목',
example: 'Getting Started',
maxLength: 255
})
title: string;
@ApiPropertyOptional({
description: '페이지 내용 (Markdown 등)',
example: '# Welcome\n\nThis is the content of the page.'
})
content?: string;
@ApiProperty({
description: '현재 사용자 ID (생성자)',
example: '550e8400-e29b-41d4-a716-446655440002',
format: 'uuid'
})
userId: string;
@ApiPropertyOptional({
description: '페이지 정렬 순서',
example: 0,
default: 0
})
sortOrder?: number;
}
export class UpdatePageDto {
@ApiPropertyOptional({
description: '페이지 제목',
example: 'Updated Title',
maxLength: 255
})
title?: string;
@ApiPropertyOptional({
description: '페이지 내용',
example: '# Updated Content\n\nNew content here.'
})
content?: string;
@ApiPropertyOptional({
description: '부모 페이지 ID (null로 설정하면 루트 페이지가 됨)',
example: '550e8400-e29b-41d4-a716-446655440001',
format: 'uuid',
nullable: true
})
parentPageId?: string;
@ApiPropertyOptional({
description: '페이지 정렬 순서',
example: 1
})
sortOrder?: number;
@ApiProperty({
description: '현재 사용자 ID (수정자)',
example: '550e8400-e29b-41d4-a716-446655440002',
format: 'uuid'
})
userId: string;
}
export class GetPageQuery {
@ApiPropertyOptional({
description: '조회할 페이지 ID',
example: '550e8400-e29b-41d4-a716-446655440000',
format: 'uuid'
})
pageId?: string;
@ApiPropertyOptional({
description: '조회할 스페이스 ID (해당 스페이스의 모든 페이지 반환)',
example: '550e8400-e29b-41d4-a716-446655440001',
format: 'uuid'
})
spaceId?: string;
}
export class CreateTemporaryTokenDto {
@ApiPropertyOptional({
description: '접근 권한을 부여할 페이지 ID 배열',
example: ['550e8400-e29b-41d4-a716-446655440000', '550e8400-e29b-41d4-a716-446655440001'],
type: [String],
isArray: true
})
pageIds?: string[];
@ApiPropertyOptional({
description: '접근 권한을 부여할 스페이스 ID 배열',
example: ['550e8400-e29b-41d4-a716-446655440002'],
type: [String],
isArray: true
})
spaceIds?: string[];
@ApiPropertyOptional({
description: '토큰 만료 시간 (시간 단위). 생략하면 만료되지 않음',
example: 24,
minimum: 1
})
expiresInHours?: number;
@ApiPropertyOptional({
description: '토큰 설명',
example: '24시간 공유 링크',
maxLength: 255
})
description?: string;
@ApiProperty({
description: '현재 사용자 ID (토큰 생성자)',
example: '550e8400-e29b-41d4-a716-446655440003',
format: 'uuid'
})
userId: string;
}
export class DeletePageDto {
@ApiProperty({
description: '현재 사용자 ID',
example: '550e8400-e29b-41d4-a716-446655440002',
format: 'uuid'
})
userId: string;
}
export class DeleteTokenDto {
@ApiProperty({
description: '삭제할 토큰 값',
example: 'abc123def456ghi789jkl012mno345pqr678stu901vwx234yz'
})
tokenValue: string;
@ApiProperty({
description: '현재 사용자 ID (토큰 생성자만 삭제 가능)',
example: '550e8400-e29b-41d4-a716-446655440003',
format: 'uuid'
})
userId: string;
}
export class PageResponseDto {
@ApiProperty({ description: '페이지 ID', format: 'uuid' })
pageId: string;
@ApiProperty({ description: '스페이스 ID', format: 'uuid' })
spaceId: string;
@ApiProperty({ description: '부모 페이지 ID', format: 'uuid', nullable: true })
parentPageId: string | null;
@ApiProperty({ description: '정렬 순서' })
sortOrder: number;
@ApiProperty({ description: '페이지 제목' })
title: string;
@ApiProperty({ description: '페이지 내용', nullable: true })
content: string | null;
@ApiProperty({ description: '생성자 사용자 ID', format: 'uuid' })
createdByUserId: string;
@ApiProperty({ description: '수정자 사용자 ID', format: 'uuid' })
updatedByUserId: string;
@ApiProperty({ description: '생성 시간', format: 'date-time' })
createdAt: string;
@ApiProperty({ description: '수정 시간', format: 'date-time' })
updatedAt: string;
@ApiProperty({ description: '삭제 여부' })
isDeleted: boolean;
}
export class TokenInfoDto {
@ApiProperty({ description: '토큰 ID', format: 'uuid' })
tokenId: string;
@ApiProperty({ description: '토큰 값 (실제 사용할 토큰 문자열)' })
tokenValue: string;
@ApiProperty({ description: '토큰 설명', nullable: true })
description: string | null;
@ApiProperty({ description: '만료 시간', format: 'date-time', nullable: true })
expiresAt: string | null;
@ApiProperty({ description: '생성 시간', format: 'date-time' })
createdAt: string;
}
export class TokenPermissionsDto {
@ApiProperty({ description: '권한이 부여된 페이지 ID 목록', type: [String] })
pageIds: string[];
@ApiProperty({ description: '권한이 부여된 스페이스 ID 목록', type: [String] })
spaceIds: string[];
}
export class CreateTokenResponseDto {
@ApiProperty({ description: '생성된 토큰 정보', type: TokenInfoDto })
token: TokenInfoDto;
@ApiProperty({ description: '토큰 권한 정보', type: TokenPermissionsDto })
permissions: TokenPermissionsDto;
}
export class DeleteResponseDto {
@ApiProperty({ description: '응답 메시지' })
message: string;
@ApiProperty({ description: '삭제된 리소스 ID', format: 'uuid' })
pageId?: string;
@ApiProperty({ description: '삭제된 토큰 ID', format: 'uuid' })
tokenId?: string;
}
@Injectable()
export class PageService {
constructor(
private readonly pageRepository: PageRepository,
private readonly tokenRepository: TokenRepository,
private readonly spaceRepository: SpaceRepository,
) {}
/**
* 페이지 생성
*/
async createPage(dto: CreatePageDto) {
// 스페이스 존재 확인
const space = await this.spaceRepository.findById(dto.spaceId);
if (!space) {
throw new NotFoundException(`Space with id '${dto.spaceId}' not found`);
}
// 부모 페이지 존재 확인 (있는 경우)
if (dto.parentPageId) {
const parentPage = await this.pageRepository.findById(dto.parentPageId);
if (!parentPage) {
throw new NotFoundException(`Parent page with id '${dto.parentPageId}' not found`);
}
// 부모 페이지가 같은 스페이스에 있는지 확인
if (parentPage.spaceId !== dto.spaceId) {
throw new BadRequestException('Parent page must be in the same space');
}
}
const page = await this.pageRepository.create({
spaceId: dto.spaceId,
parentPageId: dto.parentPageId,
title: dto.title,
content: dto.content,
createdByUserId: dto.userId,
updatedByUserId: dto.userId,
sortOrder: dto.sortOrder,
});
return page;
}
/**
* 페이지 조회
*/
async getPage(query: GetPageQuery) {
if (query.pageId) {
// 특정 페이지 조회
const page = await this.pageRepository.findById(query.pageId);
if (!page) {
throw new NotFoundException(`Page with id '${query.pageId}' not found`);
}
return page;
} else if (query.spaceId) {
// 스페이스의 모든 페이지 조회
const space = await this.spaceRepository.findById(query.spaceId);
if (!space) {
throw new NotFoundException(`Space with id '${query.spaceId}' not found`);
}
const pages = await this.pageRepository.findBySpaceId(query.spaceId);
return pages;
} else {
throw new BadRequestException('Either pageId or spaceId must be provided');
}
}
/**
* 페이지 업데이트
*/
async updatePage(pageId: string, dto: UpdatePageDto) {
const existingPage = await this.pageRepository.findById(pageId);
if (!existingPage) {
throw new NotFoundException(`Page with id '${pageId}' not found`);
}
// 부모 페이지 변경 시 검증
if (dto.parentPageId !== undefined) {
if (dto.parentPageId === pageId) {
throw new BadRequestException('A page cannot be its own parent');
}
if (dto.parentPageId) {
const parentPage = await this.pageRepository.findById(dto.parentPageId);
if (!parentPage) {
throw new NotFoundException(`Parent page with id '${dto.parentPageId}' not found`);
}
if (parentPage.spaceId !== existingPage.spaceId) {
throw new BadRequestException('Parent page must be in the same space');
}
// 순환 참조 확인
const isDescendant = await this.isPageDescendant(pageId, dto.parentPageId);
if (isDescendant) {
throw new BadRequestException('Cannot move a page to one of its descendants');
}
}
}
const updatedPage = await this.pageRepository.update(pageId, {
title: dto.title,
content: dto.content,
parentPageId: dto.parentPageId,
sortOrder: dto.sortOrder,
updatedByUserId: dto.userId,
});
return updatedPage;
}
/**
* 페이지 삭제 (소프트 삭제)
*/
async deletePage(pageId: string, userId: string) {
const page = await this.pageRepository.findById(pageId);
if (!page) {
throw new NotFoundException(`Page with id '${pageId}' not found`);
}
await this.pageRepository.softDelete(pageId, userId);
return { message: 'Page deleted successfully', pageId };
}
/**
* 임시 액세스 토큰 생성
*/
async createTemporaryAccessToken(dto: CreateTemporaryTokenDto) {
if ((!dto.pageIds || dto.pageIds.length === 0) && (!dto.spaceIds || dto.spaceIds.length === 0)) {
throw new BadRequestException('At least one pageId or spaceId must be provided');
}
// 페이지 존재 확인
if (dto.pageIds && dto.pageIds.length > 0) {
for (const pageId of dto.pageIds) {
const page = await this.pageRepository.findById(pageId);
if (!page) {
throw new NotFoundException(`Page with id '${pageId}' not found`);
}
}
}
// 스페이스 존재 확인
if (dto.spaceIds && dto.spaceIds.length > 0) {
for (const spaceId of dto.spaceIds) {
const space = await this.spaceRepository.findById(spaceId);
if (!space) {
throw new NotFoundException(`Space with id '${spaceId}' not found`);
}
}
}
// 토큰 값 생성 (안전한 랜덤 문자열)
const tokenValue = randomBytes(32).toString('base64url');
// 만료 시간 계산
const expiresAt = dto.expiresInHours
? new Date(Date.now() + dto.expiresInHours * 60 * 60 * 1000).toISOString()
: undefined;
// 토큰 생성
const token = await this.tokenRepository.createToken({
tokenValue,
description: dto.description || 'Temporary access token',
expiresAt,
createdByUserId: dto.userId,
});
// 권한 생성
const permissions: any[] = [];
// 페이지 권한 추가
if (dto.pageIds && dto.pageIds.length > 0) {
for (const pageId of dto.pageIds) {
const permission = await this.tokenRepository.createPermission({
tokenId: token.tokenId,
pageId,
});
permissions.push(permission);
}
}
// 스페이스 권한 추가
if (dto.spaceIds && dto.spaceIds.length > 0) {
for (const spaceId of dto.spaceIds) {
const permission = await this.tokenRepository.createPermission({
tokenId: token.tokenId,
spaceId,
});
permissions.push(permission);
}
}
return {
token: {
tokenId: token.tokenId,
tokenValue: token.tokenValue,
description: token.description,
expiresAt: token.expiresAt,
createdAt: token.createdAt,
},
permissions: {
pageIds: dto.pageIds || [],
spaceIds: dto.spaceIds || [],
},
};
}
/**
* 임시 액세스 토큰 삭제
*/
async deleteTemporaryAccessToken(tokenValue: string, userId: string) {
const token = await this.tokenRepository.findTokenByValue(tokenValue);
if (!token) {
throw new NotFoundException('Token not found');
}
// 토큰 생성자만 삭제 가능
if (token.createdByUserId !== userId) {
throw new UnauthorizedException('You can only delete tokens you created');
}
await this.tokenRepository.deleteToken(token.tokenId);
return { message: 'Token deleted successfully', tokenId: token.tokenId };
}
/**
* 페이지가 다른 페이지의 자손인지 확인 (재귀)
*/
private async isPageDescendant(ancestorId: string, pageId: string): Promise<boolean> {
const page = await this.pageRepository.findById(pageId);
if (!page || !page.parentPageId) {
return false;
}
if (page.parentPageId === ancestorId) {
return true;
}
return await this.isPageDescendant(ancestorId, page.parentPageId);
}
}