import { getServerSession } from "next-auth"; import { DEFAULT_SERVER_ERROR_MESSAGE, createSafeActionClient } from "next-safe-action"; import { authOptions } from "./authOptions"; import { AuthenticationError, AuthorizationError } from "../lib/errors"; import { getSDKForCurrentUser } from "../getSDKForCurrentUser"; export const actionClient = createSafeActionClient({ handleServerError(e: Error) { /* if ( e instanceof ResourceNotFoundError || e instanceof AuthorizationError || e instanceof InvalidInputError || e instanceof UnknownError || e instanceof AuthenticationError || e instanceof OperationNotAllowedError || e instanceof AppcondaException ) { return e.message; } */ // eslint-disable-next-line no-console -- This error needs to be logged for debugging server-side errors console.error("SERVER ERROR: ", e); return DEFAULT_SERVER_ERROR_MESSAGE; }, }); export const authenticatedActionClient = actionClient.use(async ({ next }) => { const options = authOptions(); const session = options ? await getServerSession(options) : null; //@ts-ignore if (!session?.user) { throw new AuthenticationError("Not authenticated"); } //@ts-ignore const userId = session.user.id; // Get the SDK and use users.get method to fetch the user const { users } = await getSDKForCurrentUser(); const user = await users.get(userId); if (!user) { throw new AuthorizationError("User not found"); } return next({ ctx: { user } }); });