56 lines
2.4 KiB
TypeScript
56 lines
2.4 KiB
TypeScript
import { Controller, Get, Param, Query, Req, Res } from '@nestjs/common';
|
|
import { Request, Response } from 'express';
|
|
import { ApiOperation, ApiTags } from '@nestjs/swagger';
|
|
import { Throttle } from '@nestjs/throttler';
|
|
import { ConfigService } from '@nestjs/config';
|
|
import { Public } from '../common/decorators/public.decorator';
|
|
import { extractIp } from '../common/utils/ua.util';
|
|
import { isValidPreviewToken } from '../common/utils/preview-token.util';
|
|
import { PublicTraceService } from './public-trace.service';
|
|
import { SettingsService } from '../settings/settings.service';
|
|
|
|
@ApiTags('公开溯源')
|
|
@Controller()
|
|
export class PublicTraceController {
|
|
constructor(
|
|
private readonly service: PublicTraceService,
|
|
private readonly settings: SettingsService,
|
|
private readonly config: ConfigService,
|
|
) {}
|
|
|
|
@Public()
|
|
@Get('public/trace/:shortCode')
|
|
// 公开溯源软限流:每 IP 每分钟 60 次,抑制脚本刷量污染防伪统计与日志
|
|
@Throttle({ default: { limit: 60, ttl: 60_000 } })
|
|
@ApiOperation({ summary: 'C 端溯源查询(匿名)' })
|
|
trace(@Param('shortCode') shortCode: string, @Req() req: Request) {
|
|
const ip = extractIp(req.headers as Record<string, unknown>, req.ip);
|
|
const userAgent = req.headers['user-agent'];
|
|
return this.service.trace(shortCode, { ip, userAgent });
|
|
}
|
|
|
|
// 后台预览:凭时间令牌访问,零副作用(不激活/不计数/不写日志)。令牌过期返回 PREVIEW_EXPIRED。
|
|
@Public()
|
|
@Get('public/trace/:shortCode/preview')
|
|
@Throttle({ default: { limit: 60, ttl: 60_000 } })
|
|
@ApiOperation({ summary: 'C 端溯源预览(令牌保护,不激活不计数)' })
|
|
preview(
|
|
@Param('shortCode') shortCode: string,
|
|
@Query('token') token?: string,
|
|
@Query('state') state?: string,
|
|
) {
|
|
if (!isValidPreviewToken(this.config.get<string>('jwt.secret') || '', token)) {
|
|
return { status: 'PREVIEW_EXPIRED' as const };
|
|
}
|
|
return this.service.preview(shortCode, state === 'active' ? 'active' : 'inactive');
|
|
}
|
|
|
|
// 短链跳转:扫码打开 /t/:shortCode -> 重定向到 C 端溯源页(不在 /api 前缀下)
|
|
@Public()
|
|
@Get('t/:shortCode')
|
|
async redirect(@Param('shortCode') shortCode: string, @Res() res: Response) {
|
|
const clientBaseUrl = await this.settings.getClientBaseUrl();
|
|
res.redirect(302, `${clientBaseUrl}/#/trace/${encodeURIComponent(shortCode)}`);
|
|
}
|
|
}
|