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

Add account password change feature #172

Merged
merged 4 commits into from
Oct 2, 2024
Merged

Add account password change feature #172

merged 4 commits into from
Oct 2, 2024

Conversation

chacha912
Copy link
Contributor

@chacha912 chacha912 commented Oct 1, 2024

What this PR does / why we need it?

This feature allows users to update their account passwords. It includes necessary validations to ensure password security and correctness.

change-password.mov

Any background context you want to provide?

What are the relevant tickets?

Fixes #160

Checklist

  • Added relevant tests or not required
  • Didn't break anything

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a password change functionality for users, accessible through the new Account settings.
    • Added a new SVG icon for enhanced visual options.
    • Expanded button color options to include a new 'info' style.
    • Enhanced navigation in the Settings page to include account management.
  • Bug Fixes

    • Improved error handling during password change operations.
  • Documentation

    • Updated UI components and styles for the password change form.
  • Chores

    • Enhanced state management for user account settings.

Copy link

coderabbitai bot commented Oct 1, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The pull request introduces several changes aimed at enhancing user account management functionalities. A new asynchronous function, changePassword, is added to facilitate password changes. Additionally, a new React component, Account, is created for managing user account settings, which integrates with Redux for state management. Styling updates are made to support the password change form, and modifications are made to the button component to include a new color option. Finally, the SettingsPage is updated to incorporate the new Account component.

Changes

File Change Summary
src/api/index.ts Added async function changePassword(username, password, newPassword) for password change functionality.
src/assets/styles/pages/admin_setting_account.scss Introduced .change_password_form, .modal_desc, and .input_box classes for styling the password change form.
src/components/Button/Button.tsx Updated ButtonProps to include new color option info and added info: 'blue_0' to ButtonStyle.
src/components/Icons/Icon.tsx Added new SVG icon RepeatSVG and updated svgMap to include repeat key.
src/features/users/Account.tsx Created Account component for managing user account settings and password changes.
src/features/users/usersSlice.ts Added changePassword state, ChangePasswordFields type, and changePassword thunk for password management.
src/pages/SettingsPage.tsx Imported Account component and added it to the Navigator and layout of the settings page.

Assessment against linked issues

Objective Addressed Explanation
Change Password

🐰 In the land of code where changes bloom,
A password change form dispels the gloom.
With styles and buttons, all dressed in blue,
Admins can manage, and users can too!
Hopping along, we celebrate this feat,
For account actions now feel complete! 🎉


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

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

🧹 Outside diff range and nitpick comments (5)
src/pages/SettingsPage.tsx (1)

39-39: LGTM: Addition of 'Account' to navigation list.

The 'Account' entry is correctly added to the navList prop, enabling navigation to the new account settings section. This change aligns with the PR objective.

Consider if the placement of 'Account' at the beginning of the list is intentional. If not, you might want to adjust the order to maintain consistency with the rendered components or any existing navigation hierarchy.

src/components/Button/Button.tsx (1)

46-46: LGTM: ButtonProps type updated correctly

The 'color' property in ButtonProps has been correctly updated to include the new 'info' option, maintaining type safety and consistency with the ButtonStyle object.

Consider extracting the color options into a separate type or constant to improve maintainability. This would make it easier to add or modify color options in the future. For example:

type ButtonColor = 'primary' | 'success' | 'danger' | 'info' | 'toggle' | 'default';

// Then in ButtonProps:
color?: ButtonColor;

This approach would centralize the color options and make it easier to keep ButtonStyle and ButtonProps in sync.

src/assets/styles/pages/admin_setting_account.scss (1)

285-293: LGTM with minor formatting suggestion.

The new styles for .change_password_form are well-structured and align with the PR objective of adding a password change feature. The margins added to .modal_desc and .input_box provide appropriate spacing between elements in the form.

Consider adjusting the indentation of the new styles to match the rest of the file for consistency. Here's the suggested change:

-  .change_password_form {
-    .modal_desc {
-      margin-bottom: 8px;
-    }
-
-    .input_box {
-      margin-top: 8px;
-    }
-  }
+.change_password_form {
+  .modal_desc {
+    margin-bottom: 8px;
+  }
+
+  .input_box {
+    margin-top: 8px;
+  }
+}
src/api/index.ts (1)

Line range hint 1-63: Enhance type safety with consistent return type annotations

To improve code readability and type safety, consider adding explicit return type annotations to all exported functions. Some functions already have return types specified, while others don't. Consistency in this area will make the code more maintainable and self-documenting.

Here are a few examples of functions that could benefit from explicit return type annotations:

export async function deleteAccount(username: string, password: string): Promise<void> {
  // ... existing implementation ...
}

export async function changePassword(username: string, password: string, newPassword: string): Promise<void> {
  // ... implementation ...
}

