Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature/auth #33

Merged
merged 18 commits into from
Nov 10, 2024
Merged

feature/auth #33

merged 18 commits into from
Nov 10, 2024

Conversation

wtfdivyansh
Copy link
Contributor

@wtfdivyansh wtfdivyansh commented Nov 10, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced SignInComponent and SignUpComponent for improved sign-in and sign-up functionality.
  • Bug Fixes

    • Enhanced error handling in sign-in and sign-up processes to provide user feedback.
  • Removals

    • Removed legacy components and layouts for sign-in, streamlining the user experience.
  • Dependencies

    • Updated React and React DOM to the latest release candidate version.
    • Removed unnecessary dependencies to optimize the project.

Copy link

vercel bot commented Nov 10, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
plura-app ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 10, 2024 11:33am
plura-web ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 10, 2024 11:33am

Copy link

coderabbitai bot commented Nov 10, 2024

Walkthrough

The pull request introduces several changes across multiple files, primarily focusing on API route handling and component structure. The OPTIONS method in route.ts has been restructured for module visibility while maintaining existing CORS configurations. Additionally, the sign-in and sign-up components have been renamed and their import paths updated. Two files, layout.tsx and page.tsx for the sign-in functionality, have been removed, indicating a shift in the layout and structure. The package.json file reflects updates to dependencies, including the removal of certain libraries and an upgrade to React.

Changes

File Path Change Summary
apps/api/app/api/[[...route]]/route.ts OPTIONS method visibility changed; now a local constant. OPTIONS added to export statement.
apps/www/app/(auth)/sign-in/page.tsx SignIn component renamed to SignInComponent; import path updated.
apps/www/app/(auth)/sign-up/page.tsx SignUp component renamed to SignUpComponent; import path updated.
apps/www/app/sign-in/[[...sign-in]]/layout.tsx AppLayout component removed; layout functionality eliminated.
apps/www/app/sign-in/[[...sign-in]]/page.tsx SignInPage component removed; sign-in page functionality eliminated.
apps/www/components/custom/signinComponent.tsx SignIn function renamed to SignInComponent; functionality unchanged.
apps/www/components/custom/signupComponent.tsx SignUp function renamed to SignUpComponent; functionality unchanged.
apps/www/package.json Removed dependencies: @radix-ui/react-scroll-area, react-icons; updated react and react-dom versions.

Possibly related PRs

  • route error fix #18: Modifications to the route.ts file related to API route handling, directly connected to the changes made in the main PR regarding the OPTIONS method.
  • feat/(usage_page) #21: Introduces a new AppLayout component and modifies layout structure, potentially relevant to the overall API route handling and organization.

🐰 In a world of routes and signs,
A rabbit hops through code designs.
With components fresh and paths anew,
The API dances, swift and true!
So let’s rejoice in changes bright,
For every hop brings code delight! 🐇✨


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?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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 using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

vercel bot commented Nov 10, 2024

@github-actions[bot] is attempting to deploy a commit to the BlueFinZ Team on Vercel.

A member of the Team first needs to authorize it.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (8)
apps/www/components/custom/signinComponent.tsx (4)

24-24: Consider a more descriptive component name.

While renaming to SignInComponent maintains consistency with SignUpComponent, consider using a more specific name like EmailSignInForm to better describe the component's purpose and authentication method.

