.
This commit is contained in:
1 parent
90a7cf6a7e
commit
905bbcc6dd
9 files changed
+122
-67
No files matched your search
@@ -9,21 +9,18 @@ import {
|
|||||||
Param,
|
Param,
|
||||||
Post,
|
Post,
|
||||||
UseGuards,
|
UseGuards,
|
||||||
UseInterceptors,
|
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
|
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
|
||||||
import { CurrentUser } from '../auth/current-user.decorator';
|
import { CurrentUser } from '../auth/current-user.decorator';
|
||||||
import { Roles } from '../auth/roles.decorator';
|
import { Roles } from '../auth/roles.decorator';
|
||||||
import { RolesGuard } from '../auth/roles.guard';
|
import { RolesGuard } from '../auth/roles.guard';
|
||||||
import { UserResolverInterceptor } from '../auth/user-resolver.interceptor';
|
|
||||||
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
|
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
|
||||||
import type { UserDocument } from '../global/database/schema';
|
import type { UserDocument } from '../global/database/schema';
|
||||||
import { AuctionService } from './auction.service';
|
import { AuctionService } from './auction.service';
|
||||||
import { PlaceBidDto, SoldDto, StartAuctionDto } from './dto/auction.dto';
|
import { PlaceBidDto, SoldDto, StartAuctionDto } from './dto/auction.dto';
|
||||||
|
|
||||||
@Controller('communities/:communityId/matches/:matchId/auction')
|
@Controller('communities/:communityId/matches/:matchId/auction')
|
||||||
@UseInterceptors(UserResolverInterceptor)
|
|
||||||
export class AuctionController {
|
export class AuctionController {
|
||||||
constructor(private readonly auctionService: AuctionService) {}
|
constructor(private readonly auctionService: AuctionService) {}
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import { IdentityService } from './identity.service';
|
|||||||
import { JwtAuthGuard } from './jwt.guard';
|
import { JwtAuthGuard } from './jwt.guard';
|
||||||
import { JwtService } from './jwt.service';
|
import { JwtService } from './jwt.service';
|
||||||
import { RolesGuard } from './roles.guard';
|
import { RolesGuard } from './roles.guard';
|
||||||
import { UserResolverInterceptor } from './user-resolver.interceptor';
|
import { UserResolverGuard } from './user-resolver.guard';
|
||||||
|
|
||||||
@Global()
|
@Global()
|
||||||
@Module({
|
@Module({
|
||||||
@@ -16,17 +16,18 @@ import { UserResolverInterceptor } from './user-resolver.interceptor';
|
|||||||
IdentityService,
|
IdentityService,
|
||||||
JwtAuthGuard,
|
JwtAuthGuard,
|
||||||
IdentityResolverGuard,
|
IdentityResolverGuard,
|
||||||
|
UserResolverGuard,
|
||||||
RolesGuard,
|
RolesGuard,
|
||||||
UserResolverInterceptor,
|
|
||||||
{ provide: APP_GUARD, useClass: JwtAuthGuard },
|
{ provide: APP_GUARD, useClass: JwtAuthGuard },
|
||||||
{ provide: APP_GUARD, useClass: IdentityResolverGuard },
|
{ provide: APP_GUARD, useClass: IdentityResolverGuard },
|
||||||
|
{ provide: APP_GUARD, useClass: UserResolverGuard },
|
||||||
],
|
],
|
||||||
exports: [
|
exports: [
|
||||||
AuthService,
|
AuthService,
|
||||||
JwtService,
|
JwtService,
|
||||||
IdentityService,
|
IdentityService,
|
||||||
|
UserResolverGuard,
|
||||||
RolesGuard,
|
RolesGuard,
|
||||||
UserResolverInterceptor,
|
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
export class AuthModule {}
|
export class AuthModule {}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import { ExecutionContext } from '@nestjs/common';
|
||||||
|
import mongoose from 'mongoose';
|
||||||
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
|
import { IdentityDocument, UserDocument } from '../global/database/schema';
|
||||||
|
import { UserResolverGuard } from './user-resolver.guard';
|
||||||
|
import './auth-request';
|
||||||
|
|
||||||
|
function createContext(request: Record<string, unknown>): ExecutionContext {
|
||||||
|
return {
|
||||||
|
switchToHttp: () => ({
|
||||||
|
getRequest: () => request,
|
||||||
|
}),
|
||||||
|
} as ExecutionContext;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('UserResolverGuard', () => {
|
||||||
|
it('resolves the community membership before role guards run', async () => {
|
||||||
|
const communityId = new mongoose.Types.ObjectId();
|
||||||
|
const identityId = new mongoose.Types.ObjectId();
|
||||||
|
const user = { _id: new mongoose.Types.ObjectId() } as UserDocument;
|
||||||
|
const findOne = jest.fn().mockReturnValue({
|
||||||
|
exec: jest.fn().mockResolvedValue(user),
|
||||||
|
});
|
||||||
|
const connectionService = {
|
||||||
|
getModel: jest.fn().mockResolvedValue({ findOne }),
|
||||||
|
} as unknown as ConnectionService;
|
||||||
|
const request = {
|
||||||
|
params: { communityId: communityId.toString() },
|
||||||
|
identity: { _id: identityId } as IdentityDocument,
|
||||||
|
};
|
||||||
|
const guard = new UserResolverGuard(connectionService);
|
||||||
|
|
||||||
|
await expect(guard.canActivate(createContext(request))).resolves.toBe(true);
|
||||||
|
|
||||||
|
expect(findOne).toHaveBeenCalledWith({
|
||||||
|
communityId,
|
||||||
|
identityId,
|
||||||
|
});
|
||||||
|
expect(request.user).toBe(user);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('skips lookup when there is no resolved identity', async () => {
|
||||||
|
const connectionService = {
|
||||||
|
getModel: jest.fn(),
|
||||||
|
} as unknown as ConnectionService;
|
||||||
|
const request = {
|
||||||
|
params: { communityId: new mongoose.Types.ObjectId().toString() },
|
||||||
|
};
|
||||||
|
const guard = new UserResolverGuard(connectionService);
|
||||||
|
|
||||||
|
await expect(guard.canActivate(createContext(request))).resolves.toBe(true);
|
||||||
|
|
||||||
|
expect(connectionService.getModel).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
|
||||||
|
import type { Request } from 'express';
|
||||||
|
import mongoose from 'mongoose';
|
||||||
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
|
import './auth-request';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class UserResolverGuard implements CanActivate {
|
||||||
|
constructor(private readonly connectionService: ConnectionService) {}
|
||||||
|
|
||||||
|
public async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||||
|
const request = context.switchToHttp().getRequest<Request>();
|
||||||
|
const communityId = request.params?.communityId;
|
||||||
|
|
||||||
|
if (
|
||||||
|
request.user ||
|
||||||
|
!request.identity ||
|
||||||
|
typeof communityId !== 'string' ||
|
||||||
|
!mongoose.isValidObjectId(communityId)
|
||||||
|
) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const UserModel = await this.connectionService.getModel('user');
|
||||||
|
const user = await UserModel.findOne({
|
||||||
|
communityId: new mongoose.Types.ObjectId(communityId),
|
||||||
|
identityId: request.identity._id,
|
||||||
|
}).exec();
|
||||||
|
|
||||||
|
if (user) request.user = user;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
import {
|
|
||||||
CallHandler,
|
|
||||||
ExecutionContext,
|
|
||||||
Injectable,
|
|
||||||
NestInterceptor,
|
|
||||||
} from '@nestjs/common';
|
|
||||||
import type { Request } from 'express';
|
|
||||||
import mongoose from 'mongoose';
|
|
||||||
import { Observable } from 'rxjs';
|
|
||||||
import { ConnectionService } from '../global/database/connection.service';
|
|
||||||
import './auth-request';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class UserResolverInterceptor implements NestInterceptor {
|
|
||||||
constructor(private readonly connectionService: ConnectionService) {}
|
|
||||||
|
|
||||||
public async intercept(
|
|
||||||
context: ExecutionContext,
|
|
||||||
next: CallHandler,
|
|
||||||
): Promise<Observable<unknown>> {
|
|
||||||
const request = context.switchToHttp().getRequest<Request>();
|
|
||||||
const communityId = request.params?.communityId;
|
|
||||||
|
|
||||||
if (
|
|
||||||
!request.user &&
|
|
||||||
request.identity &&
|
|
||||||
typeof communityId === 'string' &&
|
|
||||||
mongoose.isValidObjectId(communityId)
|
|
||||||
) {
|
|
||||||
const UserModel = await this.connectionService.getModel('user');
|
|
||||||
const user = await UserModel.findOne({
|
|
||||||
communityId: new mongoose.Types.ObjectId(communityId),
|
|
||||||
identityId: request.identity._id,
|
|
||||||
}).exec();
|
|
||||||
if (user) request.user = user;
|
|
||||||
}
|
|
||||||
|
|
||||||
return next.handle();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -9,7 +9,6 @@ import {
|
|||||||
Post,
|
Post,
|
||||||
Req,
|
Req,
|
||||||
UseGuards,
|
UseGuards,
|
||||||
UseInterceptors,
|
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import type { Request } from 'express';
|
import type { Request } from 'express';
|
||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
@@ -17,7 +16,6 @@ import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
|
|||||||
import { CurrentUser } from '../auth/current-user.decorator';
|
import { CurrentUser } from '../auth/current-user.decorator';
|
||||||
import { Roles } from '../auth/roles.decorator';
|
import { Roles } from '../auth/roles.decorator';
|
||||||
import { RolesGuard } from '../auth/roles.guard';
|
import { RolesGuard } from '../auth/roles.guard';
|
||||||
import { UserResolverInterceptor } from '../auth/user-resolver.interceptor';
|
|
||||||
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
|
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
|
||||||
import type { UserDocument } from '../global/database/schema';
|
import type { UserDocument } from '../global/database/schema';
|
||||||
import '../auth/auth-request';
|
import '../auth/auth-request';
|
||||||
@@ -26,7 +24,6 @@ import { CreateCommunityDto } from './dto/create-community.dto';
|
|||||||
import { TransferOwnershipDto } from './dto/transfer-ownership.dto';
|
import { TransferOwnershipDto } from './dto/transfer-ownership.dto';
|
||||||
|
|
||||||
@Controller('communities')
|
@Controller('communities')
|
||||||
@UseInterceptors(UserResolverInterceptor)
|
|
||||||
export class CommunityController {
|
export class CommunityController {
|
||||||
constructor(private readonly communityService: CommunityService) {}
|
constructor(private readonly communityService: CommunityService) {}
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import mongoose from 'mongoose';
|
|||||||
import { NatsService } from '../global/nats/nats.service';
|
import { NatsService } from '../global/nats/nats.service';
|
||||||
import { SecretService } from '../global/secret/secret.service';
|
import { SecretService } from '../global/secret/secret.service';
|
||||||
import { CommandParseError, parseCommand } from './parsers/command.parser';
|
import { CommandParseError, parseCommand } from './parsers/command.parser';
|
||||||
import { DakaoInboundEvent, DakaoSegment } from './dakao.types';
|
import { DakaoInboundEvent, DakaoLong, DakaoSegment } from './dakao.types';
|
||||||
import { DakaoPublisher } from './dakao.publisher';
|
import { DakaoPublisher } from './dakao.publisher';
|
||||||
import { DakaoUserError, DakaoUserService } from './dakao-user.service';
|
import { DakaoUserError, DakaoUserService } from './dakao-user.service';
|
||||||
import { IdempotencyCache } from './idempotency.cache';
|
import { IdempotencyCache } from './idempotency.cache';
|
||||||
@@ -81,16 +81,17 @@ export class DakaoSubscriber implements OnModuleInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let segments: DakaoSegment[];
|
let segments: DakaoSegment[];
|
||||||
|
const senderNickname = this.resolveSenderNickname(event);
|
||||||
|
const correlationId = this.serializeDakaoLong(event.origin.chatLog.logId);
|
||||||
try {
|
try {
|
||||||
const command = parseCommand(event.origin.chatLog.message);
|
const command = parseCommand(event.origin.chatLog.message);
|
||||||
const correlationId = String(event.origin.chatLog.logId ?? '');
|
|
||||||
|
|
||||||
switch (command.kind) {
|
switch (command.kind) {
|
||||||
case 'match-list':
|
case 'match-list':
|
||||||
segments = await this.matchListHandler.handle({
|
segments = await this.matchListHandler.handle({
|
||||||
communityId,
|
communityId,
|
||||||
senderUserId: event.userId,
|
senderUserId: event.userId,
|
||||||
senderNickname: event.nickname,
|
senderNickname,
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
case 'match-join':
|
case 'match-join':
|
||||||
@@ -98,7 +99,7 @@ export class DakaoSubscriber implements OnModuleInit {
|
|||||||
communityId,
|
communityId,
|
||||||
matchId: command.matchId,
|
matchId: command.matchId,
|
||||||
senderUserId: event.userId,
|
senderUserId: event.userId,
|
||||||
senderNickname: event.nickname,
|
senderNickname,
|
||||||
gameName: command.gameName,
|
gameName: command.gameName,
|
||||||
tagLine: command.tagLine,
|
tagLine: command.tagLine,
|
||||||
positions: command.positions.positions,
|
positions: command.positions.positions,
|
||||||
@@ -117,8 +118,8 @@ export class DakaoSubscriber implements OnModuleInit {
|
|||||||
if (err.code === 'not_a_command') return;
|
if (err.code === 'not_a_command') return;
|
||||||
await this.publisher.sendMessage({
|
await this.publisher.sendMessage({
|
||||||
chatroomId: event.chatroomId,
|
chatroomId: event.chatroomId,
|
||||||
segments: this.parseErrorReply(event, err),
|
segments: this.parseErrorReply(event, senderNickname, err),
|
||||||
correlationId: String(event.origin.chatLog.logId ?? ''),
|
correlationId,
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -145,24 +146,38 @@ export class DakaoSubscriber implements OnModuleInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private deriveLogIdKey(event: DakaoInboundEvent): string | null {
|
private deriveLogIdKey(event: DakaoInboundEvent): string | null {
|
||||||
const logId = event.origin.chatLog.logId;
|
const serialized = this.serializeDakaoLong(event.origin.chatLog.logId);
|
||||||
if (typeof logId === 'string') return `${event.projectId}:${logId}`;
|
return serialized ? `${event.projectId}:${serialized}` : null;
|
||||||
if (logId && typeof logId === 'object') {
|
}
|
||||||
const { high, low, unsigned } = logId;
|
|
||||||
return `${event.projectId}:${high ?? ''}|${low ?? ''}|${unsigned ?? ''}`;
|
private serializeDakaoLong(value: DakaoLong | string | undefined): string {
|
||||||
}
|
if (typeof value === 'string') return value;
|
||||||
return null;
|
if (!value || typeof value !== 'object') return '';
|
||||||
|
const high = BigInt(value.high ?? 0);
|
||||||
|
const low = BigInt.asUintN(32, BigInt(value.low ?? 0));
|
||||||
|
const combined = (high << 32n) | low;
|
||||||
|
return value.unsigned
|
||||||
|
? BigInt.asUintN(64, combined).toString()
|
||||||
|
: BigInt.asIntN(64, combined).toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private resolveSenderNickname(event: DakaoInboundEvent): string {
|
||||||
|
const primary = event.nickname?.trim();
|
||||||
|
if (primary) return primary;
|
||||||
|
const fallback = event.origin.authorNickname?.trim();
|
||||||
|
return fallback ?? '';
|
||||||
}
|
}
|
||||||
|
|
||||||
private parseErrorReply(
|
private parseErrorReply(
|
||||||
event: DakaoInboundEvent,
|
event: DakaoInboundEvent,
|
||||||
|
senderNickname: string,
|
||||||
err: CommandParseError,
|
err: CommandParseError,
|
||||||
): DakaoSegment[] {
|
): DakaoSegment[] {
|
||||||
const head: DakaoSegment[] = [
|
const head: DakaoSegment[] = [
|
||||||
{
|
{
|
||||||
kind: 'mention',
|
kind: 'mention',
|
||||||
userId: event.userId,
|
userId: event.userId,
|
||||||
displayText: event.nickname,
|
displayText: senderNickname,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
const text = ((): string => {
|
const text = ((): string => {
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ describe('MatchJoinHandler', () => {
|
|||||||
expect.objectContaining({ kind: 'mention', userId: 'kakao-user-1' }),
|
expect.objectContaining({ kind: 'mention', userId: 'kakao-user-1' }),
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
kind: 'text',
|
kind: 'text',
|
||||||
text: expect.stringContaining('유효하지 않은 매치 ID'),
|
text: expect.stringContaining('유효하지 않은 내전 ID'),
|
||||||
}),
|
}),
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -11,14 +11,12 @@ import {
|
|||||||
Post,
|
Post,
|
||||||
Query,
|
Query,
|
||||||
UseGuards,
|
UseGuards,
|
||||||
UseInterceptors,
|
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
|
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
|
||||||
import { CurrentUser } from '../auth/current-user.decorator';
|
import { CurrentUser } from '../auth/current-user.decorator';
|
||||||
import { Roles } from '../auth/roles.decorator';
|
import { Roles } from '../auth/roles.decorator';
|
||||||
import { RolesGuard } from '../auth/roles.guard';
|
import { RolesGuard } from '../auth/roles.guard';
|
||||||
import { UserResolverInterceptor } from '../auth/user-resolver.interceptor';
|
|
||||||
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
|
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
|
||||||
import type {
|
import type {
|
||||||
MatchDocument,
|
MatchDocument,
|
||||||
@@ -33,7 +31,6 @@ import {
|
|||||||
import { MatchService } from './match.service';
|
import { MatchService } from './match.service';
|
||||||
|
|
||||||
@Controller('communities/:communityId/matches')
|
@Controller('communities/:communityId/matches')
|
||||||
@UseInterceptors(UserResolverInterceptor)
|
|
||||||
export class MatchController {
|
export class MatchController {
|
||||||
constructor(private readonly matchService: MatchService) {}
|
constructor(private readonly matchService: MatchService) {}
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user