// Update other functions similarly

This change will make the expected return types clear for all functions and help catch potential type-related issues earlier in the development process.

src/features/users/Account.tsx (1)

48-51: Remove unnecessary dependency from onClose callback

The setIsModalOpen setter function is stable and does not need to be included in the dependency array of onClose.

Apply this diff to update the dependency array:

const onClose = useCallback(() => {
  reset();
  setIsModalOpen(false);
- }, [reset, setIsModalOpen]);
+ }, [reset]);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 4fb5588 and 80cfea3.

📒 Files selected for processing (7)
  • src/api/index.ts (1 hunks)
  • src/assets/styles/pages/admin_setting_account.scss (1 hunks)
  • src/components/Button/Button.tsx (2 hunks)
  • src/components/Icons/Icon.tsx (2 hunks)
  • src/features/users/Account.tsx (1 hunks)
  • src/features/users/usersSlice.ts (5 hunks)
  • src/pages/SettingsPage.tsx (2 hunks)
🧰 Additional context used
🪛 Biome
src/features/users/Account.tsx

[error] 111-111: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 137-137: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 155-155: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (17)
src/pages/SettingsPage.tsx (3)

23-23: LGTM: Import statement for Account component.

The import statement for the Account component is correctly placed and follows the existing import structure. This addition aligns with the PR objective of implementing the account password change feature.


Line range hint 23-45: Summary: Changes align well with PR objectives.

The modifications to SettingsPage.tsx consistently implement the addition of the Account feature, including:

  1. Importing the Account component
  2. Adding Account to the navigation list
  3. Rendering the Account component

These changes directly address the PR objective of adding an account password change feature and enhancing account management functionalities. The implementation appears to be minimal and focused, without disrupting existing features.

To ensure full alignment with the PR objectives, please confirm:

  1. The Account component includes password change functionality.
  2. Appropriate validations are in place for password changes.
  3. The feature is accessible to administrators as mentioned in the linked issue Add basic account action feature #160.

You may want to review the implementation of the Account component itself to verify these points.


45-45: LGTM: Rendering of Account component.

The Account component is correctly added to the render tree, positioned consistently with the navigation order. This addition directly implements the account management feature described in the PR objectives.

To ensure the Account component is fully implemented, please run the following script:

This script will help verify:

  1. The existence of the Account component file.
  2. The basic structure of the Account component.
  3. The presence of password change functionality within the component.

Please review the results to ensure the component is fully implemented as per the PR objectives.

✅ Verification successful

Verified: Account component implementation confirmed.

All verification tests have passed:

  • The Account.tsx file exists in src/features/users/.
  • The Account component is correctly structured.
  • Password change functionality is implemented within the component.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of the Account component

# Test 1: Check if the Account component file exists
fd -t f "Account.(tsx|js|jsx)" src/features/users

# Test 2: Inspect the Account component implementation
ast-grep --lang typescript --pattern $'export function Account() {
  $$$
}'

# Test 3: Check for password change functionality within the Account component
rg -i "password.*change|change.*password" src/features/users/Account.tsx

Length of output: 910

src/components/Button/Button.tsx (2)

29-29: LGTM: New color option added successfully

The addition of the 'info' color option with the class name 'blue_0' is consistent with the existing structure and naming convention. This enhancement provides more flexibility in UI design without breaking existing functionality.


Line range hint 1-101: Overall assessment: Changes successfully implement new color option

The modifications to add the 'info' color option have been implemented correctly and consistently throughout the file. These changes align with the PR objectives to enhance the Button component's flexibility. The implementation maintains type safety and doesn't introduce any breaking changes.

To further improve the code:

  1. Consider the suggestion to extract color options into a separate type or constant for better maintainability.
  2. Ensure that the new 'info' color option is properly styled in the corresponding CSS file (not shown in this review).
  3. Update any relevant documentation or storybook examples to showcase the new color option.

To ensure the changes are reflected in the styling, please run the following command:

This will help verify that the new 'info' color option has corresponding styles defined.

src/components/Icons/Icon.tsx (3)

62-62: LGTM: Import statement for RepeatSVG is correct and consistent.

The import statement for RepeatSVG is properly formatted and follows the established pattern for icon imports in this file. It maintains consistency with other icon imports and adheres to React component naming conventions.


108-108: LGTM: Addition of RepeatSVG to svgMap is correct and consistent.

The new entry for the RepeatSVG icon in the svgMap object is properly formatted and consistent with other entries. The key name 'repeat' is descriptive and follows the established naming convention.


Line range hint 62-108: Verify the purpose of the new RepeatSVG icon.

The addition of the RepeatSVG icon is implemented correctly and doesn't introduce any breaking changes to the existing Icon component. The component will now support the 'repeat' icon type seamlessly.

