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

Implement user account registration via invitation #846

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

eieimon
Copy link
Contributor

@eieimon eieimon commented Feb 24, 2025

Describe your changes

  • Extract user data in user account page
  • Check expire value for invitation and either show the expired status or allow user to create an account
  • Add password validation just like an admin registration page
  • Display registration error toast for 409 user conflict if user is already registered via the invitation link

Issue number

Mention the issue number(s) this PR addresses (#663).

Please ensure all items are checked off before requesting a review:

  • I deployed the code locally.
  • I have performed a self-review of my code.
  • I have included the issue # in the PR.
  • I have labelled the PR correctly.
  • The issue I am working on is assigned to me.
  • I didn't use any hardcoded values (otherwise it will not scale, and will make it difficult to maintain consistency across the application).
  • I made sure font sizes, color choices etc are all referenced from the theme.
  • My PR is granular and targeted to one specific feature.
  • I took a screenshot or a video and attached to this PR if there is a UI change.
409-user-conflict Screenshot 2025-02-24 at 12 12 15 PM

Summary by CodeRabbit

  • New Features
    • Enhanced the registration process with invitation link validation, automatically pre-populating form fields with user details when a valid invitation is detected.
    • Improved error feedback during registration with alerts and disabled inputs for expired invitations.
    • Expanded user token extraction to support the enhanced onboarding experience.

Copy link
Contributor

coderabbitai bot commented Feb 24, 2025

Walkthrough

This pull request updates the user registration flow across several components. The changes include modifications to the success status handling and error logging in the useRegisterUser hook, an expansion of the token payload extraction in extractToken, and improvements in the RegisterUser page. The registration page now validates invitation links using token data, populates form values when valid, and displays alerts for specific error scenarios during registration.

Changes

File(s) Change Summary
Clients/src/application/hooks/useRegisterUser.tsx Updated the return value of registerUser to output the raw HTTP status code instead of a boolean, and added error logging on exceptions.
Clients/src/application/tools/extractToken.ts Expanded the returned payload fields from { id, email } to include name, role, expire, and iat by returning the complete token payload.
Clients/src/presentation/pages/Authentication/RegisterUser/index.tsx Enhanced the registration flow: added invitation link validation, introduced new state variables (userToken, isInvitationValid, alert), and updated form behavior and error handling based on status.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant P as RegisterUser Page  
    participant T as Token Extractor
    participant H as useRegisterUser Hook
    participant API as API Server

    U->>P: Open registration page with token parameter
    P->>T: Extract user token from URL
    T-->>P: Return token data (id, email, name, role, expire, iat)
    P->>P: Validate invitation via checkValidInvitation
    alt Invitation valid
         P->>P: Populate form fields with token data
    else Invitation invalid
         P->>P: Disable form and display alert
    end
    U->>P: Submit registration form
    P->>H: Invoke registerUser
    H->>API: Send registration data
    API-->>H: Return HTTP status code
    H-->>P: Return raw status code or false on error
Loading

Suggested labels

frontend, enhancement, UI/UX Design

Suggested reviewers

  • MuhammadKhalilzadeh

Poem

I'm a rabbit in the code meadow, hopping with glee,
Changes sprout like carrots, wild and free.
Tokens now burst with info so grand,
And registration flows with a well-planned stand.
I tap my paws with a cheerful beat,
Celebrating code that’s light and neat!
Hoppy code days, oh what a treat! 🐰

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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
Contributor

@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: 1

🧹 Nitpick comments (6)
Clients/src/application/hooks/useRegisterUser.tsx (2)

44-44: Consider renaming or returning a dedicated status field.
Currently, isSuccess is returning the raw numeric status code (response.status) instead of a boolean. This could be misleading to callers expecting a simple boolean. Renaming it to something like statusCode or returning a true/false value can improve clarity.

- return {
-   isSuccess: response.status
- };

+ return {
+   statusCode: response.status
+ };

47-47: Avoid direct console logging in production code.
Using console.log(error) can be useful for debugging, but consider using your existing logEngine for consistent logging and to prevent accidental logs in production.

Clients/src/application/tools/extractToken.ts (1)

3-19: Ensure strong typing and validate the payload structure.
You've expanded the return type to include additional fields (name, role, expire, iat). Consider strictly typing these fields and parsing each with caution—especially expire, which may need integer conversion. Relying on any can lead to runtime errors or security oversights if the token shape changes unexpectedly.

 export const extractUserToken = (
   token: string
 ): { 
-  id: any; 
-  email: any, 
-  name: string, 
-  role: string, 
-  expire: string, 
-  iat: string 
+  id: string;
+  email: string;
+  name: string;
+  role: string;
+  expire: number;
+  iat: number;
 } | null => {
   // ...
 }
Clients/src/presentation/pages/Authentication/RegisterUser/index.tsx (3)

77-77: Clarify variable naming for status checks.
Since isSuccess now holds the numeric status code, consider renaming to something like statusCode for easier reading:

- if (isSuccess === 201) {
+ if (statusCode === 201) {

92-98: Use caution when mixing console logs and alert handling.
Though helpful for debugging, repeated console outputs can clutter production logs. If you prefer detailed logs, rely on the logEngine or wrap the console logs under a development flag.


178-295: Well-structured registration form with invitation checks.
The dynamic disabling of fields based on isInvitationValid provides a clear user experience. Consider extracting common field props (e.g., sx={fieldStyles}) into a shared config or separate component to adhere to DRY principles. Otherwise, the usage here is consistent with the design.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 09f62a8 and 8d7b71d.

📒 Files selected for processing (3)
  • Clients/src/application/hooks/useRegisterUser.tsx (1 hunks)
  • Clients/src/application/tools/extractToken.ts (2 hunks)
  • Clients/src/presentation/pages/Authentication/RegisterUser/index.tsx (7 hunks)
🔇 Additional comments (8)
Clients/src/presentation/pages/Authentication/RegisterUser/index.tsx (8)

1-2: No issues with the new imports.
The additions of Box, useEffect, lazy, and Suspense from these libraries are appropriate for the new functionalities.


13-15: Imports look correct for new token extraction and alert handling.
These imports align well with the functionalities added below.


25-28: Good inclusion of the email property in the initial form state.
Adding email ensures the form can populate and display the user's email.


36-40: State variables appear appropriately initialized.
Using the search param token to manage invitation validity and alert states is clear.


63-63: Form submission state change is fine.
Setting isSubmitting(true) at this stage is consistent with typical async form handling.


85-85: Logging is consistent with the current approach.
Creating a msg from logEngine and using it later is valid. Keep ensuring sensitive data is excluded.


125-142: Validate expire parsing before invocation.
If expire is missing or invalid, checkValidInvitation may incorrectly report the invitation as expired or valid. Consider additional safeguards around userInfo?.expire.


151-163: Lazy loading the alert is a good optimization.
Your fallback ensures the UI remains responsive while loading the alert. This is a solid approach.

Comment on lines +111 to +123
const checkValidInvitation = (expDate: any) => {
let todayDate = new Date();
let currentTime = todayDate.getTime();
console.log(currentTime)

if(currentTime < expDate){
setIsInvitationValid(true);
}else{
console.log("The link has expired already.")
setIsInvitationValid(false);
}
return isInvitationValid;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Compare timestamps accurately and prevent possible string-compare bugs.
expDate is likely a string from the token. Converting it to a number ensures correct comparison with currentTime. Also, returning isInvitationValid immediately may not reflect React's updated state, which is asynchronous.

- const checkValidInvitation = (expDate: any) => {
-   let todayDate = new Date();
-   let currentTime = todayDate.getTime();
-   if(currentTime < expDate){
-     setIsInvitationValid(true);
-   } else {
-     setIsInvitationValid(false);
-   }
-   return isInvitationValid;
- }

+ const checkValidInvitation = (expDate: string | number) => {
+   const expiryTime = typeof expDate === "string"
+     ? parseInt(expDate, 10)
+     : expDate;
+   const currentTime = Date.now();
+   if (!Number.isNaN(expiryTime) && currentTime < expiryTime) {
+     setIsInvitationValid(true);
+   } else {
+     setIsInvitationValid(false);
+   }
+   // Return the comparison result to indicate validity
+   return currentTime < expiryTime;
+ }
📝 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.

Suggested change
const checkValidInvitation = (expDate: any) => {
let todayDate = new Date();
let currentTime = todayDate.getTime();
console.log(currentTime)
if(currentTime < expDate){
setIsInvitationValid(true);
}else{
console.log("The link has expired already.")
setIsInvitationValid(false);
}
return isInvitationValid;
}
const checkValidInvitation = (expDate: string | number) => {
const expiryTime = typeof expDate === "string"
? parseInt(expDate, 10)
: expDate;
const currentTime = Date.now();
if (!Number.isNaN(expiryTime) && currentTime < expiryTime) {
setIsInvitationValid(true);
} else {
setIsInvitationValid(false);
}
// Return the comparison result to indicate validity
return currentTime < expiryTime;
}

@gorkem-bwl
Copy link
Contributor

Thanks @eieimon - looks good to me!

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