Skip to content

Commit

Permalink
feat: validate each role sending request
Browse files Browse the repository at this point in the history
  • Loading branch information
lcaohoanq committed Jul 3, 2024
1 parent e0fcc22 commit a3e83b4
Show file tree
Hide file tree
Showing 4 changed files with 74 additions and 6 deletions.
16 changes: 14 additions & 2 deletions src/modules/protectRouting/protect.middlewares.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,19 @@
import { NextFunction, Request, Response } from "express";
import { accessTokenValidator } from "../user/user.middlewares";
import { ParamSchema, checkSchema } from "express-validator";
import {
accessTokenValidator,
accessTokenValidatorV2,
} from "../user/user.middlewares";
import { getOpenRoutes } from "./protect.utils";

export const paramSchema: ParamSchema = {
customSanitizer: {
options: async (value) => {
return escape(value);
},
},
};

export const protectRouterValidator = (
req: Request,
res: Response,
Expand All @@ -15,5 +27,5 @@ export const protectRouterValidator = (
}

// else validate access_token
accessTokenValidator(req, res, next);
accessTokenValidatorV2(req, res, next);
};
1 change: 0 additions & 1 deletion src/modules/protectRouting/protect.routes.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { Router } from "express";
import { accessTokenValidator } from "../user/user.middlewares";
import { protectRouterValidator } from "./protect.middlewares";

const protectRouter = Router();
Expand Down
58 changes: 58 additions & 0 deletions src/modules/user/user.middlewares.ts
Original file line number Diff line number Diff line change
Expand Up @@ -986,6 +986,64 @@ export const accessTokenValidator = validate(
),
);

export const accessTokenValidatorV2 = validate(
checkSchema(
{
authorization: {
...paramSchema,
trim: true,
custom: {
options: async (value: string, { req }) => {
const access_token = value.split(" ")[1];
// if do not have access_token, throw error
// because we already passed openRoutes
if (!access_token) {
throw new ErrorWithStatus({
message: USER_MESSAGES.ACCESS_TOKEN_IS_REQUIRED,
status: HTTP_STATUS.UNAUTHORIZED,
});
}

// if have access_token, validate it
try {
const decoded_authorization = await verifyToken({
token: access_token,
secretOrPublickey: process.env
.JWT_SECRET_ACCESS_TOKEN as string,
});
(req as Request).decoded_authorization =
decoded_authorization;

// find the role by user_id
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");
}
} catch (error) {
throw new ErrorWithStatus({
message: capitalize(
(error as JsonWebTokenError).message,
),
status: HTTP_STATUS.UNAUTHORIZED,
});
}
return true;
},
},
},
},
["headers"],
),
);

export const refreshTokenValidator = validate(
checkSchema(
{
Expand Down
5 changes: 2 additions & 3 deletions src/modules/user/user.services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import "dotenv/config";
import { capitalize, omit } from "lodash";
import { ObjectId } from "mongodb";
import otpGenerator from "otp-generator";
import { UserList } from "~/constants/user.type";
import databaseService from "~/database/database.services";
import { capitalizePro } from "~/utils/capitalize";
import decrypt, { encrypt, hashPassword } from "~/utils/crypto";
Expand All @@ -19,7 +20,6 @@ import {
UpdateMeReqBody,
} from "./user.requests";
import User from "./user.schema";
import { UserList } from "~/constants/user.type";

class UsersService {
private decodeRefreshToken(refresh_token: string) {
Expand Down Expand Up @@ -145,10 +145,9 @@ class UsersService {
return Boolean(user);
}

async findUser(user_id: string, password: string) {
async findUserByID(user_id: string) {
const user = await databaseService.users.findOne({
_id: new ObjectId(user_id),
password: hashPassword(password),
});
return user;
}
Expand Down

0 comments on commit a3e83b4

Please sign in to comment.