However, could you please clarify how this new icon relates to the account password change feature mentioned in the PR objectives? It would be helpful to understand its intended use in the context of this feature.

src/assets/styles/pages/admin_setting_account.scss (1)

285-293: Changes align well with PR objectives.

The addition of the .change_password_form styles is focused and minimal, addressing only the new password change feature. These changes align well with the PR objectives of enabling users to update their account passwords. The new styles are properly scoped within the existing .setting_account_page class, ensuring they don't interfere with other styles.

To ensure no unintended style conflicts, run the following command to check for any other occurrences of .change_password_form in the codebase:

✅ Verification successful

Verification successful, no additional occurrences of .change_password_form found.

The search confirmed that .change_password_form exists only in src/assets/styles/pages/admin_setting_account.scss, ensuring no unintended style conflicts elsewhere.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other occurrences of .change_password_form
rg --type scss ".change_password_form"

Length of output: 67


Script:

#!/bin/bash
# Search for other occurrences of .change_password_form in .scss files
rg ".change_password_form" --glob "*.scss"

Length of output: 119

src/api/index.ts (1)

Line range hint 1-63: Summary: Password change feature implemented with room for enhancements

The implementation of the ChangePassword function successfully addresses the main objective of the PR, which is to enable users to update their account passwords. This aligns with the requirements outlined in the linked issue #160 for enhancing account management functionalities.

Key points:

  1. The core functionality for changing passwords is in place.
  2. The implementation follows the existing pattern of using gRPC for server communication.
  3. The function is exported, making it available for use in other modules as required.

Suggested improvements:

  1. Add password validation to ensure security requirements are met.
  2. Implement error handling for better user experience and easier debugging.
  3. Rename the function to changePassword for consistency with existing naming conventions.
  4. Consider grouping authentication-related functions for better code organization.
  5. Add consistent return type annotations across all exported functions.

These enhancements will improve the overall quality, security, and maintainability of the code while fully meeting the PR objectives and addressing the requirements from the linked issue.

src/features/users/usersSlice.ts (5)

49-56: Definition of changePassword state is appropriate

The changePassword state is correctly added to the UsersState interface with the necessary properties for status management and error handling.


86-92: ChangePasswordFields type is well-defined

The ChangePasswordFields type includes all required fields for the password change functionality, ensuring that necessary data is captured.


114-118: Initialization of changePassword state is correct

The initial state for changePassword is properly set up in initialState, which will help in managing the state transitions effectively.


296-324: Error handling in changePassword.rejected action is appropriate

The error handling logic for the changePassword.rejected action correctly updates the state based on different RPCStatusCode values and provides meaningful error messages to the user.


325-334: Verify the necessity of logging out the user after a successful password change

In the changePassword.fulfilled case, the user is logged out upon a successful password change by clearing the token and resetting the user state.

Please verify if this behavior is intentional and aligns with the desired user experience. Logging out the user after a password change may be a security measure, but it could also disrupt the user workflow if not expected.

src/features/users/Account.tsx (2)

94-94: Verify the necessity of the hidden username input field

The hidden input field for username may not be necessary since username is already available in the component scope.

Check if the hidden input field is required for form submission or autofill purposes. If not, consider removing it to simplify the form.

Would you like assistance in refactoring this part of the code?


125-128: Ensure the password validation regex meets security requirements

The regex pattern used for password validation should be thoroughly tested to ensure it correctly enforces the intended password policy.

Run the following script to test the regex against various password inputs:

This script will help verify that the regex pattern accepts valid passwords and rejects those that don't meet the criteria.

✅ Verification successful

Password validation regex correctly enforces security requirements.

  • The regex accurately accepts passwords with 8-30 characters, including at least one letter, one number, and one special character.
  • Invalid cases correctly reject passwords that do not meet one or more of these criteria.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Test the password regex pattern with different inputs.

# The regex pattern from the code
regex='^(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[~`!?@#$%^&*()\-_+={}[\]|\\;\:'\"<>,./])(?:[a-zA-Z0-9~`!?@#$%^&*()\-_+={}[\]|\\;\:'\"<>,./]{8,30})$'

# Test cases
passwords=(
  'Password123!'      # Valid
  'password'          # Invalid: no numbers or special characters
  '12345678'          # Invalid: no letters or special characters
  'Pass1234'          # Invalid: no special characters
  'Pass!@#'           # Invalid: no numbers
  'P@ssw0rd'          # Valid
)

# Test the passwords
for pwd in "${passwords[@]}"; do
  if [[ $pwd =~ $regex ]]; then
    echo "Valid: $pwd"
  else
    echo "Invalid: $pwd"
  fi
done

Length of output: 275


Script:

#!/bin/bash
# Description: Test the password regex pattern with different inputs.

