-
Notifications
You must be signed in to change notification settings - Fork 262
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix(backend): resolve issues in auth API endpoints, JWT strategy, and…
… MongoDB connection (#873) ### Backend Fixes and Enhancements ### Issue The backend code had several issues that prevented proper functioning of API endpoints, including incorrect file naming, invalid routes, and improper authentication handling. These issues resulted in failure to connect to the database and authenticate users. ### Description of Changes 1. **Corrected Auth Router Endpoint:** - The route for the `auth` router API endpoint was incorrect. - Fixed the route to align with the intended functionality. 2. **Updated Logout Request Method:** - Changed the HTTP method for the `logout` API from `GET` to `POST`. - This follows REST best practices. 3. **Minor Fixes in `authController.js`:** - Corrected HTTP status codes for consistent responses. - Added a **JWT token** to the response payload upon successful login. - Removed unnecessary console log statements for cleaner code. - Improved response messages for better clarity. 4. **Fixed JWT Auth Strategy:** - The `getUser` and `logout` API endpoints were failing because the JWT strategy only checked for tokens in **cookies**. - Updated the strategy to validate tokens from the `Authorization` header (bearer token). --- ### **Files Changed** 1. `app.js` - Updated the authRouter configuration by ensuring it is correctly mounted at `/api/auth`. This ensures all authentication-related endpoints are accessible under this base route. 2. `authRouter.js` - Fixed incorrect endpoint routes. - Updated logout method to `POST`. 3. `authController.js` - Updated status codes, response payloads, and removed unnecessary logs. 4. `jwt.strategy.js` - Modified to check for tokens in the `Authorization` header. --- ### Screenshots of API endpoints testing 1. **API Testing: `api/auth/signin`** - ![Signin](https://github.com/user-attachments/assets/ffa092d3-a6e2-4aef-9440-724f3899cc77) 2. **API Testing: `api/auth/signup`** - ![Signup](https://github.com/user-attachments/assets/a4a8d0c1-2b59-4108-a31a-02e1d9e2d565) 3. **API Testing: `api/auth/user`** - ![User](https://github.com/user-attachments/assets/cfb7e646-8dc4-420f-83b3-3f753f6dbcb5) 4. **API Testing: `api/auth/logout`** - ![Logout](https://github.com/user-attachments/assets/71353b61-3dd1-4ff9-b0e0-9306ce93726b) --- ## Checklist <!-- [X] - put a cross/X inside [] to check the box --> - [X] I have gone through the [contributing guide](https://github.com/Anjaliavv51/Retro) - [X] I have updated my branch and synced it with project `main` branch before making this PR - [X] I have performed a self-review of my code - [X] I have tested the changes thoroughly before submitting this pull request. - [X] I have provided relevant issue numbers, screenshots, and videos after making the changes. - [X] I have commented my code, particularly in hard-to-understand areas. @Anjaliavv51 please review this PR. Let me know if further adjustments are needed. Thank you for reviewing this PR! 🙌
- Loading branch information
Showing
6 changed files
with
105 additions
and
67 deletions.
There are no files selected for viewing
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 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
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,24 +1,31 @@ | ||
const JWT = require("jsonwebtoken"); | ||
const JWT = require('jsonwebtoken'); | ||
|
||
// router level middleware function | ||
// Middleware to check for a valid JWT token | ||
const jwtAuth = (req, res, next) => { | ||
|
||
// get cookie token(jwt token generated using json.sign()) form the request | ||
const token = ( req.cookies?.token) || null; | ||
// Check if the token is in the cookies or the Authorization header | ||
const token = req.cookies?.token || req.headers?.authorization?.split(' ')[1]; // Bearer <token> | ||
|
||
// return response if there is no token(jwt token attached with cookie) | ||
if (!token) { | ||
return res.status(400).json({ success: false, message: "NOT authorized" }); | ||
return res.status(400).json({ | ||
success: false, | ||
message: 'Not authorized, no token provided', | ||
}); | ||
} | ||
|
||
// verify the token | ||
try { | ||
// Verify the token using the secret key | ||
const payload = JWT.verify(token, process.env.SECRET); | ||
|
||
// Attach the payload data to the request object (i.e., user data) | ||
req.user = { id: payload.id, email: payload.email }; | ||
|
||
next(); | ||
} catch (error) { | ||
return res.status(400).json({ success: false, message: error.message }); | ||
return res.status(400).json({ | ||
success: false, | ||
message: 'Token verification failed: ' + error.message, | ||
}); | ||
} | ||
next(); | ||
}; | ||
|
||
module.exports = jwtAuth; |
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,21 +1,19 @@ | ||
const express = require("express"); | ||
const express = require('express'); | ||
const authRouter = express.Router(); | ||
const jwtAuth = require("../middleware/jwtAuth.js"); | ||
const jwtAuth = require('../middleware/jwtAuth.js'); | ||
|
||
const { | ||
signUp, | ||
signIn, | ||
forgotPassword, | ||
resetPassword, | ||
getUser, | ||
logout | ||
} = require("../controller/authController.js"); | ||
logout, | ||
} = require('../controller/authController.js'); | ||
|
||
authRouter.post("/signup", signUp); | ||
authRouter.post("/signin", signIn); | ||
|
||
|
||
authRouter.get("/user", jwtAuth, getUser); | ||
authRouter.get("/logout", jwtAuth, logout); | ||
authRouter.post('/signup', signUp); | ||
authRouter.post('/signin', signIn); | ||
authRouter.post('/logout', jwtAuth, logout); | ||
authRouter.get('/user', jwtAuth, getUser); | ||
|
||
module.exports = authRouter; |