Skip to content

Commit

Permalink
added test cases for verifyRole Query
Browse files Browse the repository at this point in the history
  • Loading branch information
PurnenduMIshra129th committed Jan 31, 2025
1 parent 19454bb commit 4341a08
Show file tree
Hide file tree
Showing 2 changed files with 167 additions and 10 deletions.
24 changes: 14 additions & 10 deletions src/resolvers/Query/verifyRole.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,9 @@ export const verifyRole: QueryResolvers["verifyRole"] = async (
try {
// Extract token from the Authorization header
const authHeader = req.headers.authorization;
// console.debug("Authorization header detected.") // OR remove entirely
if (!authHeader) {
return { role: "", isAuthorized: false };
}

Check warning on line 34 in src/resolvers/Query/verifyRole.ts

View check run for this annotation

Codecov / codecov/patch

src/resolvers/Query/verifyRole.ts#L33-L34

Added lines #L33 - L34 were not covered by tests

const token = authHeader.startsWith("Bearer ")
? authHeader.split(" ")[1]
: authHeader;

Check warning on line 37 in src/resolvers/Query/verifyRole.ts

View check run for this annotation

Codecov / codecov/patch

src/resolvers/Query/verifyRole.ts#L37

Added line #L37 was not covered by tests
Expand All @@ -59,15 +57,22 @@ export const verifyRole: QueryResolvers["verifyRole"] = async (
tokenVersion: process.env.TOKEN_VERSION
? parseInt(process.env.TOKEN_VERSION)
: 0,

Check warning on line 59 in src/resolvers/Query/verifyRole.ts

View check run for this annotation

Codecov / codecov/patch

src/resolvers/Query/verifyRole.ts#L59

Added line #L59 was not covered by tests
}).lean();

let role = "";
if (appUserProfile?.isSuperAdmin) {
role = "admin";
} else {
role = "user";
});
if (appUserProfile == null || appUserProfile == undefined) {
throw new Error("User profile not found");
}

