-
Notifications
You must be signed in to change notification settings - Fork 0
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
base: feedback
Are you sure you want to change the base?
Main #2
Conversation
…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"); |
There was a problem hiding this comment.
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"); |
There was a problem hiding this comment.
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"); |
There was a problem hiding this comment.
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: { |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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); | ||
} | ||
}; |
There was a problem hiding this comment.
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 } |
There was a problem hiding this comment.
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"]; |
There was a problem hiding this comment.
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" }); |
There was a problem hiding this comment.
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" }); |
There was a problem hiding this comment.
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"), |
There was a problem hiding this comment.
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(); | ||
}, | ||
]; |
There was a problem hiding this comment.
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 @@ | |||
|
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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(); |
There was a problem hiding this comment.
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()); |
There was a problem hiding this comment.
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}`)); |
There was a problem hiding this comment.
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"); |
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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.
No description provided.