Skip to content

Commit

Permalink
push
Browse files Browse the repository at this point in the history
  • Loading branch information
chryzcode committed Jul 29, 2024
1 parent 677d7aa commit 151eeac
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions middleware/authentication.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,27 @@ import { UnauthenticatedError } from "../errors/index.js";
import User from "../models/user.js";

export default async (req, res, next) => {
// check header
// Check header
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith("Bearer")) {
throw new UnauthenticatedError("Authentication invalid");
}

const token = authHeader.split(" ")[1];
const user = await User.findOne({ token: token, verified: true });
if (user) {
try {
const payload = jwt.verify(token, process.env.JWT_SECRET);
// attach the user to the job routes
req.user = { userId: payload.userId, firstName: payload.firstName };

next();
} catch (error) {
try {
const payload = jwt.verify(token, process.env.JWT_SECRET);

// Find the user by ID and check if verified
const user = await User.findOne({ _id: payload.userId, verified: true });
if (!user) {
throw new UnauthenticatedError("Authentication invalid");
}
} else {

// Attach the user to the request object
req.user = { userId: payload.userId, firstName: payload.firstName };
next();
} catch (error) {
throw new UnauthenticatedError("Authentication invalid");
}
};

0 comments on commit 151eeac

Please sign in to comment.