-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
261 lines (235 loc) · 7.8 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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
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 dbFilePath = path.join(__dirname, "twitterClone.db");
let db = null;
const initialiseDBAndServer = async () => {
try {
db = await open({
filename: dbFilePath,
driver: sqlite3.Database,
});
app.listen(3000, () => {
console.log("Server Running at http:localhost:3000");
});
} catch (error) {
console.log(error.message);
process.exit(1);
}
};
initialiseDBAndServer();
module.exports = app;
const getFollowingPeopleIdsOfUser = async (username) => {
const getTheFollowingPeopleQuery = `SELECT
following_user_id FROM follower
INNER JOIN user ON user.user_id = follower.follower_user_id
WHERE user.username='${username}';`;
const followingPeople = await db.all(getTheFollowingPeopleQuery);
const arrayOfIds = followingPeople.map(
(eachUser) => eachUser.following_user_id
);
return arrayOfIds;
};
const authentication = (request, response, next) => {
let jwtToken;
const authHeader = request.headers["authorization"];
if (authHeader) {
jwtToken = authHeader.split(" ")[1];
}
if (jwtToken) {
jwt.verify(jwtToken, "SECRET_KEY", (error, payload) => {
if (error) {
response.status(401);
response.send("Invalid JWT Token");
} else {
request.username = payload.username;
request.userId = payload.userId;
next();
}
});
} else {
response.status(401);
response.send("Invalid JWT Token");
}
};
const tweetAccessVerification = async (request, response, next) => {
const { userId } = request;
const { tweetId } = request.params;
const getTweetQuery = `SELECT
*
FROM tweet INNER JOIN follower
ON tweet.user_id = follower.following_user_id
WHERE tweet.tweet_id = '${tweetId}' AND follower_user_id = '${userId}';`;
const tweet = await db.get(getTweetQuery);
if (tweet === undefined) {
response.status(401);
response.send("Invalid Request");
} else {
next();
}
};
app.post("/register/", async (request, response) => {
const { username, password, name, gender } = request.body;
const getUserQuery = `SELECT * FROM user WHERE username = '${username}'`;
const userDBDetails = await db.get(getUserQuery);
if (userDBDetails !== undefined) {
response.status(400);
response.send("User already exists");
} else {
if (password.length < 6) {
response.status(400);
response.send("Password is too short");
} else {
const hashedPassword = await bcrypt.hash(password, 10);
const createUserQuery = `INSERT INTO
user(username,password,name,gender)
VALUES('${username}','${hashedPassword}','${name}','${gender}')`;
await db.run(createUserQuery);
response.send("User created successfully");
}
}
});
app.post("/login/", async (request, response) => {
const { username, password } = request.body;
const getUserQuery = `SELECT * FROM user WHERE username='${username}';`;
const userDbDetails = await db.get(getUserQuery);
if (userDbDetails !== undefined) {
const isPasswordCorrect = await bcrypt.compare(
password,
userDbDetails.password
);
if (isPasswordCorrect) {
const payload = { username, userId: userDbDetails.user_id };
const jwtToken = jwt.sign(payload, "SECRET_KEY");
console.log(jwtToken);
response.send({ jwtToken });
} else {
response.status(400);
response.send("Invalid password");
}
} else {
response.status(400);
response.send("Invalid user");
}
});
app.get("/user/tweets/feed/", authentication, async (request, response) => {
const { username } = request;
const followingPeopleIds = await getFollowingPeopleIdsOfUser(username);
const getTweetsQuery = `SELECT
username,tweet, date_time as dateTime
FROM user INNER JOIN tweet ON user.user_id = tweet.user_id
WHERE user.user_id IN (${followingPeopleIds})
ORDER BY date_time DESC
LIMIT 4;
`;
const tweets = await db.all(getTweetsQuery);
response.send(tweets);
});
app.get("/user/following/", authentication, async (request, response) => {
const { username, userId } = request;
const getFollowingUsersQuery = `SELECT name FROM follower
INNER JOIN user ON user.user_id = follower.following_user_id
WHERE follower_user_id = '${userId}';
`;
const followingPeople = await db.all(getFollowingUsersQuery);
response.send(followingPeople);
});
app.get("/user/followers/", authentication, async (request, response) => {
const { username, userId } = request;
const getFollowersQuery = `SELECT DISTINCT name FROM follower
INNER JOIN user ON user.user_id = follower.follower_user_id
WHERE following_user_id = '${userId}';
`;
const followers = await db.all(getFollowersQuery);
response.send(followers);
});
app.get(
"/tweets/:tweetId/",
authentication,
tweetAccessVerification,
async (request, response) => {
const { username, userId } = request;
const { tweetId } = request.params;
const getTweetQuery = `SELECT tweet,
(SELECT COUNT() FROM like WHERE tweet_id = '${tweetId}') AS likes,
(SELECT COUNT() FROM reply WHERE tweet_id = '${tweetId}') AS replies,
date_time AS dateTime
FROM tweet
WHERE tweet.tweet_id = '${tweetId}' ;`;
const tweet = await db.get(getTweetQuery);
response.send(tweet);
}
);
app.get(
"/tweets/:tweetId/likes/",
authentication,
tweetAccessVerification,
async (request, response) => {
const { tweetId } = request.params;
const getLikesQuery = `SELECT username
FROM user INNER JOIN like ON user.user_id = like.user_id
WHERE tweet_id = '${tweetId}';
`;
const likedUsers = await db.all(getLikesQuery);
const usersArray = likedUsers.map((eachUser) => eachUser.username);
response.send({ likes: usersArray });
}
);
app.get(
"/tweets/:tweetId/replies/",
authentication,
tweetAccessVerification,
async (request, response) => {
const { tweetId } = request.params;
const getRepliedQuery = `SELECT name,reply
FROM user INNER JOIN reply ON user.user_id = reply.user_id
WHERE tweet_id = '${tweetId}';
`;
const repliedUsers = await db.all(getRepliedQuery);
response.send({ replies: repliedUsers });
}
);
app.get("/user/tweets/", authentication, async (request, response) => {
const { userId } = request;
const getTweetsQuery = `
SELECT tweet,
COUNT(DISTINCT like_id) AS likes,
COUNT(DISTINCT reply_id) AS replies,
date_time AS dateTime
FROM tweet LEFT JOIN reply ON tweet.tweet_id = reply.tweet_id
LEFT JOIN like ON tweet.tweet_id = like.tweet_id
WHERE tweet.user_id = ${userId}
GROUP BY tweet.tweet_id;`;
const tweets = await db.all(getTweetsQuery);
response.send(tweets);
});
app.post("/user/tweets/", authentication, async (request, response) => {
const { tweet } = request.body;
const userId = parseInt(request.userId);
const dateTime = new Date().toJSON().substring(0, 19).replace("T", " ");
const createTweetQuery = `INSERT INTO tweet(tweet,user_id,date_time)
VALUES('${tweet}','${userId}','${dateTime}')
`;
await db.run(createTweetQuery);
response.send("Created a Tweet");
});
app.delete("/tweets/:tweetId/", authentication, async (request, response) => {
const { tweetId } = request.params;
const { userId } = request;
const getTheTweetQuery = `SELECT * FROM tweet WHERE user_id = '${userId}' AND tweet_id = '${tweetId}';`;
const tweet = await db.get(getTheTweetQuery);
console.log(tweet);
if (tweet === undefined) {
response.status(401);
response.send("Invalid Request");
} else {
const deleteTweetQuery = `DELETE FROM tweet WHERE tweet_id ='${tweetId}';`;
await db.run(deleteTweetQuery);
response.send("Tweet Removed");
}
});