Skip to content

Commit

Permalink
finished user routes
Browse files Browse the repository at this point in the history
  • Loading branch information
abhudaym committed Feb 27, 2021
1 parent a59a885 commit 2a3bd5b
Show file tree
Hide file tree
Showing 9 changed files with 235 additions and 5 deletions.
70 changes: 70 additions & 0 deletions controllers/hospitalController.js
Original file line number Diff line number Diff line change
@@ -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 };
49 changes: 47 additions & 2 deletions controllers/userController.js
Original file line number Diff line number Diff line change
@@ -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 });
Expand All @@ -31,6 +57,10 @@ const registerUser = asyncHandler(async (req, res) => {
email: user2.email,
},
],
location: {
lat,
lon,
},
});

res.status(201).json({
Expand All @@ -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.
Expand All @@ -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 };
64 changes: 64 additions & 0 deletions models/hospitalModel.js
Original file line number Diff line number Diff line change
@@ -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;
27 changes: 24 additions & 3 deletions models/userModel.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import mongoose from "mongoose";
import bcrypt from "bcryptjs";

const userSchema = mongoose.Schema(
{
Expand Down Expand Up @@ -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;
13 changes: 13 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^0.21.1",
"bcryptjs": "^2.4.3",
"dotenv": "^8.2.0",
"express": "^4.17.1",
Expand Down
12 changes: 12 additions & 0 deletions routes/hospitalRoutes.js
Original file line number Diff line number Diff line change
@@ -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;
2 changes: 2 additions & 0 deletions routes/userRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
2 changes: 2 additions & 0 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand All @@ -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!");
Expand Down

0 comments on commit 2a3bd5b

Please sign in to comment.