Repository navigation
feat: add public profiles - #1180
Conversation
|
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
WalkthroughThis update introduces several new features and components to manage user and team profiles, including the ability to view, update, and manage public profiles through new React components and backend functions. It also adds new functionality for avatar image management and incorporates ESLint rule modifications. Changes
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (invoked as PR comments)
Additionally, you can add CodeRabbit Configration File (
|
There was a problem hiding this comment.
Actionable comments posted: 0
Outside diff range and nitpick comments (1)
packages/trpc/server/profile-router/router.ts (1)
Line range hint
91-114: Ensure robust validation for public profile URL updates.The validation logic for the URL length is tied to the billing status, which is a good practice. However, consider adding more comprehensive validation for the URL format itself (e.g., regex validation to ensure it's a valid URL format). This would prevent potential issues with invalid URLs being stored in the database.
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Files selected for processing (2)
- packages/prisma/schema.prisma (4 hunks)
- packages/trpc/server/profile-router/router.ts (2 hunks)
Additional comments not posted (5)
packages/trpc/server/profile-router/router.ts (2)
Line range hint
91-114: Enhanced error handling in public profile updates.The error handling strategy using
AppError.parseErrorToTRPCErroris well-implemented. It ensures that only known errors are converted and thrown as TRPC errors, providing a cleaner error response to the client. Good job maintaining consistency in error handling across the application.
Line range hint
1-238: Review of unchanged segments in profile-router.The procedures for user management such as password updates, account deletion, and email confirmation are well implemented with proper error handling and input validation. No changes are suggested at this time.
packages/prisma/schema.prisma (3)
Line range hint
53-72: UserProfile model review.The
UserProfilemodel is well-structured with essential fields likeid,enabled,userId, andbio. The use of@default(false)for theenabledfield is a good security practice, ensuring profiles are not public by default. The relation with theUsermodel is correctly set withonDelete: Cascade, which will help maintain data integrity.
74-80: TeamProfile model review.The
TeamProfilemodel follows a similar structure to theUserProfile, with fields forid,enabled,teamId, andbio. The default settings and the relation to theTeammodel are appropriately configured. This consistency in modeling user and team profiles is beneficial for maintaining uniformity across the application.
595-596: Consider more meaningful defaults for public profile fields.As previously noted, the default values for
publicTitleandpublicDescriptionare empty strings. Consider setting more meaningful defaults or handling cases where these values are not provided by the user to enhance the user experience and data quality.
There was a problem hiding this comment.
Actionable comments posted: 12
Outside diff range and nitpick comments (2)
apps/web/src/app/(dashboard)/settings/profile/page.tsx (1)
Line range hint
6-22: Good integration of new form components.The new
AvatarImageFormandProfileFormare well integrated. Consider adding error handling or a loading state to improve user experience during asynchronous operations.export default async function ProfileSettingsPage() { + const [loading, setLoading] = useState(false); + const [error, setError] = useState(null); const { user } = await getRequiredServerComponentSession(); + if (loading) return <p>Loading...</p>; + if (error) return <p>Error: {error}</p>; return ( <div> <SettingsHeader title="Profile" subtitle="Here you can edit your personal details." /> <AvatarImageForm className="mb-8 max-w-xl" user={user} /> <ProfileForm className="mb-8 max-w-xl" user={user} /> <hr className="my-4 max-w-xl" /> <DeleteAccountDialog className="max-w-xl" user={user} /> </div> ); }packages/ui/primitives/avatar.tsx (1)
Line range hint
53-80: Enhancement: Improve accessibility and usability of AvatarWithText.The
AvatarWithTextcomponent could be improved by addingaltattributes to images for better accessibility and by ensuring that interactive elements are easily navigable and understandable.<Avatar className={cn('dark:border-border h-10 w-10 border-2 border-solid border-white', avatarClass)} > + {/* Ensure alt text is provided for better accessibility */} {avatarSrc && <AvatarImage src={avatarSrc} alt="User Avatar" />} <AvatarFallback className="text-xs text-gray-400">{avatarFallback}</AvatarFallback> </Avatar>
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Files ignored due to path filters (1)
package-lock.jsonis excluded by!**/package-lock.json
Files selected for processing (18)
- apps/web/src/app/(dashboard)/settings/profile/page.tsx (2 hunks)
- apps/web/src/app/(profile)/layout.tsx (1 hunks)
- apps/web/src/app/(profile)/p/[url]/page.tsx (1 hunks)
- apps/web/src/app/(profile)/profile-header.tsx (1 hunks)
- apps/web/src/app/(teams)/t/[teamUrl]/settings/page.tsx (3 hunks)
- apps/web/src/components/(dashboard)/layout/menu-switcher.tsx (4 hunks)
- apps/web/src/components/forms/avatar-image.tsx (1 hunks)
- apps/web/src/components/templates/manage-public-template-dialog.tsx (1 hunks)
- apps/web/src/pages/api/avatar/[id].tsx (1 hunks)
- packages/lib/package.json (2 hunks)
- packages/lib/server-only/profile/get-avatar-image.ts (1 hunks)
- packages/lib/server-only/profile/get-public-profile-by-url.ts (1 hunks)
- packages/lib/server-only/profile/set-avatar-image.ts (1 hunks)
- packages/prisma/migrations/20240627050809_add_avatar_image_model/migration.sql (1 hunks)
- packages/prisma/schema.prisma (5 hunks)
- packages/trpc/server/profile-router/router.ts (5 hunks)
- packages/trpc/server/profile-router/schema.ts (1 hunks)
- packages/ui/primitives/avatar.tsx (3 hunks)
Files skipped from review due to trivial changes (1)
- packages/lib/package.json
Files skipped from review as they are similar to previous changes (2)
- packages/prisma/schema.prisma
- packages/trpc/server/profile-router/router.ts
Additional context used
Biome
apps/web/src/components/forms/avatar-image.tsx
[error] 156-160: Provide an explicit type prop for the button element.
The default type of a button is submit, which causes the submission of a form when placed inside a
formelement. This is likely not the behaviour that you want inside a React application.
Allowed button types are: submit, button or reset(lint/a11y/useButtonType)
Additional comments not posted (9)
packages/trpc/server/profile-router/schema.ts (2)
74-77: Refinement: Clarify nullable fields in schema.The
ZSetProfileImageMutationSchemashould clearly document why fields likebytesandteamIdare nullable to avoid confusion and ensure correct usage.Consider adding comments or documentation in the code to explain the circumstances under which these fields can be null.
5-5: Configuration: Validate bio length configuration.Ensure that the
MAX_PROFILE_BIO_LENGTHis configured appropriately based on user requirements and UI constraints. It's currently set to 256, which might be too long or too short depending on the application context.Verification successful
Configuration: Validate bio length configuration.
The
MAX_PROFILE_BIO_LENGTHis consistently used across both backend and frontend files, ensuring that the bio length constraint is enforced uniformly. The current length of 256 characters appears to be properly integrated into the system.
Backend Usage:
packages/trpc/server/profile-router/schema.ts
- Line 5:
export const MAX_PROFILE_BIO_LENGTH = 256;- Line 10:
.max(MAX_PROFILE_BIO_LENGTH, { message:Bio must be shorter than ${MAX_PROFILE_BIO_LENGTH + 1} characters})Frontend Usage:
apps/web/src/components/forms/public-profile-form.tsx
- Line 10:
MAX_PROFILE_BIO_LENGTH- Line 20:
const remaningLength = MAX_PROFILE_BIO_LENGTH - (field.value || '').length;Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check the usage of MAX_PROFILE_BIO_LENGTH across the frontend to ensure it aligns with UI constraints. # Test: Search for MAX_PROFILE_BIO_LENGTH usage in frontend components. Expect: Consistent usage that matches the declared limit. rg --type typescript 'MAX_PROFILE_BIO_LENGTH'Length of output: 80
Script:
#!/bin/bash # Description: Check the usage of MAX_PROFILE_BIO_LENGTH across the codebase to ensure it aligns with UI constraints. # Test: Search for MAX_PROFILE_BIO_LENGTH usage in TypeScript files. Expect: Consistent usage that matches the declared limit. rg --type ts 'MAX_PROFILE_BIO_LENGTH'Length of output: 561
apps/web/src/components/forms/avatar-image.tsx (2)
32-34: Add a detailed comment explaining the purpose ofZAvatarImageFormSchema.It's a best practice to document the purpose of schemas, especially when they are used for form validation. This helps other developers understand the context and constraints being applied.
44-188: Ensure proper error handling and user feedback mechanisms are in place.The component handles avatar image uploads and updates. Ensure that all potential errors (e.g., network issues, server errors) are caught and appropriate user feedback is provided. This is crucial for improving user experience and debugging.
Verification successful
Proper error handling and user feedback mechanisms are in place.
The
AvatarImageFormcomponent handles errors appropriately by catching exceptions and displaying relevant error messages to the user.
- The
catchblock handlesTRPCClientErrorwith specific messages forBAD_REQUESTand general messages for other errors.Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check for proper error handling in avatar image handling. # Test: Search for error handling patterns. Expect: Proper error handling mechanisms. rg --type typescript "catch" "apps/web/src/components/forms/avatar-image.tsx"Length of output: 110
Script:
#!/bin/bash # Description: Check for proper error handling in avatar image handling. # Test: Search for error handling patterns. Expect: Proper error handling mechanisms. rg "catch" "apps/web/src/components/forms/avatar-image.tsx"Length of output: 77
Script:
#!/bin/bash # Description: Extract and review the catch block to verify error handling and user feedback. # Test: Extract lines containing catch block and surrounding code for context. rg -A 10 -B 10 "catch" "apps/web/src/components/forms/avatar-image.tsx"Length of output: 626
Tools
Biome
[error] 156-160: Provide an explicit type prop for the button element.
The default type of a button is submit, which causes the submission of a form when placed inside a
formelement. This is likely not the behaviour that you want inside a React application.
Allowed button types are: submit, button or reset(lint/a11y/useButtonType)
apps/web/src/app/(teams)/t/[teamUrl]/settings/page.tsx (1)
16-16: Confirm the integration ofAvatarImageFormin the team settings page.Ensure that the
AvatarImageFormis properly integrated and configured to handle team-specific data. Check if the form's props are correctly passed and if it functions as expected in the team context.Verification successful
The integration of
AvatarImageFormin the team settings page is properly configured.
AvatarImageFormis imported and used with the necessary props (teamandsession.user).teamandsession.userare correctly defined and passed toAvatarImageForm.Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify the integration of AvatarImageForm in the team settings page. # Test: Search for AvatarImageForm usage in the team settings page. Expect: Proper configuration and usage. rg --type typescript "AvatarImageForm" "apps/web/src/app/(teams)/t/[teamUrl]/settings/page.tsx"Length of output: 130
Script:
#!/bin/bash # Description: Verify the integration of AvatarImageForm in the team settings page. # Test: Search for AvatarImageForm usage in the team settings page. Expect: Proper configuration and usage. rg "AvatarImageForm" "apps/web/src/app/(teams)/t/[teamUrl]/settings/page.tsx"Length of output: 219
Script:
#!/bin/bash # Description: Verify the definitions of `team` and `session.user` in the team settings page. # Test: Search for `team` and `session.user` definitions in the team settings page. Expect: Proper configuration and usage. rg "const team|const session" "apps/web/src/app/(teams)/t/[teamUrl]/settings/page.tsx"Length of output: 222
apps/web/src/app/(profile)/p/[url]/page.tsx (2)
25-28: Ensure correct usage ofPublicProfilePageProps.The
PublicProfilePagePropsshould be clearly documented and used consistently throughout the component to ensure that all necessary data is passed correctly.
42-193: Review the handling of non-existent or disabled public profiles.Ensure that the logic for redirecting or showing a not found page when the public profile is non-existent or disabled is robust and user-friendly.
Verification successful
Review the handling of non-existent or disabled public profiles.
The logic for redirecting or showing a not found page when the public profile is non-existent or disabled is correctly implemented using the
notFoundfunction at line 54. This ensures that the user is appropriately informed when accessing an invalid profile.
- Line 54:
notFound();Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check the handling of non-existent or disabled public profiles. # Test: Search for logic handling non-existent or disabled profiles. Expect: Robust and user-friendly handling. rg --type typescript "notFound" "apps/web/src/app/(profile)/p/[url]/page.tsx"Length of output: 112
Script:
#!/bin/bash # Description: Check the handling of non-existent or disabled public profiles. # Test: Search for logic handling non-existent or disabled profiles. Expect: Robust and user-friendly handling. rg --type tsx "notFound" "apps/web/src/app/(profile)/p/[url]/page.tsx"Length of output: 98
Script:
#!/bin/bash # Description: Check the handling of non-existent or disabled public profiles. # Test: Search for logic handling non-existent or disabled profiles. Expect: Robust and user-friendly handling. ast-grep --lang tsx --pattern 'notFound()' "apps/web/src/app/(profile)/p/[url]/page.tsx"Length of output: 153
apps/web/src/components/(dashboard)/layout/menu-switcher.tsx (1)
103-105: Ensure correct avatar image URL formation.Verify that the avatar image URL is correctly formed and handles cases where the avatar image ID might be null or undefined.
Verification successful
Ensure correct avatar image URL formation.
The avatar image URL formation correctly handles cases where the avatar image ID might be null or undefined.
- The code checks for the existence of
avatarImageIdbefore forming the URL.Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check the formation of avatar image URLs. # Test: Search for avatar image URL formation logic. Expect: Correct handling of null or undefined IDs. rg --type typescript "avatarImageId" "apps/web/src/components/(dashboard)/layout/menu-switcher.tsx"Length of output: 134
Script:
#!/bin/bash # Description: Check the formation of avatar image URLs. # Test: Search for avatar image URL formation logic. Expect: Correct handling of null or undefined IDs. # Correcting the file type for TypeScript rg --glob '*.ts' --glob '*.tsx' "avatarImageId" "apps/web/src/components/(dashboard)/layout/menu-switcher.tsx"Length of output: 447
apps/web/src/components/templates/manage-public-template-dialog.tsx (1)
85-429: Review theManagePublicTemplateDialogfor best practices and potential improvements.Consider refactoring the
ManagePublicTemplateDialogto separate concerns more clearly:
- Extract form handling into a custom hook.
- Move the dialog content rendering into smaller, manageable components.
This will improve readability and maintainability.
| <button | ||
| className="bg-background/70 text-destructive absolute inset-0 flex cursor-pointer items-center justify-center text-xs opacity-0 transition-opacity hover:opacity-100" | ||
| disabled={form.formState.isSubmitting} | ||
| onClick={() => void onFormSubmit({ bytes: null })} | ||
| > |
There was a problem hiding this comment.
Specify the button type to avoid form submission issues.
The button within the form does not specify its type, which can lead to unintended form submissions as the default type for a button in a form is 'submit'.
- <button className="bg-background/70 text-destructive absolute inset-0 flex cursor-pointer items-center justify-center text-xs opacity-0 transition-opacity hover:opacity-100" disabled={form.formState.isSubmitting} onClick={() => void onFormSubmit({ bytes: null })}>
+ <button type="button" className="bg-background/70 text-destructive absolute inset-0 flex cursor-pointer items-center justify-center text-xs opacity-0 transition-opacity hover:opacity-100" disabled={form.formState.isSubmitting} onClick={() => void onFormSubmit({ bytes: null })}>Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| <button | |
| className="bg-background/70 text-destructive absolute inset-0 flex cursor-pointer items-center justify-center text-xs opacity-0 transition-opacity hover:opacity-100" | |
| disabled={form.formState.isSubmitting} | |
| onClick={() => void onFormSubmit({ bytes: null })} | |
| > | |
| <button | |
| type="button" | |
| className="bg-background/70 text-destructive absolute inset-0 flex cursor-pointer items-center justify-center text-xs opacity-0 transition-opacity hover:opacity-100" | |
| disabled={form.formState.isSubmitting} | |
| onClick={() => void onFormSubmit({ bytes: null })} | |
| > |
Tools
Biome
[error] 156-160: Provide an explicit type prop for the button element.
The default type of a button is submit, which causes the submission of a form when placed inside a
formelement. This is likely not the behaviour that you want inside a React application.
Allowed button types are: submit, button or reset(lint/a11y/useButtonType)
| export const getAvatarImage = async ({ id }: GetAvatarImageOptions) => { | ||
| const avatarImage = await prisma.avatarImage.findFirst({ | ||
| where: { | ||
| id, | ||
| }, | ||
| }); | ||
|
|
||
| if (!avatarImage) { | ||
| return null; | ||
| } | ||
|
|
||
| const bytes = Buffer.from(avatarImage.bytes, 'base64'); | ||
|
|
||
| return { | ||
| contentType: 'image/jpeg', | ||
| content: await sharp(bytes).toFormat('jpeg').toBuffer(), | ||
| }; | ||
| }; |
There was a problem hiding this comment.
Well-structured image retrieval and processing function.
The function correctly retrieves and processes avatar images. Consider adding a try-catch block around the Sharp image processing to handle any potential exceptions that might occur during the conversion.
try {
return {
contentType: 'image/jpeg',
content: await sharp(bytes).toFormat('jpeg').toBuffer(),
};
} catch (error) {
console.error('Failed to process image', error);
return null;
}Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| export const getAvatarImage = async ({ id }: GetAvatarImageOptions) => { | |
| const avatarImage = await prisma.avatarImage.findFirst({ | |
| where: { | |
| id, | |
| }, | |
| }); | |
| if (!avatarImage) { | |
| return null; | |
| } | |
| const bytes = Buffer.from(avatarImage.bytes, 'base64'); | |
| return { | |
| contentType: 'image/jpeg', | |
| content: await sharp(bytes).toFormat('jpeg').toBuffer(), | |
| }; | |
| }; | |
| export const getAvatarImage = async ({ id }: GetAvatarImageOptions) => { | |
| const avatarImage = await prisma.avatarImage.findFirst({ | |
| where: { | |
| id, | |
| }, | |
| }); | |
| if (!avatarImage) { | |
| return null; | |
| } | |
| const bytes = Buffer.from(avatarImage.bytes, 'base64'); | |
| try { | |
| return { | |
| contentType: 'image/jpeg', | |
| content: await sharp(bytes).toFormat('jpeg').toBuffer(), | |
| }; | |
| } catch (error) { | |
| console.error('Failed to process image', error); | |
| return null; | |
| } | |
| }; |
| ALTER TABLE "Team" ADD COLUMN "avatarImageId" TEXT; | ||
|
|
||
| -- AlterTable | ||
| ALTER TABLE "User" ADD COLUMN "avatarImageId" TEXT; | ||
|
|
||
| -- CreateTable | ||
| CREATE TABLE "AvatarImage" ( | ||
| "id" TEXT NOT NULL, | ||
| "bytes" TEXT NOT NULL, | ||
|
|
||
| CONSTRAINT "AvatarImage_pkey" PRIMARY KEY ("id") | ||
| ); | ||
|
|
||
| -- AddForeignKey | ||
| ALTER TABLE "User" ADD CONSTRAINT "User_avatarImageId_fkey" FOREIGN KEY ("avatarImageId") REFERENCES "AvatarImage"("id") ON DELETE SET NULL ON UPDATE CASCADE; | ||
|
|
||
| -- AddForeignKey | ||
| ALTER TABLE "Team" ADD CONSTRAINT "Team_avatarImageId_fkey" FOREIGN KEY ("avatarImageId") REFERENCES "AvatarImage"("id") ON DELETE SET NULL ON UPDATE CASCADE; |
There was a problem hiding this comment.
Consider optimizing data types for foreign keys.
The use of 'TEXT' data type for 'avatarImageId' might not be optimal. Consider using 'INTEGER' or 'UUID' for better performance and compatibility with other systems.
- ALTER TABLE "Team" ADD COLUMN "avatarImageId" TEXT;
+ ALTER TABLE "Team" ADD COLUMN "avatarImageId" UUID;
- ALTER TABLE "User" ADD COLUMN "avatarImageId" TEXT;
+ ALTER TABLE "User" ADD COLUMN "avatarImageId" UUID;Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| ALTER TABLE "Team" ADD COLUMN "avatarImageId" TEXT; | |
| -- AlterTable | |
| ALTER TABLE "User" ADD COLUMN "avatarImageId" TEXT; | |
| -- CreateTable | |
| CREATE TABLE "AvatarImage" ( | |
| "id" TEXT NOT NULL, | |
| "bytes" TEXT NOT NULL, | |
| CONSTRAINT "AvatarImage_pkey" PRIMARY KEY ("id") | |
| ); | |
| -- AddForeignKey | |
| ALTER TABLE "User" ADD CONSTRAINT "User_avatarImageId_fkey" FOREIGN KEY ("avatarImageId") REFERENCES "AvatarImage"("id") ON DELETE SET NULL ON UPDATE CASCADE; | |
| -- AddForeignKey | |
| ALTER TABLE "Team" ADD CONSTRAINT "Team_avatarImageId_fkey" FOREIGN KEY ("avatarImageId") REFERENCES "AvatarImage"("id") ON DELETE SET NULL ON UPDATE CASCADE; | |
| ALTER TABLE "Team" ADD COLUMN "avatarImageId" UUID; | |
| -- AlterTable | |
| ALTER TABLE "User" ADD COLUMN "avatarImageId" UUID; | |
| -- CreateTable | |
| CREATE TABLE "AvatarImage" ( | |
| "id" TEXT NOT NULL, | |
| "bytes" TEXT NOT NULL, | |
| CONSTRAINT "AvatarImage_pkey" PRIMARY KEY ("id") | |
| ); | |
| -- AddForeignKey | |
| ALTER TABLE "User" ADD CONSTRAINT "User_avatarImageId_fkey" FOREIGN KEY ("avatarImageId") REFERENCES "AvatarImage"("id") ON DELETE SET NULL ON UPDATE CASCADE; | |
| -- AddForeignKey | |
| ALTER TABLE "Team" ADD CONSTRAINT "Team_avatarImageId_fkey" FOREIGN KEY ("avatarImageId") REFERENCES "AvatarImage"("id") ON DELETE SET NULL ON UPDATE CASCADE; |
| export default async function handler(req: NextApiRequest, res: NextApiResponse) { | ||
| if (req.method !== 'GET') { | ||
| return res.status(405).json({ | ||
| status: 'error', | ||
| message: 'Method not allowed', | ||
| }); | ||
| } | ||
|
|
||
| const { id } = req.query; | ||
|
|
||
| if (typeof id !== 'string') { | ||
| return res.status(400).json({ | ||
| status: 'error', | ||
| message: 'Missing id', | ||
| }); | ||
| } | ||
|
|
||
| const result = await getAvatarImage({ id }); | ||
|
|
||
| if (!result) { | ||
| return res.status(404).json({ | ||
| status: 'error', | ||
| message: 'Not found', | ||
| }); | ||
| } | ||
|
|
||
| res.setHeader('Content-Type', result.contentType); | ||
| res.setHeader('Cache-Control', 'public, max-age=31536000, immutable'); | ||
| res.send(result.content); | ||
| } |
There was a problem hiding this comment.
Robust API handler but consider enhancing error handling and security.
The API handler correctly manages different HTTP methods and parameter validation. Consider adding more detailed error responses and rate limiting to enhance security and user feedback.
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
+ // Implement rate limiting here
if (req.method !== 'GET') {
return res.status(405).json({
status: 'error',
message: 'Method not allowed',
});
}
const { id } = req.query;
if (typeof id !== 'string') {
return res.status(400).json({
status: 'error',
message: 'Missing id',
});
}
const result = await getAvatarImage({ id });
if (!result) {
return res.status(404).json({
status: 'error',
message: 'Not found',
});
}
res.setHeader('Content-Type', result.contentType);
res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
res.send(result.content);
}Committable suggestion was skipped due to low confidence.
| // TODO: Audit Logs | ||
| } else { | ||
| await prisma.user.update({ | ||
| where: { | ||
| id: userId, | ||
| }, | ||
| data: { | ||
| avatarImageId: newAvatarImageId, | ||
| }, | ||
| }); | ||
|
|
||
| // TODO: Audit Logs | ||
| } |
There was a problem hiding this comment.
TODO: Address audit logging.
The TODO comment about audit logs is critical for maintaining traceability and accountability, especially for operations that alter user or team data.
Would you like assistance in implementing the audit logging functionality? I can provide sample code or open a GitHub issue to track this task.
| if (!team) { | ||
| throw new Error('Team not found'); | ||
| } |
There was a problem hiding this comment.
Error Handling: Improve team not found error handling.
Similar to the user not found error, consider logging additional details when a team is not found.
if (!team) {
+ // Consider logging this error to help with debugging or tracking issues with team data retrieval.
throw new Error('Team not found');
}Committable suggestion was skipped due to low confidence.
| bio: z | ||
| .string() | ||
| .max(MAX_PROFILE_BIO_LENGTH, { | ||
| message: `Bio must be shorter than ${MAX_PROFILE_BIO_LENGTH + 1} characters`, | ||
| }) | ||
| .optional(), | ||
| enabled: z.boolean().optional(), | ||
| url: z | ||
| .string() | ||
| .trim() | ||
| .toLowerCase() | ||
| .min(1, { message: 'Please enter a valid username.' }) | ||
| .regex(/^[a-z0-9-]+$/, { | ||
| message: 'Username can only container alphanumeric characters and dashes.', | ||
| }), | ||
| }) | ||
| .optional(), |
There was a problem hiding this comment.
Refinement: Enhance URL validation logic.
The regex for validating URLs could be made more robust to include other valid characters such as underscores or periods, depending on the application's requirements.
- .regex(/^[a-z0-9-]+$/, {
+ .regex(/^[a-z0-9-_\.]+$/, {
message: 'Username can only container alphanumeric characters, dashes, underscores, and periods.',
})Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| bio: z | |
| .string() | |
| .max(MAX_PROFILE_BIO_LENGTH, { | |
| message: `Bio must be shorter than ${MAX_PROFILE_BIO_LENGTH + 1} characters`, | |
| }) | |
| .optional(), | |
| enabled: z.boolean().optional(), | |
| url: z | |
| .string() | |
| .trim() | |
| .toLowerCase() | |
| .min(1, { message: 'Please enter a valid username.' }) | |
| .regex(/^[a-z0-9-]+$/, { | |
| message: 'Username can only container alphanumeric characters and dashes.', | |
| }), | |
| }) | |
| .optional(), | |
| bio: z | |
| .string() | |
| .max(MAX_PROFILE_BIO_LENGTH, { | |
| message: `Bio must be shorter than ${MAX_PROFILE_BIO_LENGTH + 1} characters`, | |
| }) | |
| .optional(), | |
| enabled: z.boolean().optional(), | |
| url: z | |
| .string() | |
| .trim() | |
| .toLowerCase() | |
| .min(1, { message: 'Please enter a valid username.' }) | |
| .regex(/^[a-z0-9-_\.]+$/, { | |
| message: 'Username can only container alphanumeric characters, dashes, underscores, and periods.', | |
| }) | |
| .optional(), |
| export const ProfileHeader = ({ user, teams = [] }: ProfileHeaderProps) => { | ||
| const [scrollY, setScrollY] = useState(0); | ||
|
|
||
| useEffect(() => { | ||
| const onScroll = () => { | ||
| setScrollY(window.scrollY); | ||
| }; | ||
|
|
||
| window.addEventListener('scroll', onScroll); | ||
|
|
||
| return () => window.removeEventListener('scroll', onScroll); | ||
| }, []); | ||
|
|
||
| if (user) { | ||
| return <AuthenticatedHeader user={user} teams={teams} />; | ||
| } | ||
|
|
||
| return ( | ||
| <header | ||
| className={cn( | ||
| 'supports-backdrop-blur:bg-background/60 bg-background/95 sticky top-0 z-[60] flex h-16 w-full items-center border-b border-b-transparent backdrop-blur duration-200', | ||
| scrollY > 5 && 'border-b-border', | ||
| )} | ||
| > | ||
| <div className="mx-auto flex w-full max-w-screen-xl items-center justify-between gap-x-4 px-4 md:px-8"> | ||
| <Link | ||
| href="/" | ||
| className="focus-visible:ring-ring ring-offset-background rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 md:inline" | ||
| > | ||
| <Logo className="hidden h-6 w-auto sm:block" /> | ||
|
|
||
| <Image | ||
| src={LogoIcon} | ||
| alt="Documenso Logo" | ||
| width={48} | ||
| height={48} | ||
| className="h-10 w-auto dark:invert sm:hidden" | ||
| /> | ||
| </Link> | ||
|
|
||
| <div className="flex flex-row items-center justify-center"> | ||
| <p className="text-muted-foreground mr-4"> | ||
| <span className="text-sm sm:hidden">Want your own public profile?</span> | ||
| <span className="hidden text-sm sm:block"> | ||
| Like to have your own public profile with agreements? | ||
| </span> | ||
| </p> | ||
|
|
||
| <Button asChild variant="secondary"> | ||
| <Link href="/signup"> | ||
| <div className="hidden flex-row items-center sm:flex"> | ||
| <PlusIcon className="mr-1 h-5 w-5" /> | ||
| Create now | ||
| </div> | ||
|
|
||
| <span className="sm:hidden">Create</span> | ||
| </Link> | ||
| </Button> | ||
| </div> | ||
| </div> | ||
| </header> | ||
| ); |
There was a problem hiding this comment.
Enhancement: Optimize scroll event handling in ProfileHeader.
The scroll event listener in ProfileHeader can be optimized to prevent excessive re-renders or state updates, which could impact performance, especially on devices with lower resources.
useEffect(() => {
const onScroll = () => {
+ // Throttle scroll updates to reduce performance impact
+ requestAnimationFrame(() => {
setScrollY(window.scrollY);
+ });
};
window.addEventListener('scroll', onScroll);
return () => window.removeEventListener('scroll', onScroll);
}, []);Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| export const ProfileHeader = ({ user, teams = [] }: ProfileHeaderProps) => { | |
| const [scrollY, setScrollY] = useState(0); | |
| useEffect(() => { | |
| const onScroll = () => { | |
| setScrollY(window.scrollY); | |
| }; | |
| window.addEventListener('scroll', onScroll); | |
| return () => window.removeEventListener('scroll', onScroll); | |
| }, []); | |
| if (user) { | |
| return <AuthenticatedHeader user={user} teams={teams} />; | |
| } | |
| return ( | |
| <header | |
| className={cn( | |
| 'supports-backdrop-blur:bg-background/60 bg-background/95 sticky top-0 z-[60] flex h-16 w-full items-center border-b border-b-transparent backdrop-blur duration-200', | |
| scrollY > 5 && 'border-b-border', | |
| )} | |
| > | |
| <div className="mx-auto flex w-full max-w-screen-xl items-center justify-between gap-x-4 px-4 md:px-8"> | |
| <Link | |
| href="/" | |
| className="focus-visible:ring-ring ring-offset-background rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 md:inline" | |
| > | |
| <Logo className="hidden h-6 w-auto sm:block" /> | |
| <Image | |
| src={LogoIcon} | |
| alt="Documenso Logo" | |
| width={48} | |
| height={48} | |
| className="h-10 w-auto dark:invert sm:hidden" | |
| /> | |
| </Link> | |
| <div className="flex flex-row items-center justify-center"> | |
| <p className="text-muted-foreground mr-4"> | |
| <span className="text-sm sm:hidden">Want your own public profile?</span> | |
| <span className="hidden text-sm sm:block"> | |
| Like to have your own public profile with agreements? | |
| </span> | |
| </p> | |
| <Button asChild variant="secondary"> | |
| <Link href="/signup"> | |
| <div className="hidden flex-row items-center sm:flex"> | |
| <PlusIcon className="mr-1 h-5 w-5" /> | |
| Create now | |
| </div> | |
| <span className="sm:hidden">Create</span> | |
| </Link> | |
| </Button> | |
| </div> | |
| </div> | |
| </header> | |
| ); | |
| useEffect(() => { | |
| const onScroll = () => { | |
| // Throttle scroll updates to reduce performance impact | |
| requestAnimationFrame(() => { | |
| setScrollY(window.scrollY); | |
| }); | |
| }; | |
| window.addEventListener('scroll', onScroll); | |
| return () => window.removeEventListener('scroll', onScroll); | |
| }, []); |
| }; | ||
| } | ||
|
|
||
| throw new AppError(AppErrorCode.NOT_FOUND, 'Profile not found'); |
There was a problem hiding this comment.
Error Handling: Enhance 'Profile not found' error response.
When a profile is not found, consider providing suggestions or actions the user can take, which could improve user experience and help in troubleshooting.
throw new AppError(AppErrorCode.NOT_FOUND, 'Profile not found');
+ // Consider adding a link to the help center or support for further assistance.Committable suggestion was skipped due to low confidence.
| // Log as critical error. | ||
| if (user?.profile && team?.profile) { | ||
| console.error('Profile URL is ambiguous', { profileUrl, userId: user.id, teamId: team.id }); | ||
| throw new AppError(AppErrorCode.INVALID_REQUEST, 'Profile URL is ambiguous'); |
There was a problem hiding this comment.
Error Handling: Address ambiguous profile URL issue.
The error handling for ambiguous profile URLs could be improved by providing more detailed error messages and possibly suggesting corrective actions to the user.
if (user?.profile && team?.profile) {
console.error('Profile URL is ambiguous', { profileUrl, userId: user.id, teamId: team.id });
+ // Provide a more user-friendly error message and possible actions to resolve the ambiguity
throw new AppError(AppErrorCode.INVALID_REQUEST, 'The profile URL matches both a user and a team. Please specify if you are looking for a user or team profile.');
}Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| // Log as critical error. | |
| if (user?.profile && team?.profile) { | |
| console.error('Profile URL is ambiguous', { profileUrl, userId: user.id, teamId: team.id }); | |
| throw new AppError(AppErrorCode.INVALID_REQUEST, 'Profile URL is ambiguous'); | |
| // Log as critical error. | |
| if (user?.profile && team?.profile) { | |
| console.error('Profile URL is ambiguous', { profileUrl, userId: user.id, teamId: team.id }); | |
| // Provide a more user-friendly error message and possible actions to resolve the ambiguity | |
| throw new AppError(AppErrorCode.INVALID_REQUEST, 'The profile URL matches both a user and a team. Please specify if you are looking for a user or team profile.'); |
There was a problem hiding this comment.
Actionable comments posted: 0
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Files selected for processing (1)
- apps/web/src/components/forms/avatar-image.tsx (1 hunks)
Files skipped from review as they are similar to previous changes (1)
- apps/web/src/components/forms/avatar-image.tsx
Description
Add public profiles
Changes
/p/<url>Draft
Summary by CodeRabbit
New Features
Enhancements
Bug Fixes
Documentation