-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
213 lines (196 loc) · 6.94 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
const express = require("express");
const path = require("path");
const sqlite3 = require("sqlite3");
const { open } = require("sqlite");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const app = express();
app.use(express.json());
const databasePath = path.join(__dirname, "covid19IndiaPortal.db");
let database = null;
const initializeAndDbAndServer = async () => {
try {
database = await open({ filename: databasePath, driver: sqlite3.Database });
app.listen(3000, () => {
console.log(`server is running on http://localhost:3000`);
});
} catch (error) {
console.log(`Database error is ${error}`);
process.exit(1);
}
};
initializeAndDbAndServer();
// API 1
// User Login
// get JWT token using jsonwebtoken package
// const JWTToken = jwt.sign(payload,'own_secret_key');
// payload is user information
// Scenarios
// 1)Invalid user
// 2)Invalid password
// 3) Return the JWT Token
app.post("/login/", async (request, response) => {
const { username, password } = request.body;
// check user
const userDetailsQuery = `select * from user where username = '${username}';`;
const userDetails = await database.get(userDetailsQuery);
if (userDetails !== undefined) {
const isPasswordValid = await bcrypt.compare(
password,
userDetails.password
);
if (isPasswordValid) {
//get JWT Token
const payload = { username: username };
const jwtToken = jwt.sign(payload, "vivek_secret_key");
response.send({ jwtToken }); //Scenario 3
} else {
response.status(400);
response.send(`Invalid password`); //Scenario 2
}
} else {
response.status(400);
response.send("Invalid user"); //Scenario 1
}
});
// Authentication with Token
// Scenarios
//1) If the token is not provided by the user or an invalid token-->Invalid JWT Token
// 2) After successful verification of token proceed to next middleware or handler
// get JWT token from headers and validate using jwt.verify
//jwt.verify(jwtToken , 'secret key given above' , callback function)
function authenticationToken(request, response, next) {
let jwtToken;
const authHeader = request.headers.authorization;
if (authHeader !== undefined) {
jwtToken = authHeader.split(" ")[1];
}
if (jwtToken !== undefined) {
jwt.verify(jwtToken, "vivek_secret_key", async (error, payload) => {
if (error) {
response.status(401);
response.send(`Invalid JWT Token`); // Scenario 1
} else {
next(); //Scenario 2
}
});
} else {
response.status(401);
response.send(`Invalid JWT Token`); //Scenario 1
}
}
// API 2
//Returns a list of all states in the state table
// get the results if the user has authentication
const convertStateDbObject = (objectItem) => {
return {
stateId: objectItem.state_id,
stateName: objectItem.state_name,
population: objectItem.population,
};
};
app.get("/states/", authenticationToken, async (request, response) => {
const getStatesQuery = `select * from state;`;
const getStates = await database.all(getStatesQuery);
response.send(getStates.map((eachState) => convertStateDbObject(eachState)));
});
// API 3
// Returns a state based on the state ID
// only authenticated users get the details
app.get("/states/:stateId/", authenticationToken, async (request, response) => {
const { stateId } = request.params;
const getStateDetailsQuery = `select * from state where state_id = ${stateId};`;
const getStateDetails = await database.get(getStateDetailsQuery);
response.send(convertStateDbObject(getStateDetails));
});
// API 4
//Create a district in the district table, district_id is auto-incremented
// only authenticated users can post the data
app.post("/districts/", authenticationToken, async (request, response) => {
const { districtName, stateId, cases, cured, active, deaths } = request.body;
const createDistrictQuery = `insert into district(district_name,state_id,cases,cured,active,deaths)
values('${districtName}',${stateId},${cases},${cured},${active},${deaths});`;
const createDistrict = await database.run(createDistrictQuery);
response.send(`District Successfully Added`);
});
// API 5
//Returns a district based on the district ID
const convertDbObjectDistrict = (objectItem) => {
return {
districtId: objectItem.district_id,
districtName: objectItem.district_name,
stateId: objectItem.state_id,
cases: objectItem.cases,
cured: objectItem.cured,
active: objectItem.active,
deaths: objectItem.deaths,
};
};
app.get(
"/districts/:districtId/",
authenticationToken,
async (request, response) => {
const { districtId } = request.params;
const getDistrictByIdQuery = `select * from district where district_id=${districtId};`;
const getDistrictByIdQueryResponse = await database.get(
getDistrictByIdQuery
);
response.send(convertDbObjectDistrict(getDistrictByIdQueryResponse));
}
);
//----------------------API 6
//Deletes a district from the district table based on the district ID
// only authenticated users can delete data from database.
app.delete(
"/districts/:districtId/",
authenticationToken,
async (request, response) => {
const { districtId } = request.params;
const deleteDistrictQuery = `delete from district where district_id = ${districtId};`;
const deleteDistrict = await database.run(deleteDistrictQuery);
response.send(`District Removed`);
}
);
// API 7
//Updates the details of a specific district based on the district ID
// only authenticated users can update the data.
app.put(
"/districts/:districtId/",
authenticationToken,
async (request, response) => {
const { districtId } = request.params;
const {
districtName,
stateId,
cases,
cured,
active,
deaths,
} = request.body;
const updateDistrictQuery = `update district set
district_name = '${districtName}',
state_id = ${stateId},
cases = ${cases},
cured = ${cured},
active = ${active},
deaths = ${deaths} where district_id = ${districtId};`;
const updateDistrictQueryResponse = await database.run(updateDistrictQuery);
response.send("District Details Updated");
}
);
// API 8
//Returns the statistics of total cases, cured, active, deaths of a specific state based on state ID
app.get(
"/states/:stateId/stats/",
authenticationToken,
async (request, response) => {
const { stateId } = request.params;
const getStateByIDStatsQuery = `select sum(cases) as totalCases, sum(cured) as totalCured,
sum(active) as totalActive , sum(deaths) as totalDeaths from district where state_id = ${stateId};`;
const getStateByIDStatsQueryResponse = await database.get(
getStateByIDStatsQuery
);
response.send(getStateByIDStatsQueryResponse);
}
);
module.exports = app;