created bacis structure and routes for creating user and logging in
This commit is contained in:
@@ -0,0 +1,2 @@
|
|||||||
|
node_modules
|
||||||
|
.env
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
const mongoose = require("mongoose");
|
||||||
|
const connectDB = async () => {
|
||||||
|
try {
|
||||||
|
const conn = await mongoose.connect(process.env.MONGO_URI);
|
||||||
|
console.log(`MongoDB Connected:${conn.connection.host}`.cyan.underline);
|
||||||
|
} catch (error) {
|
||||||
|
console.log(`Error:${error.message}`.red.underline.bold);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
module.exports = connectDB;
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
const asyncHandler = require("express-async-handler");
|
||||||
|
const bcrypt = require("bcryptjs");
|
||||||
|
const jwt = require("jsonwebtoken");
|
||||||
|
const User = require("../models/userModel");
|
||||||
|
|
||||||
|
// @desc Register a new user
|
||||||
|
// @route /api/users
|
||||||
|
// @access Public
|
||||||
|
const registerUser = asyncHandler(async (req, res) => {
|
||||||
|
const { name, email, password } = req.body;
|
||||||
|
if (!name || !email || !password) {
|
||||||
|
res.status(400);
|
||||||
|
throw new Error("Please include all fields");
|
||||||
|
}
|
||||||
|
const userExists = await User.findOne({ email });
|
||||||
|
|
||||||
|
if (userExists) {
|
||||||
|
res.status(400);
|
||||||
|
throw new Error("User already exists");
|
||||||
|
}
|
||||||
|
const salt = await bcrypt.genSalt(10);
|
||||||
|
const hashedPassword = await bcrypt.hash(password, salt);
|
||||||
|
const user = await User.create({
|
||||||
|
name,
|
||||||
|
email,
|
||||||
|
password: hashedPassword,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (user) {
|
||||||
|
res.status(201).json({
|
||||||
|
_id: user._id,
|
||||||
|
name: user.name,
|
||||||
|
email: user.email,
|
||||||
|
token: generateToken(user._id),
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
res.status(400);
|
||||||
|
throw new error("Inavalid user data");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// @desc Login a user
|
||||||
|
// @route /api/users/login
|
||||||
|
// @access Public
|
||||||
|
const loginUser = asyncHandler(async (req, res) => {
|
||||||
|
const { email, password } = req.body;
|
||||||
|
|
||||||
|
const user = await User.findOne({ email });
|
||||||
|
if (user && (await bcrypt.compare(password, user.password))) {
|
||||||
|
res.status(200).json({
|
||||||
|
_id: user._id,
|
||||||
|
name: user.name,
|
||||||
|
email: user.email,
|
||||||
|
token: generateToken(user._id),
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
res.status(401);
|
||||||
|
throw new Error("Inavalid credentials");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// @desc Get current user
|
||||||
|
// @route /api/users/me
|
||||||
|
// @access Private
|
||||||
|
const getMe = asyncHandler(async (req, res) => {
|
||||||
|
const user = {
|
||||||
|
id:req.user._id,
|
||||||
|
email:req.user.email,
|
||||||
|
name:req.user.name
|
||||||
|
}
|
||||||
|
res.status(200).json(user)
|
||||||
|
});
|
||||||
|
const generateToken = (id) => {
|
||||||
|
return jwt.sign({ id }, process.env.JWT_SECRET, {
|
||||||
|
expiresIn: "30d",
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = { registerUser, getMe, loginUser };
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
const jwt = require("jsonwebtoken");
|
||||||
|
const asyncHandler = require("express-async-handler");
|
||||||
|
const User = require("../models/userModel");
|
||||||
|
|
||||||
|
const protect = asyncHandler(async (req, res, next) => {
|
||||||
|
let token;
|
||||||
|
|
||||||
|
if (
|
||||||
|
req.headers.authorization &&
|
||||||
|
req.headers.authorization.startsWith("Bearer")
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
token = req.headers.authorization.split(" ")[1];
|
||||||
|
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||||
|
req.user = await User.findById(decoded.id).select("-password");
|
||||||
|
|
||||||
|
next();
|
||||||
|
} catch (error) {
|
||||||
|
console.log(error);
|
||||||
|
res.status(401);
|
||||||
|
throw new Error("Not authorized");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
res.status(401);
|
||||||
|
throw new Error("Not authorized");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
module.exports = protect;
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
const errorHandler = (err, req, res, next) => {
|
||||||
|
const statusCode = res.statusCode ? res.statusCode : 500;
|
||||||
|
res.status(statusCode);
|
||||||
|
res.json({
|
||||||
|
message: err.message,
|
||||||
|
stack: process.env.NODE_ENV === "production" ? null : err.stack,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
module.exports = { errorHandler };
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
const mongoose = require("mongoose");
|
||||||
|
|
||||||
|
const userSchema = mongoose.Schema(
|
||||||
|
{
|
||||||
|
name: {
|
||||||
|
type: String,
|
||||||
|
required: [true, "Please add a name"],
|
||||||
|
},
|
||||||
|
email: {
|
||||||
|
type: String,
|
||||||
|
required: [true, "Please add a email"],
|
||||||
|
unique: true,
|
||||||
|
},
|
||||||
|
password: {
|
||||||
|
type: String,
|
||||||
|
required: [true, "Please add a password"],
|
||||||
|
},
|
||||||
|
isAdmin: {
|
||||||
|
type: Boolean,
|
||||||
|
require: true,
|
||||||
|
default: false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamps: true,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
module.exports = mongoose.model("User", userSchema);
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
const express = require("express");
|
||||||
|
const router = express.Router();
|
||||||
|
const {
|
||||||
|
loginUser,
|
||||||
|
registerUser,
|
||||||
|
getMe,
|
||||||
|
} = require("../controllers/userController");
|
||||||
|
const protect = require("../middleware/authMiddleware");
|
||||||
|
|
||||||
|
router.post("/", registerUser);
|
||||||
|
router.post("/login", loginUser);
|
||||||
|
router.get("/me", protect, getMe);
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
const express = require("express");
|
||||||
|
const colors = require("colors");
|
||||||
|
const donenv = require("dotenv").config();
|
||||||
|
const { errorHandler } = require("./middleware/errorMiddleWare");
|
||||||
|
const connectDB = require("./config/db");
|
||||||
|
|
||||||
|
const PORT = process.env.PORT || 5000;
|
||||||
|
|
||||||
|
connectDB();
|
||||||
|
|
||||||
|
const app = express();
|
||||||
|
|
||||||
|
app.use(express.json());
|
||||||
|
app.use(express.urlencoded({ extended: false }));
|
||||||
|
|
||||||
|
app.get("/", (req, res) => {
|
||||||
|
res.json({ message: "Welcome to the support desk API" });
|
||||||
|
});
|
||||||
|
|
||||||
|
app.use("/api/users", require("./routes/userRoutes"));
|
||||||
|
app.use(errorHandler);
|
||||||
|
|
||||||
|
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
|
||||||
Generated
+4396
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,24 @@
|
|||||||
|
{
|
||||||
|
"name": "support-desk",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"description": "",
|
||||||
|
"main": "server.js",
|
||||||
|
"scripts": {
|
||||||
|
"start": "node backend/server.js",
|
||||||
|
"server": "nodemon backend/server.js"
|
||||||
|
},
|
||||||
|
"author": "",
|
||||||
|
"license": "ISC",
|
||||||
|
"dependencies": {
|
||||||
|
"bcryptjs": "^2.4.3",
|
||||||
|
"colors": "^1.4.0",
|
||||||
|
"dotenv": "^16.0.3",
|
||||||
|
"express": "^4.18.2",
|
||||||
|
"express-async-handler": "^1.2.0",
|
||||||
|
"jsonwebtoken": "^8.5.1",
|
||||||
|
"mongoose": "^6.7.5"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"nodemon": "^2.0.20"
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user