Skip to content

Commit

Permalink
refactor: moving check role to protect route utils
Browse files Browse the repository at this point in the history
  • Loading branch information
lcaohoanq committed Jul 4, 2024
1 parent a3e83b4 commit 0b663c6
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 6 deletions.
1 change: 1 addition & 0 deletions src/modules/protectRouting/protect.messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ export const PROTECT_MESSAGES = {
ROLE_ADMIN: "You are admin",
ROLE_CUSTOMER: "You are customer",
ROLE_EMPLOYEE: "You are employee",
ROLE_NOT_FOUND: "Role not found",
UNAUTHORIZED: "Unauthorized",
MISSING_ACCESS_TOKEN: "Missing access token",
} as const;
12 changes: 12 additions & 0 deletions src/modules/protectRouting/protect.utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { UserRole } from "../user/user.enum";

const routes: Module[] = require("./mapRouteWithRole.json");

// Interface for a Route object within a module
Expand Down Expand Up @@ -28,3 +30,13 @@ export function getOpenRoutes(): string[] {

return openRoutes;
}

export function checkRole(role: UserRole): void {
if (role === UserRole.Admin) {
console.log("User are Admin");
} else if (role === UserRole.Customer) {
console.log("User are Customer");
} else {
console.log("User are Employee");
}
}
15 changes: 9 additions & 6 deletions src/modules/user/user.middlewares.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import { isValidPhoneNumberForCountry, validate } from "~/utils/validation";
import { OTP_STATUS } from "../otp/otp.enum";
import { OTP_MESSAGES } from "../otp/otp.messages";
import otpService from "../otp/otp.services";
import { PROTECT_MESSAGES } from "../protectRouting/protect.messages";
import { checkRole } from "../protectRouting/protect.utils";
import { NoticeUser, UserRole, UserVerifyStatus } from "./user.enum";
import { LoginRequestBody, TokenPayload } from "./user.requests";
import usersService from "./user.services";
Expand Down Expand Up @@ -1018,15 +1020,16 @@ export const accessTokenValidatorV2 = validate(
const user = await usersService.findUserByID(
decoded_authorization.user_id,
);

const role = user?.role;

if (role === UserRole.Admin) {
console.log("User is Admin");
} else if (role === UserRole.Customer) {
console.log("User is Customer");
} else {
console.log("User is Employee");
if (!role) {
throw new ErrorWithStatus({
message: PROTECT_MESSAGES.ROLE_NOT_FOUND,
status: HTTP_STATUS.UNAUTHORIZED,
});
}
checkRole(role);
} catch (error) {
throw new ErrorWithStatus({
message: capitalize(
Expand Down

0 comments on commit 0b663c6

Please sign in to comment.