daphnis/app/(sharing)/[token]/token.ts

70 lines
1.8 KiB
TypeScript
Raw Normal View History

2024-06-29 05:22:22 +00:00
"use server";
import { getAuth } from "@/auth/queries/getauth";
2024-06-29 06:37:50 +00:00
import { daphnis } from "@/lib/prisma";
2024-06-29 05:22:22 +00:00
import { randomUUID } from "crypto";
import { randomBytes } from "crypto";
import { redirect } from "next/navigation";
export async function generateShareToken(id: number): Promise<{
2024-07-23 21:34:48 +00:00
token?: string;
id?: string;
error?: string;
2024-07-23 21:35:01 +00:00
}> {
2024-06-29 05:22:22 +00:00
const { user } = await getAuth();
if (!user || !user.id || typeof user.id !== "string") {
return {
error: "Invalid user or user ID",
};
}
2024-07-23 21:29:07 +00:00
// generate the token that expires
2024-06-29 05:22:22 +00:00
const gernatetoken = randomBytes(5).readUInt32BE(0).toString();
2024-07-23 21:29:07 +00:00
// generate token logic
2024-06-29 06:37:50 +00:00
const token = await daphnis.linkSharingToken.create({
2024-06-29 05:22:22 +00:00
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
2024-07-23 21:29:07 +00:00
createdAt: new Date(), // created at date
2024-06-29 05:22:22 +00:00
},
});
return { token: token.token };
}
export async function shareScore(token: string) {
2024-06-29 06:37:50 +00:00
const PublicPage = await daphnis.linkSharingToken.findUnique({
2024-06-29 05:22:22 +00:00
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
2024-06-29 05:22:22 +00:00
// if (tokenAge > tokenAgeLimit) {
// await daphnis.linkSharingToken.update({
// where: {
// token,
// },
// data: {
// tokenExpiredAt: new Date(),
// },
// });
// redirect("/");
// }
2024-06-29 05:22:22 +00:00
return { success: true };
}