.
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,
|
||||
Post,
|
||||
UseGuards,
|
||||
UseInterceptors,
|
||||
} from '@nestjs/common';
|
||||
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 { UserResolverInterceptor } from '../auth/user-resolver.interceptor';
|
||||
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
|
||||
import type { UserDocument } from '../global/database/schema';
|
||||
import { AuctionService } from './auction.service';
|
||||
import { PlaceBidDto, SoldDto, StartAuctionDto } from './dto/auction.dto';
|
||||
|
||||
@Controller('communities/:communityId/matches/:matchId/auction')
|
||||
@UseInterceptors(UserResolverInterceptor)
|
||||
export class AuctionController {
|
||||
constructor(private readonly auctionService: AuctionService) {}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ import { IdentityService } from './identity.service';
|
||||
import { JwtAuthGuard } from './jwt.guard';
|
||||
import { JwtService } from './jwt.service';
|
||||
import { RolesGuard } from './roles.guard';
|
||||
import { UserResolverInterceptor } from './user-resolver.interceptor';
|
||||
import { UserResolverGuard } from './user-resolver.guard';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
@@ -16,17 +16,18 @@ import { UserResolverInterceptor } from './user-resolver.interceptor';
|
||||
IdentityService,
|
||||
JwtAuthGuard,
|
||||
IdentityResolverGuard,
|
||||
UserResolverGuard,
|
||||
RolesGuard,
|
||||
UserResolverInterceptor,
|
||||
{ provide: APP_GUARD, useClass: JwtAuthGuard },
|
||||
{ provide: APP_GUARD, useClass: IdentityResolverGuard },
|
||||
{ provide: APP_GUARD, useClass: UserResolverGuard },
|
||||
],
|
||||
exports: [
|
||||
AuthService,
|
||||
JwtService,
|
||||
IdentityService,
|
||||
UserResolverGuard,
|
||||
RolesGuard,
|
||||
UserResolverInterceptor,
|
||||
],
|
||||
})
|
||||
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,
|
||||
Req,
|
||||
UseGuards,
|
||||
UseInterceptors,
|
||||
} from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import mongoose from 'mongoose';
|
||||
@@ -17,7 +16,6 @@ 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 { UserResolverInterceptor } from '../auth/user-resolver.interceptor';
|
||||
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
|
||||
import type { UserDocument } from '../global/database/schema';
|
||||
import '../auth/auth-request';
|
||||
@@ -26,7 +24,6 @@ import { CreateCommunityDto } from './dto/create-community.dto';
|
||||
import { TransferOwnershipDto } from './dto/transfer-ownership.dto';
|
||||
|
||||
@Controller('communities')
|
||||
@UseInterceptors(UserResolverInterceptor)
|
||||
export class CommunityController {
|
||||
constructor(private readonly communityService: CommunityService) {}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import mongoose from 'mongoose';
|
||||
import { NatsService } from '../global/nats/nats.service';
|
||||
import { SecretService } from '../global/secret/secret.service';
|
||||
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 { DakaoUserError, DakaoUserService } from './dakao-user.service';
|
||||
import { IdempotencyCache } from './idempotency.cache';
|
||||
@@ -81,16 +81,17 @@ export class DakaoSubscriber implements OnModuleInit {
|
||||
}
|
||||
|
||||
let segments: DakaoSegment[];
|
||||
const senderNickname = this.resolveSenderNickname(event);
|
||||
const correlationId = this.serializeDakaoLong(event.origin.chatLog.logId);
|
||||
try {
|
||||
const command = parseCommand(event.origin.chatLog.message);
|
||||
const correlationId = String(event.origin.chatLog.logId ?? '');
|
||||
|
||||
switch (command.kind) {
|
||||
case 'match-list':
|
||||
segments = await this.matchListHandler.handle({
|
||||
communityId,
|
||||
senderUserId: event.userId,
|
||||
senderNickname: event.nickname,
|
||||
senderNickname,
|
||||
});
|
||||
break;
|
||||
case 'match-join':
|
||||
@@ -98,7 +99,7 @@ export class DakaoSubscriber implements OnModuleInit {
|
||||
communityId,
|
||||
matchId: command.matchId,
|
||||
senderUserId: event.userId,
|
||||
senderNickname: event.nickname,
|
||||
senderNickname,
|
||||
gameName: command.gameName,
|
||||
tagLine: command.tagLine,
|
||||
positions: command.positions.positions,
|
||||
@@ -117,8 +118,8 @@ export class DakaoSubscriber implements OnModuleInit {
|
||||
if (err.code === 'not_a_command') return;
|
||||
await this.publisher.sendMessage({
|
||||
chatroomId: event.chatroomId,
|
||||
segments: this.parseErrorReply(event, err),
|
||||
correlationId: String(event.origin.chatLog.logId ?? ''),
|
||||
segments: this.parseErrorReply(event, senderNickname, err),
|
||||
correlationId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -145,24 +146,38 @@ export class DakaoSubscriber implements OnModuleInit {
|
||||
}
|
||||
|
||||
private deriveLogIdKey(event: DakaoInboundEvent): string | null {
|
||||
const logId = event.origin.chatLog.logId;
|
||||
if (typeof logId === 'string') return `${event.projectId}:${logId}`;
|
||||
if (logId && typeof logId === 'object') {
|
||||
const { high, low, unsigned } = logId;
|
||||
return `${event.projectId}:${high ?? ''}|${low ?? ''}|${unsigned ?? ''}`;
|
||||
}
|
||||
return null;
|
||||
const serialized = this.serializeDakaoLong(event.origin.chatLog.logId);
|
||||
return serialized ? `${event.projectId}:${serialized}` : null;
|
||||
}
|
||||
|
||||
private serializeDakaoLong(value: DakaoLong | string | undefined): string {
|
||||
if (typeof value === 'string') return value;
|
||||
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(
|
||||
event: DakaoInboundEvent,
|
||||
senderNickname: string,
|
||||
err: CommandParseError,
|
||||
): DakaoSegment[] {
|
||||
const head: DakaoSegment[] = [
|
||||
{
|
||||
kind: 'mention',
|
||||
userId: event.userId,
|
||||
displayText: event.nickname,
|
||||
displayText: senderNickname,
|
||||
},
|
||||
];
|
||||
const text = ((): string => {
|
||||
|
||||
@@ -43,7 +43,7 @@ describe('MatchJoinHandler', () => {
|
||||
expect.objectContaining({ kind: 'mention', userId: 'kakao-user-1' }),
|
||||
expect.objectContaining({
|
||||
kind: 'text',
|
||||
text: expect.stringContaining('유효하지 않은 매치 ID'),
|
||||
text: expect.stringContaining('유효하지 않은 내전 ID'),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -11,14 +11,12 @@ import {
|
||||
Post,
|
||||
Query,
|
||||
UseGuards,
|
||||
UseInterceptors,
|
||||
} from '@nestjs/common';
|
||||
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 { UserResolverInterceptor } from '../auth/user-resolver.interceptor';
|
||||
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
|
||||
import type {
|
||||
MatchDocument,
|
||||
@@ -33,7 +31,6 @@ import {
|
||||
import { MatchService } from './match.service';
|
||||
|
||||
@Controller('communities/:communityId/matches')
|
||||
@UseInterceptors(UserResolverInterceptor)
|
||||
export class MatchController {
|
||||
constructor(private readonly matchService: MatchService) {}
|
||||
|
||||
|
||||
Reference in new issue
Block a user