Skip to content

Commit

Permalink
adjust db attribute names, fix some bugs at auth and add schedule event
Browse files Browse the repository at this point in the history
  • Loading branch information
ducphamle2 committed Apr 21, 2020
1 parent 5d42c01 commit 6dc68c9
Show file tree
Hide file tree
Showing 10 changed files with 208 additions and 123 deletions.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,6 @@
How to run the project: ./restart-all.sh
If you want to adjust something in the server nodejs code, type ./restart-node.sh to restart the container. Otherwise,
if you want to change something in the mysql container, use ./restart-all.sh
If you want to debug the containers, remove '-d' flag in restart-all.sh and call the file again.
If you want to debug the containers, remove '-d' flag in restart-all.sh and call the file again.

Note: remember to add .env file when cloning the project
139 changes: 84 additions & 55 deletions controllers/auth/authController.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ const winston = require("winston");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const { validationResult } = require("express-validator/check");
const crypto = require('crypto');

const db = require("../../database/index");
const userId = require("../../utils/utils").generateId
const constants = require("../../utils/constants")

const generateHash = (password) => {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
Expand All @@ -26,43 +27,54 @@ module.exports = {
const errors = validationResult(req);
if (!errors.isEmpty()) {
logger.error(`Validation error: ${JSON.stringify(errors.array())}`);
res.status(422).json({ errors: errors.array() });
return res.status(422).json({ errors: errors.array() });
} else {
let email = req.body.email
let role = req.body.role
// role is used to select from correct table. Client will send the role
let sql = 'SELECT * from ?? where email = ?'
db.query(sql, [role, email], async function (err, user) {
console.log("user: ", user)
if (err) {
res.status(400).json({
message: "Error connecting to database" + err,
return res.status(400).json({
message: "Error querying" + err,
});
}
let result = await bcrypt.compare(req.body.password, user[0].password)
if (!result || result.length === 0) {
res.status(422).json({
message: "Auth failed!"
});
logger.info("Wrong password");
} else if (user.length === 0) {
return res.status(404).json({
message: "Cannot find the correct user"
})
} else {
// generate a token for the account to use in other api
jwt.sign({
username: user.username,
//userId: user.id
}, process.env.SECRET_KEY, { algorithm: "HS512" }, (err, token) => {
if (err) {
res.status(422).json({
message: "Auth failed",
});
logger.error("Cannot create token");
} else {
res.status(200).json({
message: "Logged in successfully",
token,
user
});
}
});
let result = await bcrypt.compare(req.body.password, user[0].password)
if (!result || result.length === 0) {
res.status(422).json({
message: "Auth failed!"
});
logger.info("Wrong password");
} else {
// generate a token for the account to use in other api
jwt.sign({
email: user[0].email,
// check id type based on role to sign the correct one
id: role === constants.role.donor ?
user[0].donor_id :
role === constants.role.red_cross ?
user[0].redcross_id : role === constants.role.organizer ?
user[0].organizer_id : user[0].hospital_id,
role: role
}, process.env.SECRET_KEY, { algorithm: "HS512" }, (err, token) => {
if (err) {
return res.status(422).json({
message: "Auth failed",
});
} else {
return res.status(200).json({
message: "Logged in successfully",
token,
user
});
}
});
}
}
});
}
Expand All @@ -72,37 +84,54 @@ module.exports = {
const errors = validationResult(req);
if (!errors.isEmpty()) {
logger.error(`Validation error: ${JSON.stringify(errors.array())}`);
res.status(422).json({ errors: errors.array() });
return res.status(422).json({ errors: errors.array() });
} else {
// hash the password for protection in case db is exposed
let password = generateHash(req.body.password)
console.log("Password: ", password)
let values =
req.body.role === "hospital" ?
[
// insert into three values, id which is 32 characters, email and password
[crypto.randomBytes(16).toString("hex"), req.body.redcross_id, req.body.email, password]
] :
[
// insert into three values, id which is 32 characters, email and password
[crypto.randomBytes(16).toString("hex"), req.body.email, password]
]
// role id is used to distinguish from tables
let sql =
req.body.role === "hospital" ?
'insert into ?? (' + req.body.role_id + ', redcross_id, email, password) values ?' :
'insert into ?? (' + req.body.role_id + ', email, password) values ?'
db.query(sql, [req.body.role, values], function (err, user) {
if (err) {
res.status(400).json({
message: "Error connecting to database" + err,
let sql = "select name, email from ?? where name = ? or email = ?"
// check if name has been used or not, since this will be used to query in other api
db.query(sql, [req.body.role, req.body.name, req.body.email], function (err, result) {
// if the name has been used then we return error
console.log("result: ", result)
if (result === undefined || result.length > 0) {
return res.status(403).json({
message: "The name or email has already been used",
});
} else if (err) {
return res.status(400).json({
message: "There is something wrong when querying: " + err,
});
} else {
let values =
req.body.role === constants.role.hospital ?
[
// insert into three values, id which is 32 characters, email and password
[userId(), req.body.red_cross_id, req.body.email, password, req.body.name]
] :
[
// insert into three values, id which is 32 characters, email and password
[userId(), req.body.email, password, req.body.name]
]
// role id is used to distinguish from tables
let role_id = req.body.role + "_id"
let sql =
req.body.role === constants.role.hospital ?
'insert into ?? (' + role_id + ', red_cross_id, email, password, name) values ?' :
'insert into ?? (' + role_id + ', email, password, name) values ?'
db.query(sql, [req.body.role, values], function (err, user) {
if (err) {
return res.status(400).json({
message: "Error querying: " + err,
});
} else {
console.log("USER: ", user)
res.status(200).json({
message: "Registered successfully",
body: password
});
}
})
}
console.log("USER: ", user)
res.status(200).json({
message: "Registered successfully",
body: password
});
})
}
}
Expand Down
68 changes: 68 additions & 0 deletions controllers/blood_event/eventController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
const db = require("../../database/index");
const eventId = require("../../utils/utils").generateId
const constants = require("../../utils/constants")

module.exports = {
createEvent: (req, res) => {
console.log("request user data: ", req.userData)
// only organizer can create event
if (req.userData.role !== "organizer") {
return res.status(403).json({
message: "Forbidden !! You are not allowed to call this function"
})
} else {
// need to find the id of the red cross since user can only remember name
let sql = "select red_cross_id from red_cross where name = ?"
let values = [[req.body.red_cross_name]]
db.query(sql, [values], function (err, result) {
console.log("result after querying: ", result[0].red_cross_id)
if (result.length === 0) {
return res.status(404).json({
message: "Cannot find the red cross name",
});
} else if (err) {
return res.status(503).json({
message: "There is something wrong when querying",
});
} else {

let event_id = eventId()
let values =
req.body.role =
[
[
event_id,
result[0].red_cross_id,
req.userData.id, // id of the organizer when using token
req.body.date,
req.body.name,
req.body.location,
constants.pending
]
]
let sql = "insert into event values ?"
db.query(sql, [values], function (err, user) {
if (err || user.length === 0) {
return res.status(400).json({
message: "Error querying: " + err,
});
} else {
console.log("USER: ", user)
return res.status(200).json({
message: "Your event has been created successfully",
event_id: event_id
});
}
})
}
})
}
},

updateEvent: (req, res) => {

},
deleteEvent: (req, res) => {

}
};
14 changes: 14 additions & 0 deletions controllers/blood_event/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const express = require("express");

const controller = require("./eventController.js");
const authMiddleware = require("../../middlewares/authMiddleware.js");

const router = express.Router();

router.post("/create_event", authMiddleware, controller.createEvent);

router.post("/update_event", authMiddleware, controller.updateEvent);

router.post("/delete_event", authMiddleware, controller.deleteEvent);

module.exports = router;
45 changes: 20 additions & 25 deletions init_db/db.sql
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ USE mydb;

CREATE TABLE donor (
donor_id CHAR(32) PRIMARY KEY UNIQUE NOT NULL,
donor_name VARCHAR(30) NULL,
name VARCHAR(99) NOT NULL,
password VARCHAR(100) NOT NULL,
email VARCHAR(30) NOT NULL,
address VARCHAR(50) NULL,
Expand All @@ -18,8 +18,8 @@ CREATE TABLE donor (
DEFAULT CHARACTER SET = utf8;

CREATE TABLE red_cross (
redcross_id CHAR(32) PRIMARY KEY UNIQUE NOT NULL,
redcross_name VARCHAR(30) NULL,
red_cross_id CHAR(32) PRIMARY KEY UNIQUE NOT NULL,
name VARCHAR(99) NOT NULL,
password VARCHAR(100) NOT NULL,
email VARCHAR(30) NOT NULL,
address VARCHAR(50) NULL
Expand All @@ -29,7 +29,7 @@ CREATE TABLE red_cross (

CREATE TABLE organizer (
organizer_id CHAR(32) PRIMARY KEY UNIQUE NOT NULL,
organizer_name VARCHAR(30) NULL,
name VARCHAR(99) NOT NULL,
password VARCHAR(100) NOT NULL,
email VARCHAR(30) NOT NULL,
address VARCHAR(50) NULL
Expand All @@ -39,68 +39,63 @@ CREATE TABLE organizer (

CREATE TABLE hospital (
hospital_id CHAR(32) PRIMARY KEY UNIQUE NOT NULL,
redcross_id CHAR(32) UNIQUE NOT NULL,
hospital_name VARCHAR(30) NULL,
red_cross_id CHAR(32) UNIQUE NOT NULL,
name VARCHAR(99) NOT NULL,
password VARCHAR(100) NOT NULL,
email VARCHAR(30) NOT NULL,
address VARCHAR(50) NULL,
FOREIGN KEY (redcross_id) REFERENCES red_cross(redcross_id)
FOREIGN KEY (red_cross_id) REFERENCES red_cross(red_cross_id)
)
ENGINE = INNODB
DEFAULT CHARACTER SET = utf8;

CREATE TABLE blood_store (
store_id CHAR(32) PRIMARY KEY UNIQUE NOT NULL,
redcross_id CHAR(32) UNIQUE NOT NULL,
red_cross_id CHAR(32) UNIQUE NOT NULL,
bloodType VARCHAR(5) NOT NULL,
amount DOUBLE PRECISION NULL,
FOREIGN KEY (redcross_id) REFERENCES red_cross(redcross_id)
FOREIGN KEY (red_cross_id) REFERENCES red_cross(red_cross_id)
)
ENGINE = INNODB
DEFAULT CHARACTER SET = utf8;

CREATE TABLE notification (
notification_id CHAR(32) PRIMARY KEY UNIQUE NOT NULL,
redcross_id CHAR(32) UNIQUE NOT NULL,
red_cross_id CHAR(32) UNIQUE NOT NULL,
organizer_id CHAR(32) UNIQUE NOT NULL,
noti_date DATETIME NULL,
content VARCHAR(50) NULL,
FOREIGN KEY (redcross_id) REFERENCES red_cross(redcross_id),
FOREIGN KEY (red_cross_id) REFERENCES red_cross(red_cross_id),
FOREIGN KEY (organizer_id) REFERENCES organizer(organizer_id)
)
ENGINE = INNODB
DEFAULT CHARACTER SET = utf8;

CREATE TABLE event (
event_id CHAR(32) PRIMARY KEY UNIQUE NOT NULL,
redcross_id CHAR(32) UNIQUE NOT NULL,
red_cross_id CHAR(32) UNIQUE NOT NULL,
organizer_id CHAR(32) UNIQUE NOT NULL,
event_date DATETIME NULL,
event_name VARCHAR(30) NULL,
location VARCHAR(50) NULL,
status VARCHAR(10) NULL,
FOREIGN KEY (redcross_id) REFERENCES red_cross(redcross_id),
event_date DATETIME NOT NULL,
name VARCHAR(99) NOT NULL,
location VARCHAR(50) NOT NULL,
status VARCHAR(10) NOT NULL,
FOREIGN KEY (red_cross_id) REFERENCES red_cross(red_cross_id),
FOREIGN KEY (organizer_id) REFERENCES organizer(organizer_id)
)
ENGINE = INNODB
DEFAULT CHARACTER SET = utf8;

CREATE TABLE blood (
blood_id CHAR(32) PRIMARY KEY UNIQUE NOT NULL,
redcross_id CHAR(32) UNIQUE NOT NULL,
red_cross_id CHAR(32) UNIQUE NOT NULL,
event_id CHAR(32) UNIQUE NOT NULL,
donor_id CHAR(32) UNIQUE NOT NULL,
donate_date DATETIME NULL,
amount DOUBLE PRECISION NULL,
status VARCHAR(10) NULL,
FOREIGN KEY (redcross_id) REFERENCES red_cross(redcross_id),
FOREIGN KEY (red_cross_id) REFERENCES red_cross(red_cross_id),
FOREIGN KEY (event_id) REFERENCES event(event_id),
FOREIGN KEY (donor_id) REFERENCES donor(donor_id)
)
ENGINE = INNODB
DEFAULT CHARACTER SET = utf8;

insert into red_cross values ('axswitkxfjguws', 'Red Cross', '$2a$08$e1vJwED9DFpXzwgd15LxruIvnBluHtu8px17S6ucv2k7NuRW8fHUq', '[email protected]', "DH BKHN");
insert into donor values ('txstitkxfjguwa', 'Ricardo Milos', '$2a$08$e1vJwED9DFpXzwgd15LxruIvnBluHtu8px17S6ucv2k7NuRW8fHUq', '[email protected]', NULL, NULL, NULL);
insert into organizer values ('bxswitkxfjguwa', 'BK', '$2a$08$e1vJwED9DFpXzwgd15LxruIvnBluHtu8px17S6ucv2k7NuRW8fHUq', '[email protected]', NULL);
insert into hospital values ('gxswitkxfjguwa','axswitkxfjguws', 'Hospital', '$2a$08$e1vJwED9DFpXzwgd15LxruIvnBluHtu8px17S6ucv2k7NuRW8fHUq', '[email protected]', NULL);
DEFAULT CHARACTER SET = utf8;
Loading

0 comments on commit 6dc68c9

Please sign in to comment.