Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
116 changes: 116 additions & 0 deletions src/lib/session.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
"use server";
import { prisma } from "./prisma";
import crypto from "crypto";

function generateSessionToken() {
return crypto.randomBytes(32).toString("hex"); // 64-char token
}

function hashToken(token: string) {
return crypto.createHash("sha256").update(token).digest("hex");
}

/**
* Creates a new session with a userId and projectId
* @param userId The userId of the user for the session
* @param projectId The projectId of the project for the session
* @returns The created session
*/
export async function createSession(userId: string, projectId: string) {
const rawToken = generateSessionToken();
const hashedToken = hashToken(rawToken);

const expiresAt = new Date();
expiresAt.setDate(expiresAt.getDate() + 1); // 1 day
const session = prisma.session.create({

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

prisma.session.create(...) returns a lazy PrismaPromise, and its own enumerable shape includes a then — so { ...session, token: rawToken } below produces a thenable object. When the caller does await createSession(...), that triggers promise assimilation on the returned object rather than treating it as a plain object: the DB write does happen, but the resolved value becomes the created DB record (hashed token), and token: rawToken gets discarded before it ever reaches the caller. Net effect: sessions created this way can't be validated with the token that's actually returned — worth an explicit await here and constructing the return object from the resolved row, independent of anything else in this review.

data: {
userId,
projectId,
token: hashedToken,
expiresAt,
},
});
return {
...session,
token: rawToken,
};
}

/**
* Gets a session based on a session id
* @param id The session id
* @returns The session
*/
export async function getSession(id: string) {
prisma.session.findUnique({ where: { id, expiresAt: { gt: new Date() } } });
}

/**
* Gets all sessions by filter
* @param filters userId and projectId
* @returns All sessions associated with the filters
*/
export async function getSessions(filters: {
userId: string;
projectId: string;
}) {
const sessions = await prisma.session.findMany({
where: {
...(filters?.userId && { userId: filters.userId }),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

filters?.userId && { userId: filters.userId } evaluates to "" (falsy) when userId is an empty string rather than undefined, and spreading {...""} contributes nothing — so an empty-string filter is silently dropped rather than applied. Worth checking for undefined/null explicitly (filters.userId != null) rather than relying on truthiness, since this is a plain logic bug that'll under-filter even for a fully authorized caller who passes an empty string by mistake.

...(filters?.projectId && { projectId: filters.projectId }),
expiresAt: {
gt: new Date(), // only active sessions
},
},
orderBy: {
createdAt: "desc",
},
});

if (!sessions) return null;

return sessions;
}

/**
* Updates a session to extend the expireAt
* @param id The session id
* @param data When the new expireAt should be
* @returns The updated session
*/
export async function updateSession(id: string, data: { expiresAt: Date }) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

expiresAt is taken directly from the caller with no upper bound and no check that the session belongs to them — worth clamping to a fixed server-side increment with an absolute cap (e.g. createdAt + N days) rather than trusting the caller's value directly, regardless of what auth ends up gating this.

const session = await prisma.session.findUnique({ where: { id } });
if (!session || session.expiresAt < new Date()) return null;
return prisma.session.update({
where: { id },
data: { expiresAt: data.expiresAt },
});
}

/**
* Deletes a session
* @param id The session id
* @returns If the delete was successful
*/
export async function deleteSession(id: string) {
return prisma.session.delete({ where: { id } });
}

/**
* Validates a session based on a token and project
* @param token The token associated with the session
* @param projectId The projectId associated with a project
* @returns a session
*/
export async function validateSession(token: string, projectId: string) {
const hashedToken = hashToken(token);
return prisma.session.findFirst({
where: {
token: hashedToken,
projectId,
expiresAt: {
gt: new Date(),
},
},
});
}
Loading