-export default function SignInComponent() {
+export default function EmailSignInForm() {

Line range hint 18-21: Enhance password validation rules.

The current password validation only checks for minimum length. Consider adding:

  • Maximum length constraint
  • Complexity requirements (uppercase, lowercase, numbers, special characters)
  • Common password prevention
 const formSchema = z.object({
   email: z.string().email(),
-  password: z.string().min(8),
+  password: z.string()
+    .min(8, "Password must be at least 8 characters")
+    .max(100, "Password is too long")
+    .regex(
+      /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]+$/,
+      "Password must contain uppercase, lowercase, number and special character"
+    ),
 });

Line range hint 31-45: Improve error handling and submission flow.

Several improvements are needed in the form submission logic:

  1. Replace alert with a more user-friendly error display
  2. Make callback URL configurable
  3. Add loading state during submission
  4. Implement proper success handling
+  const [isSubmitting, setIsSubmitting] = useState(false);
   const onSubmit = async (SignInData: z.infer<typeof formSchema>) => {
+    setIsSubmitting(true);
     const { data, error } = await authClient.signIn.email(
       {
         email: SignInData.email,
         password: SignInData.password,
-        callbackURL: "/dashboard",
+        callbackURL: process.env.NEXT_PUBLIC_AUTH_CALLBACK_URL || "/dashboard",
       },
       {
-        onRequest: (ctx) => {},
-        onSuccess: (ctx) => {},
+        onRequest: (ctx) => {
+          setIsSubmitting(true);
+        },
+        onSuccess: (ctx) => {
+          router.push("/dashboard");
+        },
         onError: (ctx) => {
-          alert(ctx.error.message);
+          toast.error(ctx.error.message);
+          setIsSubmitting(false);
         },
       },
     );
   };

Don't forget to:

  1. Import required dependencies (useState, useRouter, toast)
  2. Add loading state to the submit button
  3. Configure environment variables for the callback URL

Line range hint 52-78: Enhance form UX with essential features.

The current form lacks several important UX features:

  1. Meaningful input placeholders
  2. Password visibility toggle
  3. "Remember me" option
  4. Social login alternatives
 <FormField
   control={form.control}
   name="email"
   render={({ field }) => (
     <FormItem>
       <FormLabel>email</FormLabel>
       <FormControl>
-        <Input placeholder="shadcn" {...field} />
+        <Input placeholder="Enter your email" type="email" {...field} />
       </FormControl>
       <FormMessage />
     </FormItem>
   )}
 />
 <FormField
   control={form.control}
   name="password"
   render={({ field }) => (
     <FormItem>
       <FormLabel>password</FormLabel>
       <FormControl>
-        <Input placeholder="shadcn" type="password" {...field} />
+        <div className="relative">
+          <Input
+            placeholder="Enter your password"
+            type={showPassword ? "text" : "password"}
+            {...field}
+          />
+          <Button
+            type="button"
+            variant="ghost"
+            className="absolute right-2 top-1/2 -translate-y-1/2"
+            onClick={() => setShowPassword(!showPassword)}
+          >
+            {showPassword ? <EyeOffIcon /> : <EyeIcon />}
+          </Button>
+        </div>
       </FormControl>
       <FormMessage />
     </FormItem>
   )}
 />
+<FormField
+  control={form.control}
+  name="remember"
+  render={({ field }) => (
+    <FormItem className="flex items-center space-x-2">
+      <FormControl>
+        <Checkbox
+          checked={field.value}
+          onCheckedChange={field.onChange}
+        />
+      </FormControl>
+      <FormLabel>Remember me</FormLabel>
+    </FormItem>
+  )}
+/>
 <Button type="submit">Submit</Button>
+<div className="mt-4">
+  <p className="text-center">Or continue with</p>
+  <div className="mt-2 flex justify-center space-x-4">
+    <Button variant="outline" onClick={() => authClient.signIn.google()}>
+      <GoogleIcon className="mr-2" /> Google
+    </Button>
+    <Button variant="outline" onClick={() => authClient.signIn.github()}>
+      <GitHubIcon className="mr-2" /> GitHub
+    </Button>
+  </div>
+</div>
apps/api/app/api/[[...route]]/route.ts (1)

Line range hint 8-12: Consider environment-specific CORS configuration.

The allowed origins list includes both development (localhost) and production URLs. Consider moving these to environment variables or configuration files to:

  1. Prevent accidental exposure of development origins in production
  2. Make the configuration more maintainable
  3. Allow for different CORS settings per environment

Example configuration approach:

const allowedOrigins = process.env.NODE_ENV === 'production'
  ? ['https://www.plura.pro', 'http://app.plura.pro']
  : ['http://localhost:3003'];
apps/www/components/custom/signupComponent.tsx (3)

Line range hint 19-23: Enhance form validation rules

The current schema validation could be strengthened:

  • Name field should have minimum/maximum length constraints and character validation
  • Password should enforce stronger requirements (uppercase, lowercase, special characters)
 const formSchema = z.object({
-  name: z.string(),
+  name: z.string().min(2).max(50).regex(/^[a-zA-Z\s]*$/, 'Name can only contain letters and spaces'),
   email: z.string().email(),
-  password: z.string().min(8),
+  password: z
+    .string()
+    .min(8)
+    .regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]+$/, 
+      'Password must contain at least one uppercase letter, one lowercase letter, one number, and one special character'),
 });

Line range hint 32-47: Improve error handling and fix inconsistent naming

Several issues need attention:

  1. Using alert() for error handling provides poor user experience
  2. Variable name SignInData is inconsistent in a signup component
  3. Empty callback handlers could benefit from proper implementation