# The regex pattern from the code, using double quotes and escaping where necessary
regex="^(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[~\`!?@#\$%^&*()\-_+={}[\]|\\;:'\"<>,./])(?:[a-zA-Z0-9~\`!?@#\$%^&*()\-_+={}[\]|\\;:'\"<>,./]{8,30})$"

# Test cases
passwords=(
  "Password123!"      # Valid
  "password"          # Invalid: no numbers or special characters
  "12345678"          # Invalid: no letters or special characters
  "Pass1234"          # Invalid: no special characters
  "Pass!@#"           # Invalid: no numbers
  "P@ssw0rd"          # Valid
)

# Test the passwords
for pwd in "${passwords[@]}"; do
  if [[ $pwd =~ $regex ]]; then
    echo "Valid: $pwd"
  else
    echo "Invalid: $pwd"
  fi
done

Length of output: 1558


Script:

#!/bin/bash
# Description: Test the password regex pattern with different inputs using grep for better regex support.

# The regex pattern from the code, using double quotes and escaping where necessary
regex="^(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[~\`!?@#\$%^&*()\-_+={}[\]|\\;:'\"<>,./]).{8,30}$"

# Test cases
passwords=(
  "Password123!"      # Valid
  "password"          # Invalid: no numbers or special characters
  "12345678"          # Invalid: no letters or special characters
  "Pass1234"          # Invalid: no special characters
  "Pass!@#"           # Invalid: no numbers
  "P@ssw0rd"          # Valid
)

echo "Using regex: $regex"

# Test the passwords using grep -P for Perl-compatible regex
for pwd in "${passwords[@]}"; do
  echo -n "Testing '$pwd': "
  if echo "$pwd" | grep -Pq "$regex"; then
    echo "Valid"
  else
    echo "Invalid"
  fi
done

Length of output: 1701

src/api/index.ts Outdated Show resolved Hide resolved
src/features/users/usersSlice.ts Outdated Show resolved Hide resolved
src/features/users/Account.tsx Outdated Show resolved Hide resolved
src/features/users/Account.tsx Show resolved Hide resolved
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 (3)
src/features/users/usersSlice.ts (3)

86-91: LGTM: ChangePasswordFields type added

The new ChangePasswordFields type correctly defines the necessary fields for a password change operation. Including confirmPassword is a good practice for ensuring user intent.

Consider adding JSDoc comments to describe the purpose of this type and its fields for better code documentation.


160-165: LGTM: changePassword thunk action creator added

The changePassword thunk action creator is correctly implemented using createAppThunk. It properly calls the api.changePassword function with the necessary parameters.

Consider adding a comment explaining why confirmPassword is not passed to the API call, to clarify that it's intentionally omitted and used only for client-side validation.


296-334: LGTM: Comprehensive state handling for changePassword thunk

The extraReducers for the changePassword thunk are well-implemented, covering pending, rejected, and fulfilled states. The error handling is thorough, addressing UNAUTHENTICATED and INVALID_ARGUMENT status codes appropriately.

Consider adding a comment explaining why the user is logged out upon successful password change (lines 328-333). This behavior might not be immediately obvious to other developers.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 80cfea3 and 72c9933.

📒 Files selected for processing (3)
  • src/api/index.ts (1 hunks)
  • src/features/users/Account.tsx (1 hunks)
  • src/features/users/usersSlice.ts (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/api/index.ts
  • src/features/users/Account.tsx
🔇 Additional comments (3)
src/features/users/usersSlice.ts (3)

49-56: LGTM: New changePassword property added to UsersState

The new changePassword property in the UsersState interface is well-structured and consistent with other similar properties. It correctly includes fields for status tracking, success indication, and error handling specific to password changes.


114-118: LGTM: Initial state for changePassword added

The initial state for the changePassword property is correctly defined and consistent with other similar properties in the state. It properly initializes the isSuccess, status, and error fields.


Line range hint 1-365: Summary: Password change feature successfully implemented

The changes in this file successfully implement the password change feature as outlined in the PR objectives and linked issue #160. The implementation:

  1. Adds necessary state management for password changes
  2. Implements a thunk action creator for the password change operation
  3. Handles various states and error scenarios comprehensively
  4. Maintains consistency with existing code patterns and Redux best practices

These changes enhance the account management capabilities as requested, allowing users to update their passwords securely. The implementation aligns well with the broader context of improving account management features in the dashboard.

src/api/index.ts Outdated Show resolved Hide resolved
Copy link
Member

@hackerwins hackerwins left a comment

Choose a reason for hiding this comment

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

Thanks for your contribution.

@hackerwins hackerwins merged commit ff72277 into main Oct 2, 2024
2 checks passed
@hackerwins hackerwins deleted the change-password branch October 2, 2024 05:48
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.

Add basic account action feature
2 participants