Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 167
Expand file tree
/
Copy pathprofile.ts
More file actions
Latest commit
424 lines (389 loc) · 12.8 KB
/
Copy pathprofile.ts
File metadata and controls
424 lines (389 loc) · 12.8 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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
import{z}from"zod";
import{
user,
comments,
posts,
feed_sourcesasfeedSources,
topic,
user_topic_pref,
}from"@/server/db/schema";
import{buildCommentHref}from"@/server/lib/content-url";
import{
saveSettingsSchema,
getProfileSchema,
uploadPhotoUrlSchema,
updateProfilePhotoUrlSchema,
}from"@/schema/profile";
import{getPresignedUrl}from"@/server/common/getPresignedUrl";
import{
createTRPCRouter,
publicProcedure,
protectedProcedure,
rateLimitedProcedure,
}from"../trpc";
import{
isUserSubscribedToNewsletter,
manageNewsletterSubscription,
}from"@/server/lib/newsletter";
import{isReservedUsername}from"@/server/lib/reserved-usernames";
import{checkBadges}from"@/server/lib/engagement";
import{TRPCError}from"@trpc/server";
import{nanoid}from"nanoid";
import{and,desc,eq,gte,isNull,ne,sql}from"drizzle-orm";
import{alias}from"drizzle-orm/pg-core";
import{emailTokenReqSchema}from"@/schema/token";
import{generateEmailToken,sendVerificationEmail}from"@/utils/emailToken";
import{TOKEN_EXPIRATION_TIME}from"@/config/constants";
import{emailChangeRequest}from"@/server/db/schema";
exportconstprofileRouter=createTRPCRouter({
// The signed-in user's chosen topics ("Your topics" / onboarding).
myInterests: protectedProcedure.query(async({ ctx })=>{
const[row]=awaitctx.db
.select({
topics: user.topics,
onboardedAt: user.onboardedAt,
experienceLevel: user.experienceLevel,
})
.from(user)
.where(eq(user.id,ctx.session.user.id))
.limit(1);
return{
topics: row?.topics??[],
onboardedAt: row?.onboardedAt??null,
experienceLevel: row?.experienceLevel??null,
};
}),
// Save the user's topics (and optional onboarding fields). Topics are capped
// and trimmed so the column can't be stuffed.
updateInterests: protectedProcedure
.input(
z.object({
topics: z.array(z.string().min(1).max(40)).max(24),
experienceLevel: z.string().max(40).optional(),
markOnboarded: z.boolean().optional(),
}),
)
.mutation(async({ ctx, input })=>{
consttopics=Array.from(
newSet(input.topics.map((t)=>t.trim()).filter(Boolean)),
).slice(0,24);
constset: Record<string,unknown>={ topics };
if(input.experienceLevel)set.experienceLevel=input.experienceLevel;
if(input.markOnboarded)set.onboardedAt=newDate().toISOString();
const[row]=awaitctx.db
.update(user)
.set(set)
.where(eq(user.id,ctx.session.user.id))
.returning({topics: user.topics,onboardedAt: user.onboardedAt});
// Topic picks are an onboarding-badge input; no points awarded here, so
// run the badge check explicitly. Never throws.
awaitcheckBadges(ctx.session.user.id);
return{
topics: row?.topics??topics,
onboardedAt: row?.onboardedAt??null,
};
}),
// Follow/mute topics from the controlled vocabulary — drives the "For you" feed.
getTopicPrefs: protectedProcedure.query(async({ ctx })=>{
returnctx.db
.select({
topicId: user_topic_pref.topicId,
slug: topic.slug,
label: topic.label,
pref: user_topic_pref.pref,
})
.from(user_topic_pref)
.innerJoin(topic,eq(user_topic_pref.topicId,topic.id))
.where(eq(user_topic_pref.userId,ctx.session.user.id));
}),
setTopicPref: protectedProcedure
.input(
z.object({
topicId: z.number().int().positive(),
pref: z.enum(["follow","mute","none"]),
}),
)
.mutation(async({ ctx, input })=>{
constuserId=ctx.session.user.id;
if(input.pref==="none"){
awaitctx.db
.delete(user_topic_pref)
.where(
and(
eq(user_topic_pref.userId,userId),
eq(user_topic_pref.topicId,input.topicId),
),
);
return{topicId: input.topicId,pref: null};
}
awaitctx.db
.insert(user_topic_pref)
.values({ userId,topicId: input.topicId,pref: input.pref})
.onConflictDoUpdate({
target: [user_topic_pref.userId,user_topic_pref.topicId],
set: {pref: input.pref},
});
return{topicId: input.topicId,pref: input.pref};
}),
edit: rateLimitedProcedure({
name: "profile-edit",
limit: 5,
windowMs: 10*60_000,
message:
"You're updating your profile too fast. Take a breather and try again.",
})
.input(saveSettingsSchema)
.mutation(async({ input, ctx })=>{
const{ email }=ctx.session.user;
if(!email){
thrownewTRPCError({
code: "BAD_REQUEST",
message: "Email not found",
});
}
// Usernames share the top-level namespace with routes/content, so block
// any handle that would collide with a reserved path.
if(isReservedUsername(input.username)){
thrownewTRPCError({
code: "BAD_REQUEST",
message: "That username is reserved.",
});
}
// Case-insensitive uniqueness (GitHub-style). The lower(username) index
// also enforces this; this check just gives a clean message.
consthandleClash=awaitctx.db.query.user.findFirst({
columns: {id: true},
where: (users)=>
and(
sql`lower(${users.username}) = ${input.username.toLowerCase()}`,
ne(users.id,ctx.session.user.id),
),
});
if(handleClash){
thrownewTRPCError({
code: "BAD_REQUEST",
message: "That username is already taken.",
});
}
constnewsletter=awaitisUserSubscribedToNewsletter(email);
if(newsletter!==input.newsletter){
constaction=input.newsletter ? "subscribe" : "unsubscribe";
if(!email){
thrownewTRPCError({
code: "BAD_REQUEST",
message: "Email not found",
});
}
constresponse=awaitmanageNewsletterSubscription(email,action);
if(!response){
thrownewTRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "Failed to update newsletter subscription",
});
}
}
// Explicitly whitelist updatable columns rather than spreading `input`,
// so a future field added to saveSettingsSchema can't silently become
// mass-assignable on the user row.
const[profile]=awaitctx.db
.update(user)
.set({
name: input.name,
bio: input.bio,
username: input.username,
location: input.location,
websiteUrl: input.websiteUrl,
emailNotifications: input.emailNotifications,
newsletter: input.newsletter,
})
.where(eq(user.id,ctx.session.user.id))
.returning();
if(!profile){
thrownewTRPCError({
code: "NOT_FOUND",
message: "Profile not found or update failed",
});
}
returnprofile;
}),
updateProfilePhotoUrl: protectedProcedure
.input(updateProfilePhotoUrlSchema)
.mutation(async({ input, ctx })=>{
const[profile]=awaitctx.db
.update(user)
.set({image: `${input.url}?id=${nanoid(3)}`})
.where(eq(user.id,ctx.session.user.id))
.returning();
if(!profile){
thrownewTRPCError({
code: "NOT_FOUND",
message: "Profile not found or update failed",
});
}
returnprofile;
}),
getUploadUrl: protectedProcedure
.input(uploadPhotoUrlSchema)
.mutation(async({ ctx, input })=>{
const{ size, type }=input;
constextension=type.split("/")[1];
constacceptedFormats=["jpg","jpeg","gif","png","webp"];
if(!acceptedFormats.includes(extension)){
thrownewTRPCError({
code: "BAD_REQUEST",
message: `Invalid file. Accepted file formats: ${acceptedFormats.join(
", ",
)}.`,
});
}
if(size>1048576*10){
thrownewTRPCError({
code: "BAD_REQUEST",
message: "Maximum file size 10mb",
});
}
constresponse=awaitgetPresignedUrl(type,size,{
kind: "user",
userId: ctx.session.user.id,
});
returnresponse;
}),
get: publicProcedure.input(getProfileSchema).query(async({ ctx, input })=>{
const{ username }=input;
// Handles resolve case-insensitively (GitHub-style).
const[profile]=awaitctx.db
.select()
.from(user)
.where(sql`lower(${user.username}) = ${username.toLowerCase()}`);
if(!profile){
thrownewTRPCError({
code: "NOT_FOUND",
message: "Profile not found",
});
}
returnprofile;
}),
// A user's comments/replies, newest first, each linked to the comment anchor
// on its published parent content. Profiles are public.
userReplies: publicProcedure
.input(getProfileSchema)
.query(async({ ctx, input })=>{
const{ username }=input;
const[profile]=awaitctx.db
.select({id: user.id})
.from(user)
.where(sql`lower(${user.username}) = ${username.toLowerCase()}`)
.limit(1);
if(!profile){
thrownewTRPCError({
code: "NOT_FOUND",
message: "Profile not found",
});
}
// Parent post's author drives member hrefs; aliased so it doesn't collide
// with any future join on the comment author.
constpostAuthor=alias(user,"post_author");
constrows=awaitctx.db
.select({
id: comments.id,
body: comments.body,
createdAt: comments.createdAt,
parentTitle: posts.title,
parentType: posts.type,
parentSlug: posts.slug,
sourceSlug: feedSources.slug,
authorUsername: postAuthor.username,
})
.from(comments)
.innerJoin(posts,eq(comments.postId,posts.id))
.leftJoin(feedSources,eq(posts.sourceId,feedSources.id))
.leftJoin(postAuthor,eq(posts.authorId,postAuthor.id))
.where(
and(
eq(comments.authorId,profile.id),
isNull(comments.deletedAt),
eq(posts.status,"published"),
),
)
.orderBy(desc(comments.createdAt))
.limit(30);
returnrows.map((r)=>({
id: r.id,
body: r.body,
createdAt: r.createdAt,
parent: {
title: r.parentTitle,
href: buildCommentHref({
commentId: r.id,
parentType: r.parentType,
parentSlug: r.parentSlug,
sourceSlug: r.sourceSlug,
authorUsername: r.authorUsername,
}),
},
}));
}),
updateEmail: rateLimitedProcedure({
name: "profile-update-email",
limit: 5,
windowMs: 10*60_000,
message:
"You're requesting email changes too fast. Take a breather and try again.",
})
.input(emailTokenReqSchema)
.mutation(async({ input, ctx })=>{
const{ newEmail }=input;
constuserId=ctx.session.user.id;
if(!newEmail){
thrownewTRPCError({
code: "BAD_REQUEST",
message: "Invalid request",
});
}
// Check if the new email is already in use
constexistingUser=awaitctx.db.query.user.findFirst({
where: eq(user.email,newEmail),
});
if(existingUser){
thrownewTRPCError({
code: "BAD_REQUEST",
message: "Unable to process the request",
});
}
// Rate limiting: Check for recent requests
consttwoMinutesAgo=newDate(Date.now()-2*60*1000);
constrecentRequest=awaitctx.db.query.emailChangeRequest.findFirst({
where: and(
eq(emailChangeRequest.userId,userId),
gte(emailChangeRequest.createdAt,twoMinutesAgo),// 2 minutes
),
});
if(recentRequest){
thrownewTRPCError({
code: "TOO_MANY_REQUESTS",
message: "Please wait before requesting another email change",
});
}
// Generate a new token and expiration date
consttoken=generateEmailToken();
constexpiresAt=newDate(Date.now()+TOKEN_EXPIRATION_TIME);
// Create a new email change request
awaitctx.db.insert(emailChangeRequest).values({
userId,
newEmail,
token,
expiresAt,
});
// Send verification email
try{
awaitsendVerificationEmail(newEmail,token);
}catch(error){
console.error("Failed to send verification email:",error);
thrownewTRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "Failed to send verification email",
});
}
return{message: "Verification email sent"};
}),
});