diff --git a/backend/services/identity-service/src/application/services/token.service.ts b/backend/services/identity-service/src/application/services/token.service.ts index 03484c54..4c4a756f 100644 --- a/backend/services/identity-service/src/application/services/token.service.ts +++ b/backend/services/identity-service/src/application/services/token.service.ts @@ -47,8 +47,27 @@ export class TokenService { // Save refresh token hash const tokenHash = this.hashToken(refreshToken); - await this.prisma.deviceToken.create({ - data: { + + // 先撤销该设备的旧 token,避免唯一约束冲突 + await this.prisma.deviceToken.updateMany({ + where: { + userId: BigInt(payload.userId), + deviceId: payload.deviceId, + revokedAt: null, + }, + data: { revokedAt: new Date() }, + }); + + // 使用 upsert 避免并发请求导致的唯一约束冲突 + await this.prisma.deviceToken.upsert({ + where: { refreshTokenHash: tokenHash }, + update: { + userId: BigInt(payload.userId), + deviceId: payload.deviceId, + expiresAt: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), + revokedAt: null, + }, + create: { userId: BigInt(payload.userId), deviceId: payload.deviceId, refreshTokenHash: tokenHash,