let role = "user"; // Default role
if (appUserProfile) {
if (appUserProfile.isSuperAdmin) {
role = "superAdmin";
} else if (
appUserProfile.adminFor &&
appUserProfile.adminFor.length > 0
) {
role = "admin";
}
}
return {
role: role,
isAuthorized: true,
Expand All @@ -78,7 +83,6 @@ export const verifyRole: QueryResolvers["verifyRole"] = async (
"Token verification failed:",
error instanceof Error ? error.message : "Unknown error",
);

// Return specific error status
const isJwtError = error instanceof jwt.JsonWebTokenError;
return {
Expand Down
153 changes: 153 additions & 0 deletions tests/resolvers/Query/verifyRole.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
import type { Mock } from "vitest";
import { describe, test, expect, vi, beforeEach } from "vitest";
import jwt from "jsonwebtoken";
import { verifyRole } from "../../../src/resolvers/Query/verifyRole";
import { AppUserProfile } from "../../../src/models/AppUserProfile";

// Mock environment variables
process.env.ACCESS_TOKEN_SECRET = "test_secret";
process.env.DEFAULT_LANGUAGE_CODE = "en";
process.env.TOKEN_VERSION = "0";
// Mock database call
vi.mock("../../../src/models/AppUserProfile", () => ({
AppUserProfile: {
findOne: vi.fn().mockResolvedValue({
lean: () => ({ userId: "user123", isSuperAdmin: false, adminFor: [] }),
}),
},
}));
describe("verifyRole", () => {
let req: any;

Check warning on line 20 in tests/resolvers/Query/verifyRole.spec.ts

View workflow job for this annotation

GitHub Actions / Check for linting, formatting, and type errors

Unexpected any. Specify a different type
beforeEach(() => {
req = {
headers: {
authorization: "Bearer validToken",

Check failure

Code scanning / CodeQL

Hard-coded credentials Critical test

The hard-coded value "Bearer validToken" is used as
authorization header
.
},
};
vi.restoreAllMocks(); // Reset all mocks before each test
});

test("should return role 'user' for a valid user token", async () => {
vi.spyOn(jwt, "verify").mockImplementationOnce(() => {
return { userId: "user123" };
});
const req = {
headers: {
authorization: "Bearer validToken",

Check failure

Code scanning / CodeQL

Hard-coded credentials Critical test

The hard-coded value "Bearer validToken" is used as
authorization header
.
},
};
(AppUserProfile.findOne as Mock).mockResolvedValue({
userId: "user123",
isSuperAdmin: false,
adminFor: [],
});
// Mock database call for the user
if (verifyRole !== undefined) {
const result = await verifyRole({}, {}, { req });
expect(result).toEqual({ role: "user", isAuthorized: true });
} else {
throw new Error("verifyRole is undefined");
}
});

test("should return role 'admin' for a valid admin token", async () => {
vi.spyOn(jwt, "verify").mockImplementationOnce(() => {
return { userId: "admin123" };
});
const req = {
headers: {
authorization: "Bearer validToken",

Check failure

Code scanning / CodeQL

Hard-coded credentials Critical test

The hard-coded value "Bearer validToken" is used as
authorization header
.
},
};
(AppUserProfile.findOne as Mock).mockResolvedValue({
userId: "admin123",
isSuperAdmin: false,
adminFor: ["Angel Foundation"],
});
if (verifyRole !== undefined) {
const result = await verifyRole({}, {}, { req });
expect(result).toEqual({ role: "admin", isAuthorized: true });
} else {
throw new Error("verifyRole is undefined");
}
});

test("should return role 'superAdmin' for a valid superAdmin token", async () => {
vi.spyOn(jwt, "verify").mockImplementationOnce(() => {
return { userId: "superadmin123" };
});

const req = {
headers: {
authorization: "Bearer validToken",

Check failure

Code scanning / CodeQL

Hard-coded credentials Critical test

The hard-coded value "Bearer validToken" is used as
authorization header
.
},
};
(AppUserProfile.findOne as Mock).mockResolvedValue({
userId: "superadmin123",
isSuperAdmin: true,
adminFor: [],
});
if (verifyRole !== undefined) {
const result = await verifyRole({}, {}, { req });
expect(result).toEqual({ role: "superAdmin", isAuthorized: true });
} else {
throw new Error("verifyRole is undefined");
}
});

test("should return unauthorized when user is not found in DB", async () => {
vi.spyOn(jwt, "verify").mockImplementationOnce(() => {
return { userId: "unknownUser" };
});
const req = {
headers: {
authorization: "Bearer validToken",

Check failure

Code scanning / CodeQL

Hard-coded credentials Critical test

The hard-coded value "Bearer validToken" is used as
authorization header
.
},
};
(AppUserProfile.findOne as Mock).mockResolvedValue(null);
if (verifyRole !== undefined) {
const result = await verifyRole({}, {}, { req });
expect(result).toEqual({
role: "",
isAuthorized: false,
error: "Authentication failed",
});
} else {
throw new Error("verifyRole is undefined");
}
});

test("should handle missing ACCESS_TOKEN_SECRET", async () => {
delete process.env.ACCESS_TOKEN_SECRET;
if (verifyRole !== undefined) {
const result = await verifyRole({}, {}, { req });
expect(result).toEqual({
role: "",
isAuthorized: false,
error: "Authentication failed",
});
// Restore ACCESS_TOKEN_SECRET
process.env.ACCESS_TOKEN_SECRET = "test_secret";
} else {
throw new Error("verifyRole is undefined");
}
});

test("should handle malformed token", async () => {
// Simulate a malformed token error
const verify = vi.fn().mockImplementation(() => {
throw new Error("jwt malformed");
});
vi.stubGlobal("jwt", { ...jwt, verify });
if (verifyRole !== undefined) {
const result = await verifyRole({}, {}, { req });
expect(result).toEqual({
role: "",
isAuthorized: false,
error: "Invalid token",
});
} else {
throw new Error("verifyRole is undefined");
}
});
});

0 comments on commit 4341a08

Please sign in to comment.