Job application tracker and AI-powered job search assistant. Helps job seekers manage their search journey with AI resume review, job matching, task logging, and application analytics, all while keeping your data private.
TypeScript ai-agentai-resume-analyzerapplication-trackerapplication-tracking-systematscareerjob-applicationjob-automationjob-huntingjob-searchjob-seeker-toolsjob-trackerjob-trackingjobsearchjobseekersmcpollamaresumeresume-reviewself-hosted
refactor(actions): replace hand-rolled auth guards with requireUser() across 12 action files
Khuram Niaz1e25a9f84406
diff --git a/__tests__/apiKey.actions.spec.ts b/__tests__/apiKey.actions.spec.tsnew file mode 100644index 0000000..f283735--- /dev/null+++ b/__tests__/apiKey.actions.spec.ts@@ -0,0 +1,42 @@+import {+ getUserApiKeys,+ saveApiKey,+ deleteApiKey,+} from "@/actions/apiKey.actions";+import { getCurrentUser } from "@/utils/user.utils";++vi.mock("@/utils/user.utils", () => ({ getCurrentUser: vi.fn() }));++vi.mock("@/lib/db", () => ({+ default: {+ apiKey: {+ findMany: vi.fn(),+ upsert: vi.fn(),+ deleteMany: vi.fn(),+ findUnique: vi.fn(),+ },+ },+}));++const mockedGetCurrentUser = vi.mocked(getCurrentUser);++describe("apiKey actions — unauthenticated path", () => {+ beforeEach(() => {+ mockedGetCurrentUser.mockResolvedValue(null);+ });++ it("getUserApiKeys returns the Not authenticated envelope", async () => {+ const result = await getUserApiKeys();+ expect(result).toEqual({ success: false, message: "Not authenticated" });+ });++ it("saveApiKey returns the Not authenticated envelope", async () => {+ const result = await saveApiKey({ provider: "openai", key: "sk-x" });+ expect(result).toEqual({ success: false, message: "Not authenticated" });+ });++ it("deleteApiKey returns the Not authenticated envelope", async () => {+ const result = await deleteApiKey("openai");+ expect(result).toEqual({ success: false, message: "Not authenticated" });+ });+});diff --git a/src/actions/agentChat.actions.ts b/src/actions/agentChat.actions.tsindex a1af093..4df1e13 100644--- a/src/actions/agentChat.actions.ts+++ b/src/actions/agentChat.actions.ts@@ -3,7 +3,7 @@import type { UIMessage } from "ai";import prisma from "@/lib/db";import { handleError } from "@/lib/utils";-import { getCurrentUser } from "@/utils/user.utils";+import { requireUser } from "./shared";import { APP_CONSTANTS } from "@/lib/constants";export const getChatConversation = async (): Promise<{@@ -12,8 +12,7 @@ export const getChatConversation = async (): Promise<{message?: string;}> => {try {- const user = await getCurrentUser();- if (!user) throw new Error("Not authenticated");+ const user = await requireUser();const row = await prisma.chatConversation.findUnique({where: { userId: user.id },@@ -37,8 +36,7 @@ export const saveChatConversation = async (messages: UIMessage[],): Promise<{ success: boolean; message?: string }> => {try {- const user = await getCurrentUser();- if (!user) throw new Error("Not authenticated");+ const user = await requireUser();const trimmed = messages.slice(-APP_CONSTANTS.AGENT_CHAT_MAX_STORED_MESSAGES,@@ -62,8 +60,7 @@ export const clearChatConversation = async (): Promise<{message?: string;}> => {try {- const user = await getCurrentUser();- if (!user) throw new Error("Not authenticated");+ const user = await requireUser();// deleteMany, not delete: deleting a row that does not exist must not// throw, since Clear is the hard reset and has to always work.diff --git a/src/actions/apiKey.actions.ts b/src/actions/apiKey.actions.tsindex 3876db1..d654443 100644--- a/src/actions/apiKey.actions.ts+++ b/src/actions/apiKey.actions.ts@@ -2,6 +2,7 @@import db from "@/lib/db";import { getCurrentUser } from "@/utils/user.utils";+import { requireUser } from "./shared";import { handleError } from "@/lib/utils";import { encrypt, getLast4 } from "@/lib/encryption";import { apiKeySaveSchema } from "@/models/apiKey.schema";@@ -16,8 +17,7 @@ export async function getUserApiKeys(): Promise<{message?: string;}> {try {- const user = await getCurrentUser();- if (!user) return { success: false, message: "Not authenticated" };+ const user = await requireUser();const keys = await db.apiKey.findMany({where: { userId: user.id },@@ -67,8 +67,7 @@ export async function saveApiKey(input: {message?: string;}> {try {- const user = await getCurrentUser();- if (!user) return { success: false, message: "Not authenticated" };+ const user = await requireUser();const parsed = apiKeySaveSchema.parse(input);const isSensitive = parsed.sensitive;@@ -142,8 +141,7 @@ export async function deleteApiKey(provider: string): Promise<{message?: string;}> {try {- const user = await getCurrentUser();- if (!user) return { success: false, message: "Not authenticated" };+ const user = await requireUser();await db.apiKey.deleteMany({where: { userId: user.id, provider },diff --git a/src/actions/coverLetter.actions.ts b/src/actions/coverLetter.actions.tsindex bcd3cd0..e6a1c93 100644--- a/src/actions/coverLetter.actions.ts+++ b/src/actions/coverLetter.actions.ts@@ -2,7 +2,7 @@import MarkdownIt from "markdown-it";import prisma from "@/lib/db";import { handleError } from "@/lib/utils";-import { getCurrentUser } from "@/utils/user.utils";+import { requireUser } from "./shared";import { APP_CONSTANTS } from "@/lib/constants";import { buildCoverLetterTitle } from "@/lib/coverLetterTitle";@@ -15,10 +15,7 @@ export const getCoverLetterList = async (limit: number = APP_CONSTANTS.RECORDS_PER_PAGE): Promise<any | undefined> => {try {- const user = await getCurrentUser();- if (!user) {- throw new Error("Not authenticated");- }+ const user = await requireUser();const skip = (page - 1) * limit;const [data, total] = await Promise.all([@@ -67,10 +64,7 @@ export const createCoverLetter = async (content: string): Promise<any | undefined> => {try {- const user = await getCurrentUser();- if (!user) {- throw new Error("Not authenticated");- }+ const user = await requireUser();const value = title.trim().toLowerCase();const titleExists = await prisma.coverLetter.findFirst({@@ -122,10 +116,7 @@ export const updateCoverLetter = async (content: string): Promise<any | undefined> => {try {- const user = await getCurrentUser();- if (!user) {- throw new Error("Not authenticated");- }+ const user = await requireUser();const res = await prisma.coverLetter.update({where: { id, profile: { userId: user.id } },@@ -143,10 +134,7 @@ export const deleteCoverLetterById = async (coverLetterId: string): Promise<any | undefined> => {try {- const user = await getCurrentUser();- if (!user) {- throw new Error("Not authenticated");- }+ const user = await requireUser();await prisma.coverLetter.delete({where: { id: coverLetterId, profile: { userId: user.id } },@@ -164,10 +152,7 @@ export const generateCoverLetterForJob = async (markdown: string): Promise<any | undefined> => {try {- const user = await getCurrentUser();- if (!user) {- throw new Error("Not authenticated");- }+ const user = await requireUser();if (!markdown ||diff --git a/src/actions/jobLocation.actions.ts b/src/actions/jobLocation.actions.tsindex 78ae5b4..8bcb369 100644--- a/src/actions/jobLocation.actions.ts+++ b/src/actions/jobLocation.actions.ts@@ -1,16 +1,13 @@"use server";import prisma from "@/lib/db";import { handleError } from "@/lib/utils";-import { getCurrentUser } from "@/utils/user.utils";+import { requireUser } from "./shared";import { APP_CONSTANTS } from "@/lib/constants";import { getReferenceEntityList } from "./referenceList";export const getAllJobLocations = async (): Promise<any | undefined> => {try {- const user = await getCurrentUser();- if (!user) {- throw new Error("Not authenticated");- }+ const user = await requireUser();const list = await prisma.location.findMany({where: {createdBy: user.id,@@ -30,11 +27,7 @@ export const getJobLocationsList = async (search?: string,): Promise<any | undefined> => {try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }+ const user = await requireUser();return await getReferenceEntityList({model: prisma.location,@@ -56,11 +49,7 @@ export const deleteJobLocationById = async (locationId: string): Promise<any | undefined> => {try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }+ const user = await requireUser();const experiences = await prisma.workExperience.count({where: {diff --git a/src/actions/jobSource.actions.ts b/src/actions/jobSource.actions.tsindex e28be35..2ac4274 100644--- a/src/actions/jobSource.actions.ts+++ b/src/actions/jobSource.actions.ts@@ -1,7 +1,7 @@"use server";import prisma from "@/lib/db";import { handleError } from "@/lib/utils";-import { getCurrentUser } from "@/utils/user.utils";+import { requireUser } from "./shared";import { APP_CONSTANTS } from "@/lib/constants";import { getReferenceEntityList } from "./referenceList";@@ -12,11 +12,7 @@ export const getJobSourceList = async (search?: string,): Promise<any | undefined> => {try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }+ const user = await requireUser();return await getReferenceEntityList({model: prisma.jobSource,@@ -38,11 +34,7 @@ export const deleteJobSourceById = async (jobSourceId: string): Promise<any | undefined> => {try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }+ const user = await requireUser();const jobs = await prisma.job.count({where: {diff --git a/src/actions/jobtitle.actions.ts b/src/actions/jobtitle.actions.tsindex a0b2f8e..90aabac 100644--- a/src/actions/jobtitle.actions.ts+++ b/src/actions/jobtitle.actions.ts@@ -1,17 +1,14 @@"use server";import prisma from "@/lib/db";import { handleError } from "@/lib/utils";-import { getCurrentUser } from "@/utils/user.utils";+import { requireUser } from "./shared";import { APP_CONSTANTS } from "@/lib/constants";import { canonicalizeEntityValue } from "@/lib/jobs/canonicalize";import { getReferenceEntityList } from "./referenceList";export const getAllJobTitles = async (): Promise<any | undefined> => {try {- const user = await getCurrentUser();- if (!user) {- throw new Error("Not authenticated");- }+ const user = await requireUser();const list = await prisma.jobTitle.findMany({where: {createdBy: user?.id,@@ -31,11 +28,7 @@ export const getJobTitleList = async (search?: string,): Promise<any | undefined> => {try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }+ const user = await requireUser();return await getReferenceEntityList({model: prisma.jobTitle,@@ -57,11 +50,7 @@ export const createJobTitle = async (label: string): Promise<any | undefined> => {try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }+ const user = await requireUser();const value = canonicalizeEntityValue(label.trim());@@ -82,11 +71,7 @@ export const deleteJobTitleById = async (jobTitleId: string): Promise<any | undefined> => {try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }+ const user = await requireUser();const experiences = await prisma.workExperience.count({where: {diff --git a/src/actions/mcpToken.actions.ts b/src/actions/mcpToken.actions.tsindex c3af178..578cfe2 100644--- a/src/actions/mcpToken.actions.ts+++ b/src/actions/mcpToken.actions.ts@@ -1,7 +1,7 @@"use server";import prisma from "@/lib/db";-import { getCurrentUser } from "@/utils/user.utils";+import { requireUser } from "./shared";import { handleError } from "@/lib/utils";import { generateToken } from "@/lib/mcp/tokens";import { APP_CONSTANTS } from "@/lib/constants";@@ -24,8 +24,7 @@ export async function createMcpToken(input: {| { success: false; message: string }> {try {- const user = await getCurrentUser();- if (!user) throw new Error("Not authenticated");+ const user = await requireUser();const count = await prisma.mcpAccessToken.count({ where: { userId: user.id } });if (count >= APP_CONSTANTS.MCP_TOKEN_MAX_PER_USER) {@@ -65,8 +64,7 @@ export async function createMcpToken(input: {export async function listMcpTokens(): Promise<PublicTokenMeta[]> {try {- const user = await getCurrentUser();- if (!user) throw new Error("Not authenticated");+ const user = await requireUser();const records = await prisma.mcpAccessToken.findMany({where: { userId: user.id },@@ -81,8 +79,7 @@ export async function listMcpTokens(): Promise<PublicTokenMeta[]> {export async function revokeMcpToken(id: string): Promise<{ success: boolean; message?: string }> {try {- const user = await getCurrentUser();- if (!user) throw new Error("Not authenticated");+ const user = await requireUser();await prisma.mcpAccessToken.delete({ where: { id, userId: user.id } });return { success: true };diff --git a/src/actions/mock.actions.ts b/src/actions/mock.actions.tsindex b5900d5..5a5eeca 100644--- a/src/actions/mock.actions.ts+++ b/src/actions/mock.actions.ts@@ -1,7 +1,7 @@"use server";import prisma from "@/lib/db";import { handleError } from "@/lib/utils";-import { getCurrentUser } from "@/utils/user.utils";+import { requireUser } from "./shared";import { generateMockActivities } from "@/lib/mock.utils";import {mockActivityTypes,@@ -25,11 +25,7 @@ import { SALARY_RANGES } from "@/lib/data/salaryRangeData";export const generateMockActivitiesAction = async (): Promise<any> => {try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }+ const user = await requireUser();// Check if dev mode is enabledif (process.env.NODE_ENV !== "development") {@@ -116,11 +112,7 @@ export const generateMockActivitiesAction = async (): Promise<any> => {export const clearMockActivitiesAction = async (): Promise<any> => {try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }+ const user = await requireUser();// Check if dev mode is enabledif (process.env.NODE_ENV !== "development") {@@ -161,8 +153,7 @@ export const clearMockActivitiesAction = async (): Promise<any> => {export const generateMockProfileDataAction = async (): Promise<any> => {try {- const user = await getCurrentUser();- if (!user) throw new Error("Not authenticated");+ const user = await requireUser();if (process.env.NODE_ENV !== "development") {throw new Error(@@ -351,8 +342,7 @@ export const generateMockProfileDataAction = async (): Promise<any> => {export const clearMockProfileDataAction = async (): Promise<any> => {try {- const user = await getCurrentUser();- if (!user) throw new Error("Not authenticated");+ const user = await requireUser();if (process.env.NODE_ENV !== "development") {throw new Error(@@ -464,8 +454,7 @@ function pickWeightedStatus(statusMap: Map<string, string>): string {export const generateMockJobsAction = async (): Promise<any> => {try {- const user = await getCurrentUser();- if (!user) throw new Error("Not authenticated");+ const user = await requireUser();if (process.env.NODE_ENV !== "development") {throw new Error(@@ -597,8 +586,7 @@ export const generateMockJobsAction = async (): Promise<any> => {export const clearMockJobsAction = async (): Promise<any> => {try {- const user = await getCurrentUser();- if (!user) throw new Error("Not authenticated");+ const user = await requireUser();if (process.env.NODE_ENV !== "development") {throw new Error(diff --git a/src/actions/note.actions.ts b/src/actions/note.actions.tsindex 8b1dcb7..933907e 100644--- a/src/actions/note.actions.ts+++ b/src/actions/note.actions.ts@@ -3,17 +3,14 @@ import prisma from "@/lib/db";import { handleError } from "@/lib/utils";import { NoteFormSchema } from "@/models/note.schema";import { NoteResponse } from "@/models/note.model";-import { getCurrentUser } from "@/utils/user.utils";+import { requireUser } from "./shared";import { z } from "zod";export const getNotesByJobId = async (jobId: string): Promise<any | undefined> => {try {- const user = await getCurrentUser();- if (!user) {- throw new Error("Not authenticated");- }+ const user = await requireUser();const job = await prisma.job.findFirst({where: { id: jobId, userId: user.id },@@ -44,10 +41,7 @@ export const addNote = async (data: z.infer<typeof NoteFormSchema>): Promise<any | undefined> => {try {- const user = await getCurrentUser();- if (!user) {- throw new Error("Not authenticated");- }+ const user = await requireUser();const validated = NoteFormSchema.parse(data);@@ -78,10 +72,7 @@ export const updateNote = async (data: z.infer<typeof NoteFormSchema>): Promise<any | undefined> => {try {- const user = await getCurrentUser();- if (!user) {- throw new Error("Not authenticated");- }+ const user = await requireUser();const validated = NoteFormSchema.parse(data);if (!validated.id) {@@ -104,10 +95,7 @@ export const deleteNote = async (noteId: string): Promise<any | undefined> => {try {- const user = await getCurrentUser();- if (!user) {- throw new Error("Not authenticated");- }+ const user = await requireUser();await prisma.note.delete({where: { id: noteId, userId: user.id },diff --git a/src/actions/question.actions.ts b/src/actions/question.actions.tsindex c298c09..24b5612 100644--- a/src/actions/question.actions.ts+++ b/src/actions/question.actions.ts@@ -2,7 +2,7 @@import prisma from "@/lib/db";import { handleError } from "@/lib/utils";import { AddQuestionFormSchema } from "@/models/addQuestionForm.schema";-import { getCurrentUser } from "@/utils/user.utils";+import { requireUser } from "./shared";import { APP_CONSTANTS } from "@/lib/constants";import { z } from "zod";@@ -13,8 +13,7 @@ export const getQuestionsList = async (search?: string): Promise<any | undefined> => {try {- const user = await getCurrentUser();- if (!user) throw new Error("Not authenticated");+ const user = await requireUser();const offset = (page - 1) * limit;@@ -56,8 +55,7 @@ export const getQuestionById = async (questionId: string): Promise<any | undefined> => {try {- const user = await getCurrentUser();- if (!user) throw new Error("Not authenticated");+ const user = await requireUser();const question = await prisma.question.findFirst({where: { id: questionId, createdBy: user.id },@@ -78,8 +76,7 @@ export const createQuestion = async (data: z.infer<typeof AddQuestionFormSchema>): Promise<any | undefined> => {try {- const user = await getCurrentUser();- if (!user) throw new Error("Not authenticated");+ const user = await requireUser();const validatedData = AddQuestionFormSchema.parse(data);@@ -105,8 +102,7 @@ export const updateQuestion = async (data: z.infer<typeof AddQuestionFormSchema>): Promise<any | undefined> => {try {- const user = await getCurrentUser();- if (!user) throw new Error("Not authenticated");+ const user = await requireUser();if (!data.id) throw new Error("Question ID is required for update");@@ -134,8 +130,7 @@ export const deleteQuestion = async (questionId: string): Promise<any | undefined> => {try {- const user = await getCurrentUser();- if (!user) throw new Error("Not authenticated");+ const user = await requireUser();await prisma.question.delete({where: { id: questionId, createdBy: user.id },@@ -151,8 +146,7 @@ export const getTagsWithQuestionCounts = async (): Promise<any | undefined> => {try {- const user = await getCurrentUser();- if (!user) throw new Error("Not authenticated");+ const user = await requireUser();const tags = await prisma.tag.findMany({where: { createdBy: user.id },diff --git a/src/actions/tag.actions.ts b/src/actions/tag.actions.tsindex 6f01ce5..7964121 100644--- a/src/actions/tag.actions.ts+++ b/src/actions/tag.actions.ts@@ -1,16 +1,13 @@"use server";import prisma from "@/lib/db";import { handleError } from "@/lib/utils";-import { getCurrentUser } from "@/utils/user.utils";+import { requireUser } from "./shared";import { APP_CONSTANTS } from "@/lib/constants";import { resolveTag as resolveTagCore } from "@/lib/jobs/resolve";export const getAllTags = async (): Promise<any | undefined> => {try {- const user = await getCurrentUser();- if (!user) {- throw new Error("Not authenticated");- }+ const user = await requireUser();const list = await prisma.tag.findMany({where: { createdBy: user.id },orderBy: { label: "asc" },@@ -28,10 +25,7 @@ export const getTagList = async (search?: string,): Promise<any | undefined> => {try {- const user = await getCurrentUser();- if (!user) {- throw new Error("Not authenticated");- }+ const user = await requireUser();const skip = (page - 1) * limit;const whereClause: any = { createdBy: user.id };@@ -64,10 +58,7 @@ export const getTagList = async (export const createTag = async (label: string): Promise<any | undefined> => {try {- const user = await getCurrentUser();- if (!user) {- throw new Error("Not authenticated");- }+ const user = await requireUser();if (!label.trim()) {throw new Error("Tag label cannot be empty.");@@ -85,10 +76,7 @@ export const deleteTagById = async (tagId: string,): Promise<any | undefined> => {try {- const user = await getCurrentUser();- if (!user) {- throw new Error("Not authenticated");- }+ const user = await requireUser();const [jobs, questions, skills] = await Promise.all([prisma.job.count({ where: { tags: { some: { id: tagId } } } }),diff --git a/src/actions/userSettings.actions.ts b/src/actions/userSettings.actions.tsindex 57d8438..8d603ab 100644--- a/src/actions/userSettings.actions.ts+++ b/src/actions/userSettings.actions.ts@@ -1,7 +1,7 @@"use server";import prisma from "@/lib/db";import { handleError } from "@/lib/utils";-import { getCurrentUser } from "@/utils/user.utils";+import { requireUser } from "./shared";import {UserSettingsData,defaultUserSettings,@@ -11,11 +11,7 @@ import {export const getUserSettings = async (): Promise<any | undefined> => {try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }+ const user = await requireUser();const userSettings = await prisma.userSettings.findUnique({where: { userId: user.id },@@ -53,11 +49,7 @@ export const updateUserSettings = async (settings: Partial<UserSettingsData>): Promise<any | undefined> => {try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }+ const user = await requireUser();const existingSettings = await prisma.userSettings.findUnique({where: { userId: user.id },