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
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:
Currently, the JWT token is verified first, and then the AuthService is called to fetch the user.
Refactor the code to directly call the authentication service, which will handle both JWT token verification and user retrieval.
This will involve updating the auth.middleware.ts file, specifically the parseUser method.
Tasks:
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.
Ensure that both access and refresh token types are handled correctly by the AuthService.
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);
}
};
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:
AuthService
is called to fetch the user.auth.middleware.ts
file, specifically theparseUser
method.Tasks:
parseUser
method inauth.middleware.ts
:AuthService
.AuthService.verifyToken
method.access
andrefresh
token types are handled correctly by theAuthService
.Code Reference (
auth.middleware.ts
):Related: #55