- const onSubmit = async (SignInData: z.infer<typeof formSchema>) => {
+ const onSubmit = async (signUpData: z.infer<typeof formSchema>) => {
    const { data, error } = await authClient.signUp.email(
      {
-       name: SignInData.name,
-       email: SignInData.email,
-       password: SignInData.password,
+       name: signUpData.name,
+       email: signUpData.email,
+       password: signUpData.password,
      },
      {
-       onRequest: (ctx) => {},
-       onSuccess: (ctx) => {},
+       onRequest: (ctx) => {
+         // Show loading state
+         form.setError("root", { message: "Signing up..." });
+       },
+       onSuccess: (ctx) => {
+         // Handle successful signup
+         router.push("/dashboard");
+       },
        onError: (ctx) => {
-         alert(ctx.error.message);
+         form.setError("root", { message: ctx.error.message });
        },
      },
    );
  };

Line range hint 52-91: Improve form UX and accessibility

The form UI needs several improvements:

  1. Form labels should be properly capitalized
  2. Placeholder text should be descriptive
  3. Add loading state during form submission
 <FormField
   control={form.control}
   name="name"
   render={({ field }) => (
     <FormItem>
-      <FormLabel>name</FormLabel>
+      <FormLabel>Name</FormLabel>
       <FormControl>
-        <Input placeholder="shadcn" {...field} />
+        <Input placeholder="Enter your full name" {...field} />
       </FormControl>
       <FormMessage />
     </FormItem>
   )}
 />

Similar changes should be applied to email and password fields.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 3da4b84 and 09dfa97.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (8)
  • apps/api/app/api/[[...route]]/route.ts (1 hunks)
  • apps/www/app/(auth)/sign-in/page.tsx (1 hunks)
  • apps/www/app/(auth)/sign-up/page.tsx (1 hunks)
  • apps/www/app/sign-in/[[...sign-in]]/layout.tsx (0 hunks)
  • apps/www/app/sign-in/[[...sign-in]]/page.tsx (0 hunks)
  • apps/www/components/custom/signinComponent.tsx (1 hunks)
  • apps/www/components/custom/signupComponent.tsx (1 hunks)
  • apps/www/package.json (0 hunks)
💤 Files with no reviewable changes (3)
  • apps/www/app/sign-in/[[...sign-in]]/layout.tsx
  • apps/www/app/sign-in/[[...sign-in]]/page.tsx
  • apps/www/package.json
✅ Files skipped from review due to trivial changes (2)
  • apps/www/app/(auth)/sign-in/page.tsx
  • apps/www/app/(auth)/sign-up/page.tsx
🔇 Additional comments (4)
apps/api/app/api/[[...route]]/route.ts (2)

101-101: LGTM! Consistent HTTP method handling.

The OPTIONS handler is now defined consistently with other HTTP method handlers, maintaining a clean and symmetric API design.


103-103: Verify the impact of OPTIONS export change.

The consolidated export of HTTP methods is clean and consistent. However, let's verify that no other parts of the codebase were directly importing the OPTIONS handler separately.

✅ Verification successful

OPTIONS export change is safe to proceed

The consolidated export including OPTIONS is safe as there are no direct imports of the OPTIONS handler in the codebase. The only file importing from this route (apps/api/tests/hello.test.ts) only imports GET, POST, PATCH, and DELETE methods, and doesn't use OPTIONS.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any direct imports of OPTIONS from this route file
# This helps ensure the refactor hasn't broken any existing imports

echo "Checking for direct OPTIONS imports..."
rg -l "import.*OPTIONS.*route" --type ts

echo "Checking for destructured OPTIONS imports..."
rg -l "import.*\{.*OPTIONS.*\}.*route" --type ts

Length of output: 279


Script:

#!/bin/bash
# Let's try a broader search to catch any references to OPTIONS from this route file
# First, get the exact path pattern for the route file
fd "route.ts" apps/api

# Then search for any imports or references to OPTIONS in TypeScript files
echo "Checking for any OPTIONS references..."
rg -l "OPTIONS.*route" --type ts

# Also check for any direct usage of the route file
echo "Checking for imports from the route file..."
rg -l "from.*route'" --type ts
rg -l "from.*\[\[\.\.\.route\]\]" --type ts

Length of output: 391


Script:

#!/bin/bash
# Let's check the content of the test file to see how it imports from the route
echo "Checking test file imports..."
cat apps/api/tests/hello.test.ts

# Also let's verify if there are any other files importing from this route using a different pattern
echo "Checking for other import patterns..."
rg "from.*api.*route" --type ts

Length of output: 3152

apps/www/components/custom/signupComponent.tsx (2)

26-26: LGTM: Component naming follows conventions

The rename from SignUp to SignUpComponent aligns with component naming standards.


Line range hint 26-91: Verify security measures implementation

Please ensure the following security measures are in place:

  1. Rate limiting for signup attempts
  2. CSRF protection
  3. Password strength indicators for users

Consider adding a password strength indicator component to help users create strong passwords.

@SkidGod4444 SkidGod4444 merged commit bf8e84c into SkidGod4444:main Nov 10, 2024
4 of 5 checks passed
This was referenced Nov 10, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants