-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
289 lines (263 loc) · 8.11 KB
/
Copy pathapp.js
File metadata and controls
289 lines (263 loc) · 8.11 KB
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
const express = require('express')
const app = express()
app.use(express.json())
const sqlite3 = require('sqlite3')
const {open} = require('sqlite')
const bcrypt = require('bcrypt')
const jwt = require('jsonwebtoken')
let db = null
const path = require('path')
const dbpath = path.join(__dirname, 'twitterClone.db')
const dbInitializer = async () => {
db = await open({
filename: dbpath,
driver: sqlite3.Database,
})
app.listen(3000)
console.log('Server is running on http://localhost:3000')
}
//Register API
app.post('/register/', async (request, response) => {
const {username, password, name, gender} = request.body
const hashedPassword = await bcrypt.hash(password, 10)
const selectQuery = `Select * from user where username='${username}'`
const dbResponse = await db.get(selectQuery)
if (dbResponse === undefined) {
if (password.length < 6) {
response.status(400)
response.send('Password is too short')
return
} else {
const insertQuery = `insert into user(username,password,name,gender) values('${username}','${hashedPassword}','${name}','${gender}');`
const dbResponse = await db.run(insertQuery)
response.send('User created successfully')
}
} else {
response.status(400)
response.send('User already exists')
}
})
app.post('/login/', async (request, response) => {
const {username, password} = request.body
const selectQuery = `Select * from user where username='${username}';`
const dbResponse = await db.get(selectQuery)
if (dbResponse === undefined) {
// User Doesn't Exist
response.status(400)
response.send('Invalid user')
} else {
// User Exists
const isPassMatched = await bcrypt.compare(password, dbResponse.password)
if (isPassMatched === true) {
// Password is matched
const userId = dbResponse.user_id
const payload = {
username: username,
userId: userId,
}
//console.log(dbResponse)
//console.log(payload)
const jwtToken = await jwt.sign(payload, 'SECREt_TOKEN')
response.send({jwtToken})
} else {
// Password is not matched
response.status(400)
response.send('Invalid password')
}
}
})
const authenticate = (request, response, next) => {
const authHeader = request.headers['authorization']
if (authHeader === undefined) {
response.status(401).send('Invalid JWT Token')
return
}
const jwtToken = authHeader.split(' ')[1]
if (jwtToken === undefined) {
response.status(401).send('Invalid JWT Token')
return
}
jwt.verify(jwtToken, 'SECREt_TOKEN', (error, payload) => {
if (error) {
response.status(401).send('Invalid JWT Token')
} else {
//console.log('Decoded JWT payload:', payload)
request.userId = payload.userId
request.username = payload.username
next()
}
})
}
app.get('/user/tweets/feed/', authenticate, async (request, response) => {
const userId = request.userId
const selectQuery = `SELECT
u.username,
t.tweet,
t.date_time AS dateTime
FROM
follower f
INNER JOIN tweet t ON f.following_user_id = t.user_id
INNER JOIN user u ON t.user_id = u.user_id
WHERE
f.follower_user_id = ${userId}
ORDER BY
t.date_time DESC
LIMIT 4;
`
const tweets = await db.all(selectQuery)
//console.log(tweets)
response.send(tweets)
})
app.get('/user/following/', authenticate, async (request, response) => {
const userId = request.userId
const selectQuery = `Select
distinct(u.name)
from
follower f
inner join user u on f.following_user_id=u.user_id
where f.follower_user_id=${userId}
`
const dbResponse = await db.all(selectQuery)
response.send(dbResponse)
})
app.get('/user/followers/', authenticate, async (request, response) => {
const userId = request.userId
const selectQuery = `Select
u.name as name
from follower f
inner join user u
on u.user_id=f.follower_user_id
where
f.following_user_id=${userId};`
const dbResponse = await db.all(selectQuery)
response.send(dbResponse)
})
app.get('/tweets/:tweetId/', authenticate, async (request, response) => {
try {
const {tweetId} = request.params
const userId = request.userId
// Step 1: Check if the tweet is posted by someone the user follows
const accessQuery = `
SELECT tweet.tweet, tweet.date_time AS dateTime
FROM tweet
INNER JOIN follower ON tweet.user_id = follower.following_user_id
WHERE follower.follower_user_id = ? AND tweet.tweet_id = ?;
`
const tweetContent = await db.get(accessQuery, [userId, tweetId])
if (tweetContent === undefined) {
response.status(401).send('Invalid Request')
return
}
// Step 2: Get likes count
const likesQuery = `SELECT COUNT(*) AS likes FROM like WHERE tweet_id = ?;`
const {likes} = await db.get(likesQuery, [tweetId])
// Step 3: Get replies count
const repliesQuery = `SELECT COUNT(*) AS replies FROM reply WHERE tweet_id = ?;`
const {replies} = await db.get(repliesQuery, [tweetId])
// Step 4: Send final response
response.send({
tweet: tweetContent.tweet,
likes,
replies,
dateTime: tweetContent.dateTime,
})
} catch (error) {
response.status(500).send('Server Error')
}
})
app.get('/tweets/:tweetId/likes/', authenticate, async (request, response) => {
const {tweetId} = request.params
const userId = request.userId
const selectQuery = `Select
t.tweet,
t.date_time as dateTime
from tweet t
inner join follower f on f.following_user_id=t.user_id
where f.follower_user_id=${userId} and t.tweet_id=${tweetId}
`
const tweetContent = await db.get(selectQuery)
if (tweetContent === undefined) {
response.status(401)
response.send('Invalid Request')
} else {
const likedUsersQuery = `Select
u.username
from
user u
inner join like l on l.user_id=u.user_id
where l.tweet_id=${tweetId}
`
const likedUsers = await db.all(likedUsersQuery)
const likes = {
likes: likedUsers.map(user => user.username),
}
response.send(likes)
}
})
app.get(
'/tweets/:tweetId/replies/',
authenticate,
async (request, response) => {
const {tweetId} = request.params
const userId = request.userId
const selectQuery = `Select
t.tweet,
t.date_time as dateTime
from tweet t
inner join follower f on f.following_user_id=t.user_id
where f.follower_user_id=${userId} and t.tweet_id=${tweetId}
`
const tweetContent = await db.get(selectQuery)
if (tweetContent === undefined) {
response.status(401)
response.send('Invalid Request')
} else {
const likedUsersQuery = `Select
u.name,
l.reply
from
user u
inner join reply l on l.user_id=u.user_id
where l.tweet_id=${tweetId}
`
const repliedUsers = await db.all(likedUsersQuery)
response.send({replies: repliedUsers})
}
},
)
app.get('/user/tweets/', authenticate, async (request, response) => {
const userId = request.userId
const selectQuery = `Select
t.tweet,
(select count(*) from like where tweet_id=t.tweet_id) as likes,
(select count(*) from reply where tweet_id=t.tweet_id) as replies,
t.date_time as dateTime
from tweet t
where t.user_id=${userId}
`
const dbResponse = await db.all(selectQuery)
response.send(dbResponse)
})
app.post('/user/tweets/', authenticate, async (request, response) => {
const userId = request.userId
const tweet = request.tweet
const insertQuery = `insert into tweet (tweet,user_id) values('${tweet}','${userId}')`
await db.run(insertQuery)
response.send('Created a Tweet')
})
app.delete('/tweets/:tweetId/', authenticate, async (request, response) => {
const {tweetId} = request.params
const userId = request.userId
const selectQuery = `Select user_id from tweet where tweet_id=${tweetId}`
const dbuser = await db.get(selectQuery)
if (dbuser.user_id === userId) {
const deleteQuery = `delete from tweet where tweet_id=${tweetId}`
await db.run(deleteQuery)
response.send('Tweet Removed')
} else {
response.status(401)
response.send('Invalid Request')
}
})
dbInitializer()
module.exports = app