-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
310 lines (254 loc) · 7.32 KB
/
index.ts
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
import { PrismaClient } from "@prisma/client"
import { compare, hash } from "bcrypt"
import { config } from "dotenv"
import express from "express"
import session from "express-session"
import { z } from "zod"
config({ path: ".env" })
const prisma = new PrismaClient()
const app = express()
const store = new session.MemoryStore()
app.use(express.json())
if (!process.env.SESSION_SECRET) {
console.error("No SESSION_SECRET environment variable provided")
process.exit(1)
}
app.use(
session({
secret: process.env.SESSION_SECRET,
cookie: { maxAge: 7 * 24 * 60 * 60 * 1000 }, // 7 days
resave: false,
saveUninitialized: false,
store,
}),
)
declare module "express-session" {
interface SessionData {
authenticated: boolean
user: { username: string }
}
}
app.post("/signup", async (req, res) => {
const result = z
.object({
username: z.string(),
password: z.string(),
})
.safeParse(req.body)
if (!result.success) {
return res.status(400).json({ error: result.error })
}
try {
const { username, password: unsafePassword } = result.data
const existingUser = await prisma.user.findUnique({ where: { username } })
if (existingUser) {
return res.status(400).json({ error: "User already exists" })
}
const hashedPassword = await hash(unsafePassword, 12)
const user = await prisma.user.create({
data: {
username,
password: hashedPassword,
},
})
if (user) {
req.session.authenticated = true
req.session.user = { username }
return res.status(201).json(req.session)
}
} catch (error) {
console.error(error)
}
return res.status(500).json({ error: "Error creating user" })
})
app.post("/signin", async (req, res) => {
const result = z
.object({
username: z.string(),
password: z.string(),
})
.safeParse(req.body)
if (!result.success) {
return res.status(400).json({ error: result.error })
}
try {
const { username, password } = result.data
const user = await prisma.user.findFirst({
where: { username },
select: { password: true },
})
if (user && await compare(password, user.password)) {
req.session.authenticated = true
req.session.user = { username }
return res.json(req.session)
}
} catch (error) {
console.error(error)
return res.status(500).json({ error: "Error authenticating the user" })
}
return res.status(403).json({ error: "Bad credentials" })
})
app.post("/signout", async (req, res) => {
if (!req.session.authenticated) {
return res.status(401).json({ error: "User not authenticated" })
}
req.session.authenticated = false
req.session.user = undefined
return res.status(200).send()
})
app.get("/feed", async (req, res) => {
if (!req.session?.authenticated) {
return res.status(401).json({ error: "User not authenticated" })
}
try {
const username = req.session?.user?.username
const user = await prisma.user.findUnique({
where: { username },
select: {
id: true,
following: { select: { id: true } },
},
})
if (!user) {
return res.status(404).json({ error: "User not found" })
}
const userIds = [user.id, ...user.following.map(({ id }) => id)]
const followingFeed = await prisma.creditLog.findMany({
where: { userId: { in: userIds } },
select: {
amount: true,
createdAt: true,
type: true,
user: { select: { username: true } },
},
orderBy: { createdAt: "desc" },
take: 128,
})
const globalFeed = await prisma.creditLog.findMany({
where: { userId: { not: { in: userIds } } },
select: {
amount: true,
createdAt: true,
type: true,
user: { select: { username: true } },
},
orderBy: { createdAt: "desc" },
take: 128,
})
return res.json([
...followingFeed.map((log) => ({
...log,
following: log.user.username !== username,
})),
...globalFeed.map((log) => ({ ...log, following: false })),
])
} catch (error) {
console.error(error)
return res.status(500).json({ error: "Error fetching user feed" })
}
})
app.get("/follow/:username", async (req, res) => {
if (!req.session?.authenticated) {
return res.status(401).json({ error: "User not authenticated" })
}
const result = z.object({ username: z.string() }).safeParse(req.params)
if (!result.success) {
return res.status(400).json({ error: result.error })
}
const { username } = result.data
if (req.session?.user?.username === username) {
return res.status(400).json({ error: "Users cannot follow themselves" })
}
try {
await prisma.user.update({
where: { username: req.session?.user?.username },
data: {
following: { connect: { username } },
},
})
return res.status(200).send()
} catch (error) {
console.error(error)
return res.status(500).json({ error: "Error following user" })
}
})
app.get("/unfollow/:username", async (req, res) => {
if (!req.session?.authenticated) {
return res.status(401).json({ error: "User not authenticated" })
}
const result = z.object({ username: z.string() }).safeParse(req.params)
if (!result.success) {
return res.status(400).json({ error: result.error })
}
const { username } = result.data
try {
await prisma.user.update({
where: { username: req.session?.user?.username },
data: {
following: { disconnect: { username } },
},
})
return res.status(200).send()
} catch (error) {
console.error(error)
return res.status(500).json({ error: "Error unfollowing user" })
}
})
app.get("/credit/list", async (req, res) => {
if (!req.session?.authenticated) {
return res.status(401).json({ error: "User not authenticated" })
}
try {
const user = await prisma.user.findUnique({
where: { username: req.session?.user?.username },
select: {
creditLogs: {
select: {
amount: true,
createdAt: true,
type: true,
},
},
},
})
if (!user) {
return res.status(404).json({ error: "User not found" })
}
return res.json(user.creditLogs)
} catch (error) {
console.error(error)
return res.status(500).json({ error: "Error listing credit logs" })
}
})
app.post("/credit/log", async (req, res) => {
if (!req.session?.authenticated) {
return res.status(401).json({ error: "User not authenticated" })
}
const creditLogSchema = z.object({
amount: z.number(),
type: z.string(),
})
const result = creditLogSchema.safeParse(req.body)
if (!result.success) {
return res.status(400).json({ error: result.error })
}
try {
const creditLog = await prisma.creditLog.create({
data: {
...result.data,
user: { connect: { username: `${req.session?.user?.username}` } },
},
})
if (!creditLog) {
return res.status(500).json({ error: "Error creating credit log" })
}
return res.status(201).json({ ...result.data, createdAt: creditLog.createdAt })
} catch (error) {
console.error(error)
return res.status(500).json({ error: "Error creating credit log" })
}
})
const PORT = process.env.PORT || 3000
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`)
})