From 2a3bd5b686119bb2292f99a29c37281c2feef9ec Mon Sep 17 00:00:00 2001 From: abhudaym <52799877+abhudaym@users.noreply.github.com> Date: Sat, 27 Feb 2021 21:02:46 +0530 Subject: [PATCH] finished user routes --- controllers/hospitalController.js | 70 +++++++++++++++++++++++++++++++ controllers/userController.js | 49 +++++++++++++++++++++- models/hospitalModel.js | 64 ++++++++++++++++++++++++++++ models/userModel.js | 27 ++++++++++-- package-lock.json | 13 ++++++ package.json | 1 + routes/hospitalRoutes.js | 12 ++++++ routes/userRoutes.js | 2 + server.js | 2 + 9 files changed, 235 insertions(+), 5 deletions(-) create mode 100644 controllers/hospitalController.js create mode 100644 models/hospitalModel.js create mode 100644 routes/hospitalRoutes.js diff --git a/controllers/hospitalController.js b/controllers/hospitalController.js new file mode 100644 index 0000000..5e1ac33 --- /dev/null +++ b/controllers/hospitalController.js @@ -0,0 +1,70 @@ +// login / register hospitals +import asyncHandler from "express-async-handler"; +import generateToken from "../utils/generateToken.js"; +import Hospital from "../models/hospitalModel.js"; +import axios from "axios"; + +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, + name: user.name, + email: user.email, + isAdmin: user.isAdmin, + token: generateToken(user._id), + }); + } else { + res.status(401); + throw new Error("Invalid Email or password"); + } +}); + +const registerHospital = asyncHandler(async (req, res) => { + const data = await axios.get(`http://ip-api.com/json`); + const lat = data.data.lat; + const lon = data.data.lon; + const { name, email, password, contactNo, address, availability } = req.body; + + const userExist = await Hospital.findOne({ email }); + + const user = await Hospital.create({ + name, + email, + password, + contactNo, + address, + ambulance: { + availability, + location: { + lat, + lon, + }, + }, + }); + if (userExist) { + res.status(400); + throw new Error("User Already exists!"); + } else { + res.json({ + id: user._id, + name: user.name, + email: user.email, + contactNo: user.contactNo, + address: user.address, + ambulance: user.ambulance, + availability: user.availability, + token: generateToken(user._id), + }); + } +}); + +const getHospitals = asyncHandler(async (req, res) => { + const user = await Hospital.find({}); + res.json(user); +}); + +export { registerHospital, getHospitals }; diff --git a/controllers/userController.js b/controllers/userController.js index b002f1c..f83e802 100644 --- a/controllers/userController.js +++ b/controllers/userController.js @@ -1,16 +1,42 @@ import asyncHandler from "express-async-handler"; import generateToken from "../utils/generateToken.js"; import User from "../models/userModel.js"; +import axios from "axios"; const getUsers = asyncHandler(async (req, res) => { const user = await User.find({}); res.json(user); }); + +const authUser = asyncHandler(async (req, res) => { + const { email, password } = req.body; + + const user = await User.findOne({ email }); + + const check = await user.matchPassword(password); + console.log(check); + if (user && (await user.matchPassword(password))) { + res.json({ + _id: user._id, + name: user.name, + email: user.email, + token: generateToken(user._id), + }); + } else { + res.status(401); + throw new Error("Invalid Email or password"); + } +}); // Update circle // Add user const registerUser = asyncHandler(async (req, res) => { const { name, email, password, email2 } = req.body; + const data = await axios.get(`http://ip-api.com/json`); + const lat = data.data.lat; + const lon = data.data.lon; + console.log(data.data); + const user2 = await User.findOne({ email: email2 }); const userExist = await User.findOne({ email }); @@ -31,6 +57,10 @@ const registerUser = asyncHandler(async (req, res) => { email: user2.email, }, ], + location: { + lat, + lon, + }, }); res.status(201).json({ @@ -39,24 +69,35 @@ const registerUser = asyncHandler(async (req, res) => { email: user.email, circle: user.circle, token: generateToken(user._id), + location: { + lat, + lon, + }, }); } else if (!user2) { const user = await User.create({ name, email, password, + location: { + lat, + lon, + }, }); res.status(201).json({ _id: user._id, name: user.name, email: user.email, token: generateToken(user._id), + location: { + lat, + lon, + }, }); } }); const updateCircle = asyncHandler(async (req, res) => { - // const objCircle = {email: req.body.email} // to update circle, we need to find the user whose circle // needs to be updated and then use spread operator to // populate the existing array and add the new user. @@ -75,7 +116,11 @@ const updateCircle = asyncHandler(async (req, res) => { name: user.name, email: user.email, circle: user.circle, + location: { + lat, + lon, + }, }); }); -export { getUsers, registerUser, updateCircle }; +export { getUsers, registerUser, updateCircle, authUser }; diff --git a/models/hospitalModel.js b/models/hospitalModel.js new file mode 100644 index 0000000..e5d219f --- /dev/null +++ b/models/hospitalModel.js @@ -0,0 +1,64 @@ +import mongoose from "mongoose"; +import bcrypt from "bcryptjs"; + +const hospitalSchema = mongoose.Schema( + { + name: { + type: String, + required: true, + }, + address: { + type: String, + required: true, + }, + contactNo: { + type: Number, + required: true, + }, + email: { + type: String, + required: true, + }, + password: { + type: String, + required: true, + }, + ambulance: [ + { + availabilty: { + type: Boolean, + required: false, + }, + location: { + lat: { + type: String, + required: false, + }, + lon: { + type: String, + required: false, + }, + }, + }, + ], + }, + { + timestamps: true, + } +); + +hospitalSchema.methods.matchPassword = async function (enteredPassword) { + return await bcrypt.compare(enteredPassword, this.password); +}; + +hospitalSchema.pre("save", async function (next) { + if (!this.isModified("password")) { + next(); + } + + const salt = await bcrypt.genSalt(10); + this.password = await bcrypt.hash(this.password, salt); +}); + +const Hospital = mongoose.model("Hospital", hospitalSchema); +export default Hospital; diff --git a/models/userModel.js b/models/userModel.js index 13dd0bc..69064f3 100644 --- a/models/userModel.js +++ b/models/userModel.js @@ -1,4 +1,5 @@ import mongoose from "mongoose"; +import bcrypt from "bcryptjs"; const userSchema = mongoose.Schema( { @@ -32,14 +33,34 @@ const userSchema = mongoose.Schema( }, }, ], - // medicalDocs: { - // id: - // } + location: { + lat: { + type: String, + required: false, + }, + lon: { + type: String, + required: false, + }, + }, }, { timestamps: true, } ); +userSchema.methods.matchPassword = async function (enteredPassword) { + return await bcrypt.compare(enteredPassword, this.password); +}; + +userSchema.pre("save", async function (next) { + if (!this.isModified("password")) { + next(); + } + + const salt = await bcrypt.genSalt(10); + this.password = await bcrypt.hash(this.password, salt); +}); + const User = mongoose.model("User", userSchema); export default User; diff --git a/package-lock.json b/package-lock.json index 480290c..3a993fa 100644 --- a/package-lock.json +++ b/package-lock.json @@ -100,6 +100,14 @@ "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", "integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI=" }, + "axios": { + "version": "0.21.1", + "resolved": "https://registry.npmjs.org/axios/-/axios-0.21.1.tgz", + "integrity": "sha512-dKQiRHxGD9PPRIUNIWvZhPTPpl1rf/OxTYKsqKUDjBwYylTvV7SjSHJb9ratfyzM6wCdLCOYLzs73qpg5c4iGA==", + "requires": { + "follow-redirects": "^1.10.0" + } + }, "balanced-match": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", @@ -562,6 +570,11 @@ } } }, + "follow-redirects": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.13.2.tgz", + "integrity": "sha512-6mPTgLxYm3r6Bkkg0vNM0HTjfGrOEtsfbhagQvbxDEsEkpNhw582upBaoRZylzen6krEmxXJgt9Ju6HiI4O7BA==" + }, "forwarded": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.1.2.tgz", diff --git a/package.json b/package.json index 8c8ec4d..b5809c9 100644 --- a/package.json +++ b/package.json @@ -14,6 +14,7 @@ "author": "", "license": "ISC", "dependencies": { + "axios": "^0.21.1", "bcryptjs": "^2.4.3", "dotenv": "^8.2.0", "express": "^4.17.1", diff --git a/routes/hospitalRoutes.js b/routes/hospitalRoutes.js new file mode 100644 index 0000000..cc5ff4b --- /dev/null +++ b/routes/hospitalRoutes.js @@ -0,0 +1,12 @@ +import express from "express"; +import { + getHospitals, + registerHospital, +} from "../controllers/hospitalController.js"; +import { protect } from "../middleware/authMiddleware.js"; + +const router = express.Router(); +router.route("/").post(registerHospital).get(getHospitals); +// router.post("/login", authUser); + +export default router; diff --git a/routes/userRoutes.js b/routes/userRoutes.js index fc387ac..4a67612 100644 --- a/routes/userRoutes.js +++ b/routes/userRoutes.js @@ -3,11 +3,13 @@ import { getUsers, registerUser, updateCircle, + authUser, } from "../controllers/userController.js"; import { protect } from "../middleware/authMiddleware.js"; const router = express.Router(); router.route("/").get(getUsers).post(registerUser); router.route("/circle").post(protect, updateCircle); +router.post("/login", authUser); export default router; diff --git a/server.js b/server.js index 414ce02..581f257 100644 --- a/server.js +++ b/server.js @@ -3,6 +3,7 @@ import dotenv from "dotenv"; import connectDB from "./config/db.js"; import User from "./models/userModel.js"; import userRoutes from "./routes/userRoutes.js"; +import hospitalRoutes from "./routes/hospitalRoutes.js"; import asyncHandler from "express-async-handler"; @@ -15,6 +16,7 @@ const app = express(); app.use(express.json()); app.use("/api/user", userRoutes); +app.use("/api/hospital", hospitalRoutes); app.get("/", (req, res) => { res.send("API is running!");