MERN_sample_app/middlewares/auth/index.js

29 lines
752 B
JavaScript

import admin from "../../services/auth/index.js";
const getAuthToken = (req, res, next) => {
if (
req.headers.authorization &&
req.headers.authorization.split(" ")[0] === "Bearer"
) {
req.authToken = req.headers.authorization.split(" ")[1];
} else {
req.authToken = null;
}
next();
};
const authenticationChecker = (req, res, next) => {
getAuthToken(req, res, async () => {
try {
const { authToken } = req;
const userInfo = await admin.auth().verifyIdToken(authToken);
req.authId = userInfo.uid;
return next();
} catch (e) {
return res
.status(401)
.json({ error: "You are not authorized to make this request." });
}
});
};
export default authenticationChecker;