Finished restful code
This commit is contained in:
@@ -1,8 +1,6 @@
|
|||||||
/* @flow */
|
/* @flow */
|
||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
/* eslint-disable */
|
|
||||||
|
|
||||||
const getRegion = async (
|
const getRegion = async (
|
||||||
res: any,
|
res: any,
|
||||||
dbConn: any,
|
dbConn: any,
|
||||||
@@ -13,15 +11,26 @@ const getRegion = async (
|
|||||||
let sqlQuery = "";
|
let sqlQuery = "";
|
||||||
if (country == null) {
|
if (country == null) {
|
||||||
sqlQuery = `
|
sqlQuery = `
|
||||||
SELECT rr.*, cc.countryName
|
SELECT rr.*
|
||||||
FROM regions rr
|
FROM regions rr
|
||||||
JOIN countries cc
|
JOIN countries cc
|
||||||
ON cc.countryCode=rr.countryCode
|
ON cc.countryCode=rr.countryCode
|
||||||
ORDER BY cc.countryCode, rr.regionCode
|
ORDER BY cc.countryCode, rr.regionCode
|
||||||
`;
|
`;
|
||||||
} else if (id == null) {
|
} else if (region == null) {
|
||||||
sqlQuery = `
|
sqlQuery = `
|
||||||
SELECT rr.*, cc.countryName
|
SELECT 1
|
||||||
|
FROM countries
|
||||||
|
WHERE countryCode="${country}"
|
||||||
|
`;
|
||||||
|
|
||||||
|
const countries = await dbConn.query(sqlQuery);
|
||||||
|
if (countries.length === 0) {
|
||||||
|
return res.status(404).send("Country not found");
|
||||||
|
}
|
||||||
|
|
||||||
|
sqlQuery = `
|
||||||
|
SELECT rr.*
|
||||||
FROM regions rr
|
FROM regions rr
|
||||||
JOIN countries cc
|
JOIN countries cc
|
||||||
ON cc.countryCode=rr.countryCode
|
ON cc.countryCode=rr.countryCode
|
||||||
@@ -30,7 +39,7 @@ const getRegion = async (
|
|||||||
`;
|
`;
|
||||||
} else {
|
} else {
|
||||||
sqlQuery = `
|
sqlQuery = `
|
||||||
SELECT rr.*, cc.countryName
|
SELECT rr.*
|
||||||
FROM regions rr
|
FROM regions rr
|
||||||
JOIN countries cc
|
JOIN countries cc
|
||||||
ON cc.countryCode=rr.countryCode
|
ON cc.countryCode=rr.countryCode
|
||||||
@@ -40,12 +49,16 @@ const getRegion = async (
|
|||||||
}
|
}
|
||||||
|
|
||||||
const regions = await dbConn.query(sqlQuery);
|
const regions = await dbConn.query(sqlQuery);
|
||||||
res
|
if (regions.length > 0 || region === null) {
|
||||||
.status(200)
|
res
|
||||||
.set("Content-Type", "application/json")
|
.status(200)
|
||||||
.send(JSON.stringify(regions));
|
.set("Content-Type", "application/json")
|
||||||
|
.send(JSON.stringify(regions));
|
||||||
|
} else {
|
||||||
|
res.status(404).send("Not found");
|
||||||
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
res.status(500).send("Server error");
|
res.status(500).send("Server error 1");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -60,11 +73,11 @@ const deleteRegion = async (
|
|||||||
SELECT 1 FROM cities
|
SELECT 1 FROM cities
|
||||||
WHERE countryCode="${country}"
|
WHERE countryCode="${country}"
|
||||||
AND regionCode="${region}"
|
AND regionCode="${region}"
|
||||||
LIMIT 1"
|
LIMIT 1
|
||||||
`;
|
`;
|
||||||
const cities = await dbConn.query(sqlCities);
|
const cities = await dbConn.query(sqlCities);
|
||||||
if (cities.length > 0) {
|
if (cities.length > 0) {
|
||||||
res.status(403).send("Cannot delete a region with cities");
|
res.status(405).send("Cannot delete a region with cities");
|
||||||
} else {
|
} else {
|
||||||
const deleteRegion = `
|
const deleteRegion = `
|
||||||
DELETE FROM regions
|
DELETE FROM regions
|
||||||
@@ -73,8 +86,7 @@ const deleteRegion = async (
|
|||||||
`;
|
`;
|
||||||
|
|
||||||
const result = await dbConn.query(deleteRegion);
|
const result = await dbConn.query(deleteRegion);
|
||||||
|
if (result.info.affectedRows > 0) {
|
||||||
if (result.affectedRows > 0) {
|
|
||||||
res.status(204).send("Region deleted");
|
res.status(204).send("Region deleted");
|
||||||
} else {
|
} else {
|
||||||
res.status(404).send("Region not found");
|
res.status(404).send("Region not found");
|
||||||
@@ -91,6 +103,10 @@ const postRegion = async (
|
|||||||
country: string,
|
country: string,
|
||||||
name: string
|
name: string
|
||||||
) => {
|
) => {
|
||||||
|
if (!name) {
|
||||||
|
return res.status(400).send("Missing name");
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const sqlCountry = `
|
const sqlCountry = `
|
||||||
SELECT 1
|
SELECT 1
|
||||||
@@ -103,12 +119,13 @@ const postRegion = async (
|
|||||||
}
|
}
|
||||||
|
|
||||||
const sqlGetId = `
|
const sqlGetId = `
|
||||||
SELECT MAX(regionCode) AS maxr
|
SELECT MAX(CAST(regionCode AS INTEGER)) AS maxr
|
||||||
FROM regions
|
FROM regions
|
||||||
WHERE countryCode="${country}"
|
WHERE countryCode="${country}"
|
||||||
`;
|
`;
|
||||||
const regions = await dbConn.query(sqlCountry);
|
const regions = await dbConn.query(sqlGetId);
|
||||||
const newId = regions.length === 0 ? 1 : 1 + regions[0].maxr;
|
const newId =
|
||||||
|
regions.length === 0 ? 1 : 1 + Number(regions[0].maxr);
|
||||||
|
|
||||||
const sqlAddRegion = `
|
const sqlAddRegion = `
|
||||||
INSERT INTO regions SET
|
INSERT INTO regions SET
|
||||||
@@ -118,8 +135,11 @@ const postRegion = async (
|
|||||||
`;
|
`;
|
||||||
|
|
||||||
const result = await dbConn.query(sqlAddRegion);
|
const result = await dbConn.query(sqlAddRegion);
|
||||||
if (result.affectedRows > 0) {
|
if (result.info.affectedRows > 0) {
|
||||||
res.status(201).send("Region created");
|
res
|
||||||
|
.status(201)
|
||||||
|
.header("Location", `/regions/${country}/${newId}`)
|
||||||
|
.send("Region created");
|
||||||
} else {
|
} else {
|
||||||
res.status(409).send("Region not created");
|
res.status(409).send("Region not created");
|
||||||
}
|
}
|
||||||
@@ -135,6 +155,10 @@ const putRegion = async (
|
|||||||
region: string,
|
region: string,
|
||||||
name: string
|
name: string
|
||||||
) => {
|
) => {
|
||||||
|
if (!name) {
|
||||||
|
return res.status(400).send("Missing name");
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const sqlUpdateRegion = `
|
const sqlUpdateRegion = `
|
||||||
UPDATE regions
|
UPDATE regions
|
||||||
@@ -144,7 +168,8 @@ const putRegion = async (
|
|||||||
`;
|
`;
|
||||||
|
|
||||||
const result = await dbConn.query(sqlUpdateRegion);
|
const result = await dbConn.query(sqlUpdateRegion);
|
||||||
if (result.affectedRows > 0) {
|
|
||||||
|
if (result.info.affectedRows > 0) {
|
||||||
res.status(204).send("Region updated");
|
res.status(204).send("Region updated");
|
||||||
} else {
|
} else {
|
||||||
res.status(409).send("Region not updated");
|
res.status(409).send("Region not updated");
|
||||||
|
|||||||
@@ -3,13 +3,25 @@
|
|||||||
|
|
||||||
const express = require("express");
|
const express = require("express");
|
||||||
const app = express();
|
const app = express();
|
||||||
const jwt = require("jsonwebtoken");
|
|
||||||
const bodyParser = require("body-parser");
|
const bodyParser = require("body-parser");
|
||||||
|
|
||||||
const validateUser = require("./validate_user.js");
|
|
||||||
|
|
||||||
const dbConn = require("./restful_db.js");
|
const dbConn = require("./restful_db.js");
|
||||||
|
|
||||||
|
app.get("/", (req, res) => res.send("Secure server!"));
|
||||||
|
|
||||||
|
/*
|
||||||
|
Add here the logic for CORS
|
||||||
|
*/
|
||||||
|
const cors = require("cors");
|
||||||
|
app.use(cors());
|
||||||
|
|
||||||
|
app.use(bodyParser.urlencoded({ extended: false }));
|
||||||
|
|
||||||
|
/*
|
||||||
|
Add here the logic for providing a JWT at /gettoken
|
||||||
|
and the logic for validating a JWT, as shown earlier
|
||||||
|
*/
|
||||||
|
|
||||||
const {
|
const {
|
||||||
getRegion,
|
getRegion,
|
||||||
deleteRegion,
|
deleteRegion,
|
||||||
@@ -17,51 +29,6 @@ const {
|
|||||||
putRegion
|
putRegion
|
||||||
} = require("./restful_regions.js");
|
} = require("./restful_regions.js");
|
||||||
|
|
||||||
const SECRET_JWT_KEY = "modernJSbook";
|
|
||||||
|
|
||||||
app.use(bodyParser.urlencoded({ extended: false }));
|
|
||||||
|
|
||||||
app.post("/gettoken", (req, res) => {
|
|
||||||
validateUser(req.body.user, req.body.password, (idErr, userid) => {
|
|
||||||
if (idErr !== null) {
|
|
||||||
res.status(401).send(idErr);
|
|
||||||
} else {
|
|
||||||
jwt.sign(
|
|
||||||
{ userid },
|
|
||||||
SECRET_JWT_KEY,
|
|
||||||
{ algorithm: "HS256", expiresIn: "1h" },
|
|
||||||
(err, token) => res.status(200).send(token)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
/*
|
|
||||||
app.use((req, res, next) => {
|
|
||||||
// First check for the Authorization header
|
|
||||||
const authHeader = req.headers.authorization;
|
|
||||||
if (!authHeader || !authHeader.startsWith("Bearer ")) {
|
|
||||||
return res.status(401).send("No token specified");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Now validate the token itself
|
|
||||||
const token = authHeader.split(" ")[1];
|
|
||||||
|
|
||||||
jwt.verify(token, SECRET_JWT_KEY, (err, decoded) => {
|
|
||||||
if (err) {
|
|
||||||
// Token bad formed, or expired, or other problem
|
|
||||||
return res.status(403).send("Token expired or not valid");
|
|
||||||
} else {
|
|
||||||
// Token OK; get the user id from it
|
|
||||||
req.userid = decoded.userid;
|
|
||||||
// Keep processing the request
|
|
||||||
next();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
*/
|
|
||||||
|
|
||||||
// START ROUTING FOR REGIONS
|
|
||||||
|
|
||||||
app.get("/regions/", (req, res) => getRegion(res, dbConn));
|
app.get("/regions/", (req, res) => getRegion(res, dbConn));
|
||||||
|
|
||||||
app.get("/regions/:country/", (req, res) =>
|
app.get("/regions/:country/", (req, res) =>
|
||||||
@@ -90,14 +57,22 @@ app.put("/regions/:country/:region", (req, res) =>
|
|||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
|
||||||
// END OF ROUTING FOR REGIONS
|
|
||||||
|
|
||||||
// eslint-disable-next-line no-unused-vars
|
// eslint-disable-next-line no-unused-vars
|
||||||
app.use((err, req, res, next) => {
|
app.use((err, req, res, next) => {
|
||||||
console.error("Error....", err.message);
|
console.error("Error....", err.message);
|
||||||
res.status(500).send("INTERNAL SERVER ERROR");
|
res.status(500).send("INTERNAL SERVER ERROR");
|
||||||
});
|
});
|
||||||
|
|
||||||
app.listen(8080, () =>
|
/*
|
||||||
console.log("Mini JWT server ready, at http://localhost:8080/!")
|
Add here the logic for HTTPS
|
||||||
);
|
*/
|
||||||
|
|
||||||
|
const https = require("https");
|
||||||
|
const fs = require("fs");
|
||||||
|
const path = require("path");
|
||||||
|
const keysPath = path.join(__dirname, "../../certificates");
|
||||||
|
const ca = fs.readFileSync(`${keysPath}/modernjsbook.csr`);
|
||||||
|
const cert = fs.readFileSync(`${keysPath}/modernjsbook.crt`);
|
||||||
|
const key = fs.readFileSync(`${keysPath}/modernjsbook.key`);
|
||||||
|
|
||||||
|
https.createServer({ ca, cert, key }, app).listen(8443);
|
||||||
|
|||||||
Reference in New Issue
Block a user