AI-Tennis-Coach/server/middlewares/auth.js
2025-02-11 11:23:59 +05:30

40 lines
1.3 KiB
JavaScript

import { statusCodes, makeResponse, responseMessages } from '../helper/index.js';
import { verifyToken } from '../helper/index.js';
// Middleware function for authentication
export default async function auth(req, res, next) {
try {
// Retrieve the token from the request headers
const token = req.headers["Authorization"] || req.headers["authorization"];
// Check if token is present or not
if (!token) {
return makeResponse(res, statusCodes.AUTH_ERROR, false, responseMessages.UNAUTHORIZED);
}
// Verify the token using the verifyToken function
const decode = await verifyToken(token, 'access');
// Verify if token is valid or not
if (!decode) {
return makeResponse(res, statusCodes.AUTH_ERROR, false, responseMessages.UNAUTHORIZED);
}
// Check if the decoded token contains an email
if (decode.data?.email == null || decode.data?.email == undefined) {
return makeResponse(res, statusCodes.AUTH_ERROR, false, responseMessages.UNAUTHORIZED);
}
// Attach the user data to the request object
req.user = decode.data;
next();
} catch (err) {
return makeResponse(res, statusCodes.AUTH_ERROR, false, err.message);
}
};