Commit 73cfa314 authored by Rishad M.H.M's avatar Rishad M.H.M

Merge branch 'IT20613686/login-and-register-backend' into 'master'

Login and register backend endpoints

See merge request !1
parents ea449fbb 1e1c13f0
...@@ -2,6 +2,8 @@ ...@@ -2,6 +2,8 @@
# dependencies # dependencies
/node_modules /node_modules
BACKEND/node_modules/
frontend/node_modules/
/.pnp /.pnp
.pnp.js .pnp.js
......
//secrets
PORT=8070
MONGODB_URL=mongodb+srv://Rishan:rishan123@cluster0.b06jc.mongodb.net/InstaHire_db?retryWrites=true&w=majority
NODE_ENV=development
JWT_SECRET=verve123
\ No newline at end of file
const mongoose = require("mongoose");
//function to connect mongo db
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGODB_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log(`Mongo db connected : ${conn.connection.host}`);
} catch (error) {
console.error(`Error:${error.message}`);
process.exit();
}
};
module.exports = connectDB;
//error handling
const asyncHandler = require("express-async-handler");
const User = require("../models/userModels");
const generateToken = require("../utils/generateToken");
//@description Register new user
//@route POST /api/users/
//@access Public
const registerUser = asyncHandler(async (req, res) => {
const { firstName, lastName, email, password } = req.body;
const userExist = await User.findOne({ email });
if (userExist) {
res.status(400);
throw new Error("user already exists ");
}
const user = await User.create({
firstName,
lastName,
email,
password,
});
if (user) {
res.status(201).json({
_id: user._id,
firstName: user.firstName,
lastName: user.lastName,
email: user.email,
isAdmin: user.isAdmin,
token: generateToken(user._id),
});
} else {
res.status(400);
throw new Error("Error occured ");
}
});
//@description Auth the user
//@route POST /api/users/login
const authUser = asyncHandler(async (req, res) => {
const { email, password } = req.body;
const user = await User.findOne({ email });
if (user && (await user.matchPassword(password))) {
res.json({
_id: user._id,
firstName: user.firstName,
lastName: user.lastName,
email: user.email,
isAdmin: user.isAdmin,
token: generateToken(user._id),
});
} else {
res.status(401);
throw new Error("Invalid Email or Password");
}
});
// @desc GET user profile
// @route GET /api/users/profile
// @access Private
module.exports = { registerUser, authUser };
const User = require("../models/userModels");
const jwt = require("jsonwebtoken");
const asyncHandler = require("express-async-handler");
//its protect our api over unauthorized access
const protect = asyncHandler(async (req, res, next) => {
let token;
if (
req.headers.authorization &&
//from front end gives the token
req.headers.authorization.startsWith("Bearer")
) {
try {
token = req.headers.authorization.split(" ")[1];
//decodes token id
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = await User.findById(decoded.id).select("password");
next();
} catch (error) {
res.status(401);
throw new Error("Not authorized, token failed");
}
}
if (!token) {
res.status(401);
throw new Error("Not authorized, no token");
}
});
module.exports = protect;
//if router doesnt find
//errors occured
const notFound = (req, res, next) => {
const error = new Error(`Not Found - ${req.originalUrl}`);
res.status(404);
next(error);
};
//general errors
const errorHandler = (err, req, res, next) => {
const statusCode = res.statusCode === 200 ? 500 : res.statusCode;
res.status(statusCode);
res.json({
message: err.message,
stack: process.env.NODE_ENV === "production" ? null : err.stack,
});
};
module.exports = { notFound, errorHandler };
//what type data user going to have
//user databse--> save
const mongoose = require("mongoose");
const bcrypt = require("bcryptjs");
//user schema
const userSchema = mongoose.Schema(
{
firstName: {
type: String,
required: true,
},
lastName: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
isAdmin: {
type: Boolean,
required: true,
default: false,
},
},
//when was created in database feild &updated
{
timestamps: true,
}
);
//encrypt the password
userSchema.pre("save", async function (next) {
if (!this.isModified("password")) {
next();
}
//more char secure max
const salt = await bcrypt.genSalt(10);
this.password = await bcrypt.hash(this.password, salt);
});
//decrypt the password
//compare the entered p/w and database p/w
userSchema.methods.matchPassword = async function (enteredPassword) {
return await bcrypt.compare(enteredPassword, this.password);
};
const User = mongoose.model("User", userSchema);
module.exports = User;
This source diff could not be displayed because it is too large. You can view the blob instead.
{
"name": "backend",
"version": "1.0.0",
"description": "E market management system",
"main": "index.js",
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js"
},
"author": "Rishad",
"license": "ISC",
"dependencies": {
"alert": "^5.0.10",
"bcryptjs": "^2.4.3",
"cors": "^2.8.5",
"dotenv": "^16.0.0",
"express": "^4.17.2",
"express-async-handler": "^1.2.0",
"fs-extra": "^11.1.1",
"jsonwebtoken": "^9.0.0",
"mongoose": "^6.2.1",
"multer": "^1.4.4",
"nodemon": "^2.0.15",
"popups": "^1.1.3",
"window": "^4.2.7"
}
}
const express = require("express");
const {
registerUser,
authUser,
} = require("../controllers/userControllers");
// const protect = require("../middlewares/authMiddleware");
const User = require("../models/userModels");
const router = express.Router();
router.route("/register").post(registerUser);
router.route("/login").post(authUser);
// router.route("/profile").post(protect, updateUserProfile);
//.route("/:id")
// router.route("/:id").delete(protect, DeleteProfile);
router.route("/view").get((req, res) => {
User.find()
.then((users) => {
res.json(users);
})
.catch((err) => {
console.log(err);
});
});
module.exports = router;
const express = require("express");
const mongoose = require("mongoose");
const bodyparser = require("body-parser");
const cors = require("cors");
const connectDB = require("./config/db");
const dotenv = require("dotenv");
const userRoutes = require("./routes/userRoutes");
// const hardwareRouter = require("./routes/hardwares.js");
// const hardwareItemRouter = require("./routes/hardwareItems.js");
const { notFound, errorHandler } = require("./middlewares/errorMiddleware");
const app = express();
dotenv.config();
connectDB();
app.use(express.json());
app.use(cors());
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({ extended: true }));
app.use('/uploads', express.static('./uploads'));
app.use("/api/users", userRoutes);
// app.use("/hardware", hardwareRouter);
// app.use("/hardwareItem", hardwareItemRouter);
app.use(notFound);
app.use(errorHandler);
const PORT = process.env.PORT || 8070;
app.listen(8070, console.log(`server started on port ${PORT}`));
\ No newline at end of file
//open standard used to share security information between two parties — a client and a server
const jwt = require("jsonwebtoken");
const generateToken = (id) => {
return jwt.sign({ id }, process.env.JWT_SECRET, {
expiresIn: "30d",
});
};
module.exports = generateToken;
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment