ansopedia / user-service

The Ansopedia User Service is a backend service responsible for managing user accounts and authentication within the Ansopedia learning platform. It provides functionalities like authentication & authorization, profile management.
4 stars 2 forks source link

Refactor JWT Token Verification Logic in `auth.middleware.ts` #59

Open sanjaysah101 opened 3 days ago

sanjaysah101 commented 3 days ago

Description

Refactor the JWT token verification logic so that the authentication service is called directly, and the logic to verify the JWT token is moved into the authentication service. This will simplify the middleware by delegating both user retrieval and token verification to the authentication service.

Key Details:

Tasks:

  1. Update the parseUser method in auth.middleware.ts:
    • Instead of verifying the JWT token in the middleware, directly call the AuthService.
    • Move the JWT verification logic into the AuthService.verifyToken method.
  2. Ensure that both access and refresh token types are handled correctly by the AuthService.
  3. Test the changes to ensure that the middleware functions correctly after the refactor.

Code Reference (auth.middleware.ts):

const parseUser = async (req: Request, _: Response, next: NextFunction, tokenType: 'access' | 'refresh') => {
  try {
    const authHeader = req.headers.authorization;

    if (authHeader == null || authHeader === '') throw new Error(ErrorTypeEnum.enum.NO_AUTH_HEADER);

    const token = extractTokenFromBearerString(authHeader);
    let user: Auth;

    // Update logic: Call AuthService directly to handle both token verification and user retrieval
    user = await AuthService.verifyToken(token, tokenType);

    req.body.loggedInUser = { ...user, userId: user.userId.toString() };

    next();
  } catch (error) {
    next(error);
  }
};

Related: #55

kk7188048 commented 2 days ago

/attempt