-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
configured user route to hanlde user choice route
- Loading branch information
1 parent
d373510
commit e21ace0
Showing
5 changed files
with
68 additions
and
22 deletions.
There are no files selected for viewing
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,23 +1,32 @@ | ||
const JWT = require("jsonwebtoken"); | ||
const User = require("../models/userModel"); | ||
|
||
const jwtsecret = process.env.JWT_SECRET; | ||
if (!jwtsecret) { | ||
throw new Error("Missing JWt token from env variable"); | ||
throw new Error("Missing JWT token from env variable"); | ||
} | ||
|
||
const isAuthorized = async (req, res, next) => { | ||
const authHeader = req.headers.authorization; | ||
if (!authHeader || !authHeader.startsWith("Bearer")) { | ||
next("Authentication Failed"); | ||
} | ||
const token = authHeader.split(" ")[1]; | ||
module.exports.isAuthorized = async (req, res, next) => { | ||
try { | ||
const payload = JWT.verify(token, jwtsecret); | ||
req.user = { userId: payload.userId }; | ||
next(); | ||
const token = | ||
req.cookie.token || | ||
(req.headers.authorization || "").replace("Bearer", ""); | ||
|
||
// Verify if token is present or not | ||
if (!token) { | ||
console.log(`Missing header token`); | ||
throw new Error(`No token found , please login to generate`); | ||
} | ||
|
||
// verify the jwt token from cookie | ||
const decodeToken = JWT.verify(token, jwtsecret); | ||
|
||
// find and attach user object to the decoded user | ||
req.user = await User.findById(decodeToken.id); | ||
|
||
return next(); | ||
} catch (error) { | ||
return next(new Error("Auth failed")); | ||
console.log(`Error while verifying token`); | ||
|
||
return next(error); | ||
} | ||
}; | ||
|
||
module.exports = isAuthorized; |
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters