You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
Use Swagger UI or tools like swagger-jsdoc to auto-generate documentation for your endpoints.
Example for Swagger setup: const swaggerJsdoc = require("swagger-jsdoc"); const swaggerUi = require("swagger-ui-express"); const swaggerOptions = { definition: { openapi: "3.0.0", info: { title: "User API", version: "1.0.0", description: "API documentation for user operations", }, }, apis: ["./routes/*.js"], // Path to your endpoint files }; const specs = swaggerJsdoc(swaggerOptions); app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(specs));
Define a MongoDB schema using Mongoose:
const mongoose = require("mongoose"); const userSchema = new mongoose.Schema({ username: { type: String, required: true, unique: true }, password: { type: String, required: true }, role: { type: String, enum: ["user", "admin"], default: "user" }, }); module.exports = mongoose.model("User", userSchema);
Connect to MongoDB Atlas:
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log("Database connected")) .catch((err) => console.error("Database connection error:", err));
Use bcrypt to hash passwords:
const bcrypt = require("bcrypt"); async function hashPassword(password) { const salt = await bcrypt.genSalt(10); return await bcrypt.hash(password, salt); }
Implement JWT-based authentication:
const jwt = require("jsonwebtoken"); function generateToken(user) { return jwt.sign({ id: user._id, role: user.role }, process.env.JWT_SECRET, { expiresIn: "1h" }); }
Middleware for Role-Based Access Control:
function roleCheck(roles) { return (req, res, next) => { if (!roles.includes(req.user.role)) { return res.status(403).json({ message: "Access Denied" }); } next(); }; }
Validate input with tools like Joi:
const Joi = require("joi"); const registerSchema = Joi.object({ username: Joi.string().required(), password: Joi.string().min(6).required(), }); async function validateRegister(req, res, next) { try { await registerSchema.validateAsync(req.body); next(); } catch (error) { res.status(400).json({ error: error.message }); } }
Implement proper error handling:
app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send({ error: "Something went wrong!" }); });
Beta Was this translation helpful? Give feedback.
All reactions