Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Main #2

Open
wants to merge 8 commits into
base: feedback
Choose a base branch
from
Open

Main #2

wants to merge 8 commits into from

Conversation

sibananda15
Copy link
Collaborator

No description provided.

github-classroom bot and others added 8 commits January 12, 2025 15:25
…nd preferences

- Implemented validation middleware for email and password in registration
- Added validation for preferences input
- Enhanced error handling for invalid inputs and unauthorized access
- Updated folder structure to include separate validation middleware
- Improved code organization for better readability and maintainability
exports.registerUser = async (req, res, next) => {
try {
const { username, password } = req.body;
if (!username || !password) throw new Error("Username and password required");

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using throw new Error("Username and password required") will result in a generic 500 status code. Consider using return res.status(400).json({ error: "Username and password required" }); for consistency and to indicate it's a client-side error.

try {
const { username, password } = req.body;
const user = await User.findOne({ username });
if (!user) throw new Error("Invalid username or password");

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The error message "Invalid username or password" is not specific, it could hint at either a nonexistent user or incorrect password, which is good from a security perspective. Ensure the error handling middleware captures and logs specifics separately for debug purposes.

if (!user) throw new Error("Invalid username or password");

const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) throw new Error("Invalid username or password");

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider using a more specific error type for authentication failures instead of throwing a generic Error. This allows for more precise error handling or logging upstream.

const apiKey = process.env.NEWS_API_KEY;

const response = await axios.get(`https://newsapi.org/v2/top-headlines`, {
params: {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The URL for the news API is hardcoded. Consider storing this URL in a configuration file or as an environment variable for easier maintenance and greater flexibility.

},
});

res.json(response.data);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of directly returning the response from the third-party API, consider adding error handling to provide more informative feedback to the client in case the API request fails.

} catch (err) {
next(err);
}
};

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's a good practice to end files with a newline character. This can prevent potential issues with some tools and version control systems when concatenating files.

await Preference.findOneAndUpdate(
{ username },
{ username, preferences },
{ upsert: true, new: true }

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider specifying the runValidators option in the findOneAndUpdate method to ensure that any validation rules in the Mongoose model are executed when updating the document. For example:

{ upsert: true, new: true, runValidators: true }

const jwt = require("jsonwebtoken");

module.exports = (req, res, next) => {
const token = req.headers["authorization"];

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider checking for token prefix Bearer and splitting the token accordingly to only take the token value. Currently, this assumes only a space separation, which might not cater for the token type prefix.


module.exports = (req, res, next) => {
const token = req.headers["authorization"];
if (!token) return res.status(401).json({ error: "Access denied" });

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider adding a more detailed error message to help with troubleshooting, such as indicating that the token header was not provided.

req.user = decoded;
next();
} catch (err) {
res.status(401).json({ error: "Invalid token" });

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To provide more security information, consider logging the error message err.message for server-side diagnostics, ensuring sensitive information is not exposed in production.

const { body, validationResult } = require("express-validator");

exports.validateRegistration = [
body("username").isEmail().withMessage("Invalid email format"),

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The function isEmail() is used to validate the username field. If username is intended to allow emails only, consider renaming the field to email for better clarity. Alternatively, ensure that the requirement is documented elsewhere.

}
next();
},
];

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider adding a newline at the end of the file to adhere to EOF (End of file) standards, which can help prevent potential issues with file concatenation in some systems.

@@ -0,0 +1,9 @@

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unnecessary blank line at the start of the file. Consider removing it.

preferences: { type: Object, required: true },
});

module.exports = mongoose.model("Preference", preferenceSchema);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's a good practice to add a newline at the end of the file for compatibility with various text editors and version control tools. Consider adding one.

username: { type: String, required: true, unique: true },
password: { type: String, required: true },
});
module.exports = mongoose.model("User", userSchema);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is good practice to end files with a newline. Please add a newline at the end of the file to avoid potential issues with some text processing tools and version control systems.

router.post("/login", loginUser);


module.exports = router;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add a newline at the end of the file to comply with POSIX standards and prevent potential issues with certain tools processing the file.


router.get("/", authMiddleware, fetchNews);

module.exports = router;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The file is missing a newline at the end. Consider adding a newline to adhere to POSIX standards, which can help avoid issues with certain tools and ensure consistency across files.


router.post("/", authMiddleware, validatePreferences, savePreferences);

module.exports = router;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is a good practice to end files with a newline character. Please add a newline at the end of the file.

@@ -0,0 +1,29 @@
require("dotenv").config();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please ensure the .env file is listed in the .gitignore to avoid exposing sensitive data.

const preferenceRoutes = require("./routes/preferenceRoutes");

const app = express();
app.use(bodyParser.json());

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The body-parser package is now a part of express. You can use express.json() directly instead of importing body-parser. This would eliminate the need for the body-parser dependency.


// Start Server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider handling unhandled promise rejections or exceptions, particularly for asynchronous operations like dbConnect(), to ensure proper error handling and server stability.

useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log("Connected to MongoDB");

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's generally not a good practice to use console.log for logging in production code. Consider using a logging library like winston or morgan for more control over logging levels and outputs.

}
};

module.exports = dbConnect;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider adding a newline at the end of the file to adhere to POSIX standards. This can help avoid potential issues with some text processing tools that expect a newline at the end of the file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants