From 71394b4a470aaaf51e875a1e01cae6106ed0cc43 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EB=B0=95=EB=8B=A4=ED=98=84=20=28Dahyeon=20Park=29?= Date: Sun, 12 Apr 2026 11:00:00 +0900 Subject: [PATCH] feat(api): add community and user resources --- .../modules/community/community.controller.ts | 107 ++++++++++ .../src/modules/community/community.module.ts | 10 + .../modules/community/community.service.ts | 196 ++++++++++++++++++ .../community/dto/create-community.dto.ts | 47 +++++ .../community/dto/transfer-ownership.dto.ts | 6 + .../src/modules/user/dto/me-response.dto.ts | 22 ++ .../user/dto/refresh-riot-account.dto.ts | 13 ++ apps/api/src/modules/user/user.controller.ts | 120 +++++++++++ apps/api/src/modules/user/user.module.ts | 9 + 9 files changed, 530 insertions(+) create mode 100644 apps/api/src/modules/community/community.controller.ts create mode 100644 apps/api/src/modules/community/community.module.ts create mode 100644 apps/api/src/modules/community/community.service.ts create mode 100644 apps/api/src/modules/community/dto/create-community.dto.ts create mode 100644 apps/api/src/modules/community/dto/transfer-ownership.dto.ts create mode 100644 apps/api/src/modules/user/dto/me-response.dto.ts create mode 100644 apps/api/src/modules/user/dto/refresh-riot-account.dto.ts create mode 100644 apps/api/src/modules/user/user.controller.ts create mode 100644 apps/api/src/modules/user/user.module.ts diff --git a/apps/api/src/modules/community/community.controller.ts b/apps/api/src/modules/community/community.controller.ts new file mode 100644 index 00000000..be0f5327 --- /dev/null +++ b/apps/api/src/modules/community/community.controller.ts @@ -0,0 +1,107 @@ +import { + Body, + Controller, + BadRequestException, + ForbiddenException, + Get, + Param, + Patch, + Post, + Req, + UseGuards, +} from '@nestjs/common'; +import type { Request } from 'express'; +import mongoose from 'mongoose'; +import { AllowPublicAccess } from '../auth/allow-public-access.decorator'; +import { CurrentUser } from '../auth/current-user.decorator'; +import { Roles } from '../auth/roles.decorator'; +import { RolesGuard } from '../auth/roles.guard'; +import { ParseObjectIdPipe } from '../common/parse-object-id.pipe'; +import type { UserDocument } from '../global/database/schema'; +import '../auth/auth-request'; +import { CommunityService } from './community.service'; +import { CreateCommunityDto } from './dto/create-community.dto'; +import { TransferOwnershipDto } from './dto/transfer-ownership.dto'; + +@Controller('communities') +export class CommunityController { + constructor(private readonly communityService: CommunityService) {} + + @Post() + @AllowPublicAccess() + public async createCommunity( + @Body() body: CreateCommunityDto, + @Req() req: Request, + ) { + if (!req.identity && !body.owner) { + throw new BadRequestException( + 'owner is required when not authenticated.', + ); + } + return this.communityService.createCommunityWithOwner({ + ...body, + identityId: req.identity?._id, + }); + } + + @Get(':communityId') + @AllowPublicAccess() + public async getCommunity( + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + ) { + return this.communityService.getById(communityId); + } + + @Patch(':communityId/members/:userId/promote') + @Roles('owner') + @UseGuards(RolesGuard) + public async promoteToAdmin( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('userId', ParseObjectIdPipe) targetUserId: mongoose.Types.ObjectId, + ) { + this.assertOwnerOfCommunity(currentUser, communityId); + return this.communityService.promoteToAdmin({ communityId, targetUserId }); + } + + @Patch(':communityId/members/:userId/demote') + @Roles('owner') + @UseGuards(RolesGuard) + public async demoteToMember( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('userId', ParseObjectIdPipe) targetUserId: mongoose.Types.ObjectId, + ) { + this.assertOwnerOfCommunity(currentUser, communityId); + return this.communityService.demoteToMember({ communityId, targetUserId }); + } + + @Patch(':communityId/transfer-ownership') + @Roles('owner') + @UseGuards(RolesGuard) + public async transferOwnership( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Body() body: TransferOwnershipDto, + ) { + this.assertOwnerOfCommunity(currentUser, communityId); + return this.communityService.transferOwnership({ + communityId, + currentOwnerUserId: currentUser._id, + newOwnerUserId: new mongoose.Types.ObjectId(body.newOwnerUserId), + }); + } + + private assertOwnerOfCommunity( + user: UserDocument, + communityId: mongoose.Types.ObjectId, + ): void { + if (!user.communityId.equals(communityId)) { + throw new ForbiddenException('You do not belong to this community.'); + } + } +} diff --git a/apps/api/src/modules/community/community.module.ts b/apps/api/src/modules/community/community.module.ts new file mode 100644 index 00000000..24e60fd7 --- /dev/null +++ b/apps/api/src/modules/community/community.module.ts @@ -0,0 +1,10 @@ +import { Module } from '@nestjs/common'; +import { CommunityController } from './community.controller'; +import { CommunityService } from './community.service'; + +@Module({ + controllers: [CommunityController], + providers: [CommunityService], + exports: [CommunityService], +}) +export class CommunityModule {} diff --git a/apps/api/src/modules/community/community.service.ts b/apps/api/src/modules/community/community.service.ts new file mode 100644 index 00000000..44a52e42 --- /dev/null +++ b/apps/api/src/modules/community/community.service.ts @@ -0,0 +1,196 @@ +import { + BadRequestException, + Injectable, + InternalServerErrorException, + NotFoundException, +} from '@nestjs/common'; +import mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import { + CommunityDocument, + UserDocument, +} from '../global/database/schema'; + +export interface CreateCommunityInput { + name: string; + description?: string; + identityId?: mongoose.Types.ObjectId; + owner?: { + kakaoTalkId?: string; + kakaoTalkNickname?: string; + discordId?: string; + discordNickname?: string; + }; +} + +@Injectable() +export class CommunityService { + constructor(private readonly connectionService: ConnectionService) {} + + public async getById( + communityId: mongoose.Types.ObjectId, + ): Promise { + const CommunityModel = await this.connectionService.getModel('community'); + const community = await CommunityModel.findById(communityId).exec(); + if (!community) throw new NotFoundException('Community not found.'); + return community; + } + + public async createCommunityWithOwner(input: CreateCommunityInput): Promise<{ + community: CommunityDocument; + owner: UserDocument; + }> { + const CommunityModel = await this.connectionService.getModel('community'); + const UserModel = await this.connectionService.getModel('user'); + + const communityId = new mongoose.Types.ObjectId(); + const ownerUserId = new mongoose.Types.ObjectId(); + + const session = await this.connectionService.createSession(); + if (!session) { + throw new InternalServerErrorException('Failed to start DB session.'); + } + + try { + session.startTransaction(); + + const [community] = await CommunityModel.create( + [ + { + _id: communityId, + name: input.name, + description: input.description ?? '', + ownerUserId, + }, + ], + { session }, + ); + + const [owner] = await UserModel.create( + [ + { + _id: ownerUserId, + communityId, + identityId: input.identityId, + role: 'owner', + kakaoTalkId: input.owner?.kakaoTalkId, + kakaoTalkNickname: input.owner?.kakaoTalkNickname, + discordId: input.owner?.discordId, + discordNickname: input.owner?.discordNickname, + }, + ], + { session }, + ); + + await session.commitTransaction(); + return { community, owner }; + } catch (err) { + await session.abortTransaction(); + throw err; + } finally { + await session.endSession(); + } + } + + public async promoteToAdmin(params: { + communityId: mongoose.Types.ObjectId; + targetUserId: mongoose.Types.ObjectId; + }): Promise { + return this.changeNonOwnerRole({ ...params, nextRole: 'admin' }); + } + + public async demoteToMember(params: { + communityId: mongoose.Types.ObjectId; + targetUserId: mongoose.Types.ObjectId; + }): Promise { + return this.changeNonOwnerRole({ ...params, nextRole: 'member' }); + } + + public async transferOwnership(params: { + communityId: mongoose.Types.ObjectId; + currentOwnerUserId: mongoose.Types.ObjectId; + newOwnerUserId: mongoose.Types.ObjectId; + }): Promise<{ + community: CommunityDocument; + previousOwner: UserDocument; + newOwner: UserDocument; + }> { + if (params.currentOwnerUserId.equals(params.newOwnerUserId)) { + throw new BadRequestException('New owner is already the current owner.'); + } + + const CommunityModel = await this.connectionService.getModel('community'); + const UserModel = await this.connectionService.getModel('user'); + + const session = await this.connectionService.createSession(); + if (!session) { + throw new InternalServerErrorException('Failed to start DB session.'); + } + + try { + session.startTransaction(); + + const community = await CommunityModel.findById( + params.communityId, + ).session(session); + if (!community) throw new NotFoundException('Community not found.'); + if (!community.ownerUserId.equals(params.currentOwnerUserId)) { + throw new BadRequestException('Acting user is not the current owner.'); + } + + const [previousOwner, newOwner] = await Promise.all([ + UserModel.findById(params.currentOwnerUserId).session(session), + UserModel.findById(params.newOwnerUserId).session(session), + ]); + if (!previousOwner) + throw new NotFoundException('Previous owner user not found.'); + if (!newOwner) throw new NotFoundException('New owner user not found.'); + if (!newOwner.communityId.equals(params.communityId)) { + throw new BadRequestException( + 'New owner does not belong to this community.', + ); + } + + community.ownerUserId = newOwner._id; + previousOwner.role = 'admin'; + newOwner.role = 'owner'; + + await Promise.all([ + community.save({ session }), + previousOwner.save({ session }), + newOwner.save({ session }), + ]); + + await session.commitTransaction(); + return { community, previousOwner, newOwner }; + } catch (err) { + await session.abortTransaction(); + throw err; + } finally { + await session.endSession(); + } + } + + private async changeNonOwnerRole(params: { + communityId: mongoose.Types.ObjectId; + targetUserId: mongoose.Types.ObjectId; + nextRole: 'admin' | 'member'; + }): Promise { + const UserModel = await this.connectionService.getModel('user'); + const user = await UserModel.findById(params.targetUserId); + if (!user) throw new NotFoundException('Target user not found.'); + if (!user.communityId.equals(params.communityId)) { + throw new BadRequestException( + 'Target user does not belong to this community.', + ); + } + if (user.role === 'owner') { + throw new BadRequestException( + 'Owner role must be changed via transferOwnership.', + ); + } + user.role = params.nextRole; + await user.save(); + return user; + } +} diff --git a/apps/api/src/modules/community/dto/create-community.dto.ts b/apps/api/src/modules/community/dto/create-community.dto.ts new file mode 100644 index 00000000..e175b7fb --- /dev/null +++ b/apps/api/src/modules/community/dto/create-community.dto.ts @@ -0,0 +1,47 @@ +import { Type } from 'class-transformer'; +import { + IsOptional, + IsString, + MaxLength, + MinLength, + ValidateNested, +} from 'class-validator'; + +class CreateCommunityOwnerDto { + @IsOptional() + @IsString() + @MaxLength(64) + kakaoTalkId?: string; + + @IsOptional() + @IsString() + @MaxLength(64) + kakaoTalkNickname?: string; + + @IsOptional() + @IsString() + @MaxLength(64) + discordId?: string; + + @IsOptional() + @IsString() + @MaxLength(64) + discordNickname?: string; +} + +export class CreateCommunityDto { + @IsString() + @MinLength(1) + @MaxLength(64) + name!: string; + + @IsOptional() + @IsString() + @MaxLength(1024) + description?: string; + + @IsOptional() + @ValidateNested() + @Type(() => CreateCommunityOwnerDto) + owner?: CreateCommunityOwnerDto; +} diff --git a/apps/api/src/modules/community/dto/transfer-ownership.dto.ts b/apps/api/src/modules/community/dto/transfer-ownership.dto.ts new file mode 100644 index 00000000..90d472ec --- /dev/null +++ b/apps/api/src/modules/community/dto/transfer-ownership.dto.ts @@ -0,0 +1,6 @@ +import { IsMongoId } from 'class-validator'; + +export class TransferOwnershipDto { + @IsMongoId() + newOwnerUserId!: string; +} diff --git a/apps/api/src/modules/user/dto/me-response.dto.ts b/apps/api/src/modules/user/dto/me-response.dto.ts new file mode 100644 index 00000000..0bd09bbf --- /dev/null +++ b/apps/api/src/modules/user/dto/me-response.dto.ts @@ -0,0 +1,22 @@ +import type { + CommunityDocument, + UserDocument, +} from '../../global/database/schema'; + +export interface MeIdentityDto { + id: string; + entraOid: string; + tenantId?: string; + email?: string; + displayName?: string; +} + +export interface MeMembershipDto { + user: UserDocument; + community: CommunityDocument | null; +} + +export interface MeResponseDto { + identity: MeIdentityDto | null; + memberships: MeMembershipDto[]; +} diff --git a/apps/api/src/modules/user/dto/refresh-riot-account.dto.ts b/apps/api/src/modules/user/dto/refresh-riot-account.dto.ts new file mode 100644 index 00000000..02d9fd2d --- /dev/null +++ b/apps/api/src/modules/user/dto/refresh-riot-account.dto.ts @@ -0,0 +1,13 @@ +import { IsBoolean, IsIn, IsOptional } from 'class-validator'; +import { RIOT_PLATFORM_ROUTES } from '../../riot/riot.types'; +import type { RiotPlatformRoute } from '../../riot/riot.types'; + +export class RefreshRiotAccountDto { + @IsOptional() + @IsBoolean() + force?: boolean; + + @IsOptional() + @IsIn(RIOT_PLATFORM_ROUTES) + platform?: RiotPlatformRoute; +} diff --git a/apps/api/src/modules/user/user.controller.ts b/apps/api/src/modules/user/user.controller.ts new file mode 100644 index 00000000..9b614966 --- /dev/null +++ b/apps/api/src/modules/user/user.controller.ts @@ -0,0 +1,120 @@ +import { + Body, + Controller, + ForbiddenException, + Get, + Param, + Post, + Req, + UnauthorizedException, +} from '@nestjs/common'; +import type { Request } from 'express'; +import { AllowPublicAccess } from '../auth/allow-public-access.decorator'; +import '../auth/auth-request'; +import { CurrentUser } from '../auth/current-user.decorator'; +import { ConnectionService } from '../global/database/connection.service'; +import type { + IdentityDocument, + UserDocument, +} from '../global/database/schema'; +import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service'; +import type { MeResponseDto } from './dto/me-response.dto'; +import { RefreshRiotAccountDto } from './dto/refresh-riot-account.dto'; + +@Controller('me') +export class UserController { + constructor( + private readonly enrichment: RiotAccountEnrichmentService, + private readonly connectionService: ConnectionService, + ) {} + + @Get() + @AllowPublicAccess() + public async me(@Req() req: Request): Promise { + if (req.identity) { + return this.resolveMeByIdentity(req.identity); + } + if (req.user) { + return { + identity: null, + memberships: [ + { + user: req.user, + community: await this.findCommunity(req.user), + }, + ], + }; + } + return { identity: null, memberships: [] }; + } + + @Post('riot-accounts/:puuid/refresh') + public async refreshRiotAccount( + @CurrentUser() user: UserDocument | undefined, + @Req() req: Request, + @Param('puuid') puuid: string, + @Body() body: RefreshRiotAccountDto, + ) { + const resolvedUser = + user ?? (req.identity ? await this.findUserByIdentityAndPuuid(req.identity, puuid) : null); + if (!resolvedUser) { + throw new UnauthorizedException('Authentication required.'); + } + if (!resolvedUser.riotAccounts.some((account) => account.puuid === puuid)) { + throw new ForbiddenException('Riot account does not belong to user.'); + } + + return this.enrichment.enrichRiotAccount({ + userId: resolvedUser._id, + puuid, + options: { + force: body.force === true, + platform: body.platform, + }, + }); + } + + private async resolveMeByIdentity( + identity: IdentityDocument, + ): Promise { + const UserModel = await this.connectionService.getModel('user'); + const CommunityModel = await this.connectionService.getModel('community'); + const users = await UserModel.find({ identityId: identity._id }).exec(); + const communities = await CommunityModel.find({ + _id: { $in: users.map((user) => user.communityId) }, + }).exec(); + const communityById = new Map( + communities.map((community) => [community._id.toString(), community]), + ); + + return { + identity: { + id: identity._id.toString(), + entraOid: identity.entraOid, + tenantId: identity.tenantId, + email: identity.email, + displayName: identity.displayName, + }, + memberships: users.map((user) => ({ + user, + community: communityById.get(user.communityId.toString()) ?? null, + })), + }; + } + + private async findCommunity(user: UserDocument) { + const CommunityModel = await this.connectionService.getModel('community'); + return CommunityModel.findById(user.communityId).exec(); + } + + private async findUserByIdentityAndPuuid( + identity: IdentityDocument, + puuid: string, + ): Promise { + const UserModel = await this.connectionService.getModel('user'); + return UserModel.findOne({ + identityId: identity._id, + 'riotAccounts.puuid': puuid, + }).exec(); + } +} diff --git a/apps/api/src/modules/user/user.module.ts b/apps/api/src/modules/user/user.module.ts new file mode 100644 index 00000000..66ca9ce0 --- /dev/null +++ b/apps/api/src/modules/user/user.module.ts @@ -0,0 +1,9 @@ +import { Module } from '@nestjs/common'; +import { RiotModule } from '../riot/riot.module'; +import { UserController } from './user.controller'; + +@Module({ + imports: [RiotModule], + controllers: [UserController], +}) +export class UserModule {}