Eric Whale

Add authorization middleware using jwt

......@@ -2,7 +2,7 @@ const bcrypt = require("bcryptjs");
// handles "exception" inside of async express routes
const asyncHandler = require("express-async-handler");
const User = require("../models/userModel");
const jwtGenerator = require("../config/jwt");
const { jwtGenerator } = require("../config/jwt");
// @desc Signup new user
// @route POST /api/users
......@@ -73,7 +73,7 @@ const loginUser = asyncHandler(async (req, res) => {
// @route GET /api/users/self
// @access Private
const getSelf = asyncHandler(async (req, res) => {
// Not figured out
// TODO
res.status(200).json(req.user);
});
......
......@@ -2,7 +2,9 @@ const jwt = require("jsonwebtoken");
const jwtGenerator = (id) => {
// https://github.com/auth0/node-jsonwebtoken
const token = jwt.sign({ id }, JWT_SECRET, { expiresIn: "2 days" });
const token = jwt.sign({ id }, process.env.JWT_SECRET, {
expiresIn: "2 days",
});
return token;
};
......
const jwt = require("jsonwebtoken");
const asyncHandler = require("express-async-handler");
const User = require("../models/userModel");
const authHandler = (err, req, res, next) => {
next();
};
const authHandler = asyncHandler(async (req, res, next) => {
// Check if token exists
if (!req.headers.authorization) {
res.status(401);
throw new Error("Not authorized");
}
// Evaluate the token
const token = req.headers.authorization.split(" ")[1];
const decoded = jwt.verify(
token,
process.env.JWT_SECRET,
function (err, decoded) {
if (err) {
res.status(401);
throw new Error("Not authorized");
}
return decoded;
}
);
const user = await User.findById(decoded.id).select("-password");
req.user = user;
return next();
});
module.exports = { authHandler };
......
......@@ -20,5 +20,4 @@ const userSchema = mongoose.Schema(
}
);
const userModel = mongoose.model("User", userSchema);
module.exports = userModel;
module.exports = mongoose.model("User", userSchema);
......
const express = require("express");
const router = express.Router();
const { signupUser, loginUser, getSelf } = require("../actions/userActions");
const { authHandler } = require("../middleware/authMiddleware");
router.post("/", signupUser);
router.post("/login", loginUser);
router.get("/self", getSelf);
router.get("/self", authHandler, getSelf);
module.exports = router;
......