Files
sign/packages/auth/server/lib/utils/get-session.ts

57 lines
1.4 KiB
TypeScript
Raw Normal View History

2025-01-02 15:33:37 +11:00
import type { Context } from 'hono';
import { AppError } from '@documenso/lib/errors/app-error';
import { AuthenticationErrorCode } from '../errors/error-codes';
import type { SessionValidationResult } from '../session/session';
import { validateSessionToken } from '../session/session';
import { getSessionCookie } from '../session/session-cookies';
2025-02-16 00:44:01 +11:00
export const getSession = async (c: Context | Request) => {
const { session, user } = await getOptionalSession(mapRequestToContextForCookie(c));
if (session && user) {
return { session, user };
}
if (c instanceof Request) {
throw new Error('Unauthorized');
}
throw new AppError(AuthenticationErrorCode.Unauthorized);
};
export const getOptionalSession = async (
c: Context | Request,
): Promise<SessionValidationResult> => {
2025-01-02 15:33:37 +11:00
const sessionId = await getSessionCookie(mapRequestToContextForCookie(c));
if (!sessionId) {
return {
isAuthenticated: false,
session: null,
user: null,
};
}
return await validateSessionToken(sessionId);
};
2025-02-14 22:00:55 +11:00
/**
2025-02-19 16:07:04 +11:00
* Todo: (RR7) Rethink, this is pretty sketchy.
2025-02-14 22:00:55 +11:00
*/
2025-01-02 15:33:37 +11:00
const mapRequestToContextForCookie = (c: Context | Request) => {
if (c instanceof Request) {
const partialContext = {
req: {
raw: c,
},
};
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
return partialContext as unknown as Context;
}
return c;
};