.
This commit is contained in:
1 parent
5af2c80cd1
commit
f7ee34da4f
78 files changed
+9016
-150
No files matched your search
@@ -9,17 +9,21 @@ 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) {}
|
||||
|
||||
@@ -47,6 +51,7 @@ export class AuctionController {
|
||||
}
|
||||
|
||||
@Get()
|
||||
@AllowPublicAccess()
|
||||
public async getAuction(
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
) {
|
||||
@@ -55,6 +60,7 @@ export class AuctionController {
|
||||
|
||||
// 공개 — 팀장 2명만 쓸 엔드포인트(트러스트 기반, 10명 동시 관전).
|
||||
@Post('open-bidding')
|
||||
@AllowPublicAccess()
|
||||
@HttpCode(HttpStatus.OK)
|
||||
public async openBidding(
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
@@ -63,6 +69,7 @@ export class AuctionController {
|
||||
}
|
||||
|
||||
@Post('bids')
|
||||
@AllowPublicAccess()
|
||||
@HttpCode(HttpStatus.OK)
|
||||
public async placeBid(
|
||||
@CurrentUser() currentUser: UserDocument | undefined,
|
||||
@@ -78,6 +85,7 @@ export class AuctionController {
|
||||
}
|
||||
|
||||
@Post('sold')
|
||||
@AllowPublicAccess()
|
||||
@HttpCode(HttpStatus.OK)
|
||||
public async markSold(
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
@@ -90,6 +98,7 @@ export class AuctionController {
|
||||
}
|
||||
|
||||
@Post('next')
|
||||
@AllowPublicAccess()
|
||||
@HttpCode(HttpStatus.OK)
|
||||
public async next(
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
|
||||
@@ -9,8 +9,19 @@ import {
|
||||
WebSocketServer,
|
||||
} from '@nestjs/websockets';
|
||||
import mongoose from 'mongoose';
|
||||
import type { JWTPayload } from 'jose';
|
||||
import { Namespace, Socket } from 'socket.io';
|
||||
import type { AuctionDocument, Position, TeamSide } from '../global/database/schema';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
import { IdentityService } from '../auth/identity.service';
|
||||
import { JwtService } from '../auth/jwt.service';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import type {
|
||||
AuctionDocument,
|
||||
IdentityDocument,
|
||||
Position,
|
||||
TeamSide,
|
||||
UserDocument,
|
||||
} from '../global/database/schema';
|
||||
import { AuctionService } from './auction.service';
|
||||
|
||||
interface JoinAuctionPayload {
|
||||
@@ -32,7 +43,7 @@ interface SoldPayload {
|
||||
cors: {
|
||||
origin: true,
|
||||
credentials: true,
|
||||
allowedHeaders: ['Content-Type', 'X-Auth-User-Id'],
|
||||
allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'],
|
||||
},
|
||||
})
|
||||
export class AuctionGateway
|
||||
@@ -44,10 +55,26 @@ export class AuctionGateway
|
||||
private readonly logger = new Logger(AuctionGateway.name);
|
||||
private readonly roomTimers = new Map<string, NodeJS.Timeout>();
|
||||
|
||||
constructor(private readonly auctionService: AuctionService) {}
|
||||
constructor(
|
||||
private readonly auctionService: AuctionService,
|
||||
private readonly authService: AuthService,
|
||||
private readonly jwtService: JwtService,
|
||||
private readonly identityService: IdentityService,
|
||||
private readonly connectionService: ConnectionService,
|
||||
) {}
|
||||
|
||||
public handleConnection(socket: Socket) {
|
||||
this.logger.debug(`Auction client connected: ${socket.id}`);
|
||||
public async handleConnection(socket: Socket) {
|
||||
try {
|
||||
await this.authenticateSocket(socket);
|
||||
this.logger.debug(`Auction client connected: ${socket.id}`);
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`Auction client authentication failed: ${
|
||||
err instanceof Error ? err.message : err
|
||||
}`,
|
||||
);
|
||||
socket.disconnect(true);
|
||||
}
|
||||
}
|
||||
|
||||
public handleDisconnect(socket: Socket) {
|
||||
@@ -70,6 +97,7 @@ export class AuctionGateway
|
||||
socket.data.matchId = payload.matchId;
|
||||
|
||||
try {
|
||||
await this.resolveSocketUserForMatch(socket, payload.matchId);
|
||||
const auction = await this.auctionService.getByMatchId(
|
||||
new mongoose.Types.ObjectId(payload.matchId),
|
||||
);
|
||||
@@ -165,7 +193,9 @@ export class AuctionGateway
|
||||
}
|
||||
|
||||
private getSocketMatchId(socket: Socket): string | undefined {
|
||||
return typeof socket.data.matchId === 'string' ? socket.data.matchId : undefined;
|
||||
return typeof socket.data.matchId === 'string'
|
||||
? socket.data.matchId
|
||||
: undefined;
|
||||
}
|
||||
|
||||
private resolveBidderUserId(
|
||||
@@ -173,7 +203,9 @@ export class AuctionGateway
|
||||
payloadBidderUserId?: string,
|
||||
): mongoose.Types.ObjectId | undefined {
|
||||
const candidate =
|
||||
payloadBidderUserId ?? this.readHandshakeUserId(socket);
|
||||
payloadBidderUserId ??
|
||||
(socket.data.user as UserDocument | undefined)?._id.toString() ??
|
||||
this.readHandshakeUserId(socket);
|
||||
if (!candidate || !mongoose.isValidObjectId(candidate)) {
|
||||
return undefined;
|
||||
}
|
||||
@@ -188,6 +220,80 @@ export class AuctionGateway
|
||||
return Array.isArray(header) ? header[0] : header;
|
||||
}
|
||||
|
||||
private async authenticateSocket(socket: Socket): Promise<void> {
|
||||
const fallback = await this.authService.resolveDevUserById(
|
||||
this.readHandshakeUserId(socket),
|
||||
);
|
||||
if (fallback) {
|
||||
socket.data.user = fallback.user;
|
||||
socket.data.identity = fallback.identity;
|
||||
return;
|
||||
}
|
||||
|
||||
const token = this.readHandshakeToken(socket);
|
||||
if (!token) {
|
||||
throw new Error('Missing auction socket token.');
|
||||
}
|
||||
|
||||
const { payload } = await this.jwtService.verify(
|
||||
token,
|
||||
'MICROSOFT_ENTRAID',
|
||||
);
|
||||
socket.data.identity = await this.identityService.findOrCreateByOid({
|
||||
entraOid: this.requireStringClaim(payload, 'oid'),
|
||||
tenantId: this.stringClaim(payload.tid),
|
||||
email:
|
||||
this.stringClaim(payload.preferred_username) ??
|
||||
this.stringClaim(payload.email),
|
||||
displayName: this.stringClaim(payload.name),
|
||||
});
|
||||
}
|
||||
|
||||
private readHandshakeToken(socket: Socket): string | undefined {
|
||||
const authToken = socket.handshake.auth.token;
|
||||
if (typeof authToken === 'string' && authToken.trim()) {
|
||||
return authToken.trim().replace(/^Bearer\s+/i, '');
|
||||
}
|
||||
|
||||
const header = socket.handshake.headers.authorization;
|
||||
const authorization = Array.isArray(header) ? header[0] : header;
|
||||
if (authorization?.startsWith('Bearer ')) {
|
||||
return authorization.slice('Bearer '.length).trim();
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private async resolveSocketUserForMatch(
|
||||
socket: Socket,
|
||||
matchId: string,
|
||||
): Promise<void> {
|
||||
if (socket.data.user || !socket.data.identity) return;
|
||||
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const match = await MatchModel.findById(matchId).select({
|
||||
communityId: 1,
|
||||
});
|
||||
if (!match) return;
|
||||
|
||||
const UserModel = await this.connectionService.getModel('user');
|
||||
socket.data.user = await UserModel.findOne({
|
||||
communityId: match.communityId,
|
||||
identityId: (socket.data.identity as IdentityDocument)._id,
|
||||
}).exec();
|
||||
}
|
||||
|
||||
private requireStringClaim(payload: JWTPayload, key: string): string {
|
||||
const value = payload[key];
|
||||
if (typeof value !== 'string' || value.length === 0) {
|
||||
throw new Error(`Token is missing ${key} claim.`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private stringClaim(value: unknown): string | undefined {
|
||||
return typeof value === 'string' && value.length > 0 ? value : undefined;
|
||||
}
|
||||
|
||||
private broadcastState(matchId: string, auction: AuctionDocument) {
|
||||
this.server.to(matchId).emit('state', this.serializeAuction(auction));
|
||||
this.syncRoomTimer(matchId, auction);
|
||||
|
||||
Reference in new issue
Block a user