daphnis/app/(sharing)/[token]/token.ts
2024-07-23 17:33:15 -04:00

70 lines
1.8 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; // share token
id?: string; // playlog id after the token
error?: string; // error
}> {
const { user } = await getAuth();
if (!user || !user.id || typeof user.id !== "string") {
return {
error: "Invalid user or user ID",
};
}
// generate the token that expires
const gernatetoken = randomBytes(5).readUInt32BE(0).toString();
// generate token logic
const token = await daphnis.linkSharingToken.create({
data: {
playlogId: id, // sets the playlog id
id: randomUUID(), // generates a random primary id for the share token
userId: user.id, // attaches the userid from daphnis
token: gernatetoken, // makes an expirable token thats added to the token column
createdAt: new Date(), // created at 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 };
}