Files
var-monorepo/apps/hub/app/(auth)/login/_components/action.ts
2026-02-08 21:37:10 +01:00

111 lines
2.7 KiB
TypeScript

"use server";
import { LOG_TYPE, prisma } from "@repo/db";
import { getServerSession } from "api/auth/[...nextauth]/auth";
import { randomUUID } from "crypto";
import { cookies, headers } from "next/headers";
import { sendReportEmbed } from "../../../../helper/discord";
export async function getOrSetDeviceId() {
const store = await cookies();
let deviceId = store.get("device_id")?.value;
if (!deviceId) {
deviceId = randomUUID();
store.set("device_id", deviceId, {
httpOnly: true,
secure: true,
sameSite: "lax",
path: "/",
maxAge: 60 * 60 * 24 * 365, // 1 Jahr
});
}
return deviceId;
}
export const logAction = async (
type: LOG_TYPE,
otherValues?: {
ip: string;
field?: string;
oldValue?: string;
newValue?: string;
userId?: string;
},
) => {
const headersList = await headers();
const user = await getServerSession();
const deviceId = await getOrSetDeviceId();
if (type == "LOGIN" || type == "REGISTER") {
const existingLogs = await prisma.log.findMany({
where: {
type: "LOGIN",
userId: {
not: user?.user.id,
},
OR: [
{
ip: otherValues?.ip,
},
{
deviceId: deviceId,
},
],
},
});
if (existingLogs.length > 0 && user?.user.id) {
const existingReport = await prisma.report.findFirst({
where: {
reportedUserId: user.user.id,
reportedUserRole: {
contains: "Doppelter Account Verdacht",
},
},
});
// keine Doppel-Reports für denselben Nutzer erstellen
if (!existingReport) {
// Möglicherweise ein doppelter Account, Report erstellen
const report = await prisma.report.create({
data: {
text: `Möglicher doppelter Account erkannt bei Login-Versuch.\n\nÜbereinstimmende Logs:\n${existingLogs
.map((log) => `- Log ID: ${log.id}, IP: ${log.ip}, Zeitstempel: ${log.timestamp}`)
.join("\n")}`,
reportedUserId: user?.user.id,
reportedUserRole: "LOGIN - Doppelter Account Verdacht",
},
});
await sendReportEmbed(report.id);
} else {
// Update report and send it again to Discord
const updatedReport = await prisma.report.update({
where: {
id: existingReport.id,
},
data: {
text: `Möglicher doppelter Account erkannt bei Login-Versuch.\n\nÜbereinstimmende Logs:\n${existingLogs
.map(
(log) =>
`- Log ID: ${log.id}, IP: ${log.ip}, Zeitstempel: ${new Date(log.timestamp).toLocaleString("de-DE")}`,
)
.join("\n")}`,
},
});
await sendReportEmbed(updatedReport.id);
}
}
}
await prisma.log.create({
data: {
type,
browser: headersList.get("user-agent") || "unknown",
userId: user?.user.id || otherValues?.userId,
deviceId: deviceId,
ip: otherValues?.ip,
...otherValues,
},
});
};