daphnis/app/(sharing)/[token]/token.ts
2024-06-29 02:37:50 -04:00

68 lines
1.5 KiB
TypeScript

"use server";
import { getAuth } from "@/auth/queries/getauth";
import { daphnis } from "@/lib/prisma";
import { randomUUID } from "crypto";
import { randomBytes } from "crypto";
import { redirect } from "next/navigation";
export async function generateShareToken(id: number): Promise<{
token?: string;
id?: string;
error?: string;
}> {
const { user } = await getAuth();
if (!user || !user.id || typeof user.id !== "string") {
return {
error: "Invalid user or user ID",
};
}
const gernatetoken = randomBytes(5).readUInt32BE(0).toString();
const token = await daphnis.linkSharingToken.create({
data: {
playlogId: id,
id: randomUUID(),
userId: user.id,
token: gernatetoken,
createdAt: new Date(),
},
});
return { token: token.token };
}
export async function shareScore(token: string) {
const PublicPage = await daphnis.linkSharingToken.findUnique({
where: {
token,
},
});
if (!PublicPage) {
return {
error: "Invalid token or token does not exist",
};
}
// Check if token has expired
const tokenAge =
new Date().getTime() - new Date(PublicPage.createdAt).getTime();
const tokenAgeLimit = 1000 * 60 * 60 * 24; // 1 day in milliseconds
if (tokenAge > tokenAgeLimit) {
await daphnis.linkSharingToken.update({
where: {
token,
},
data: {
tokenExpiredAt: new Date(),
},
});
redirect("/");
}
return { success: true };
}