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

Password reset feature #2432

Merged
merged 13 commits into from
Feb 7, 2025
Merged

Password reset feature #2432

merged 13 commits into from
Feb 7, 2025

Conversation

Karagwa
Copy link
Contributor

@Karagwa Karagwa commented Jan 30, 2025

Summary of Changes (What does this PR do?)

  • Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change.

Status of maturity (all need to be checked before merging):

  • I've tested this locally
  • I consider this code done
  • This change ready to hit production in its current state
  • The title of the PR states what changed and the related issues number (used for the release note).
  • I've included issue number in the "Closes #ISSUE-NUMBER" part of the "What are the relevant tickets?" section to link the issue.
  • I've updated corresponding documentation for the changes in this PR.
  • I have written unit and/or e2e tests for my change(s).

How should this be manually tested?

  • Please include the steps to be done inorder to setup and test this PR.

What are the relevant tickets?

Screenshots (optional)

Summary by CodeRabbit

  • New Features

    • Added password reset functionality
    • Introduced ability to request password reset via email
    • Added verification code entry for password reset
    • Implemented new password setup after reset
    • Enhanced user interface with a dedicated Forgot Password page
    • Added Reset Link Sent and Reset Success pages for user feedback
  • Bug Fixes

    • Improved theme handling logic for dynamic text colors
  • Documentation

    • Enhanced authentication user interface
  • Chores

    • Added new dependency for pin code fields

Copy link

coderabbitai bot commented Jan 30, 2025

Warning

Rate limit exceeded

@Karagwa has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 24 minutes and 21 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 918e9e7 and aa730e2.

📒 Files selected for processing (1)
  • mobile-v3/lib/src/app/auth/bloc/ForgotPasswordBloc/forgot_password_bloc.dart (1 hunks)
📝 Walkthrough

Walkthrough

This pull request introduces comprehensive password reset functionality to the mobile application. The changes span multiple files, adding new authentication-related components including a PasswordResetBloc, password reset pages, and corresponding event and state management. The implementation includes UI for requesting password resets, entering verification codes, and setting new passwords, integrated with the existing authentication repository.

Changes

File Change Summary
mobile-v3/lib/main.dart Added password reset bloc provider and new imports for ForgotPasswordBloc and ForgotPasswordPage.
mobile-v3/lib/src/app/auth/bloc/ForgotPasswordBloc/* Created new bloc, events, and states for password reset functionality.
mobile-v3/lib/src/app/auth/pages/login_page.dart Added "Forgot password?" navigation link to the login page.
mobile-v3/lib/src/app/auth/pages/password_reset/* Implemented new pages for password reset flow including ForgotPasswordPage, PasswordResetPage, ResetLinkSentPage, and ResetSuccessPage.
mobile-v3/lib/src/app/auth/repository/auth_repository.dart Added methods for password reset and update operations.
mobile-v3/lib/src/meta/utils/colors.dart Updated color definitions and added new static colors.
mobile-v3/pubspec.yaml Added pin_code_fields: ^8.0.1 dependency.

Possibly related PRs

Suggested Labels

ready for review

Suggested Reviewers

  • Mozart299
  • Baalmart

Poem

🔐 Passwords lost, no need to fret,
A reset journey, smoothly met!
Tokens fly, new codes arise,
Authentication's clever guise.
Security dances, user's 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 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 or @coderabbitai title 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: 16

🧹 Nitpick comments (10)
mobile-v3/lib/src/app/auth/pages/welcome_screen.dart (2)

128-130: Clean up extra empty lines.

Multiple consecutive empty lines don't serve any purpose here. Consider keeping just one empty line for readability.

                    ),
                  ),
-

-

-
                ],

126-127: Consider adding a subtle hint about password reset.

Since we're implementing a password reset feature, consider adding a small hint below the login button to improve feature discoverability. This could help users who might be returning to the app but have forgotten their credentials.

                      ),
                    ),
+                  SizedBox(height: 8),
+                  Text(
+                    "Forgot your password?",
+                    style: TextStyle(
+                      fontSize: 12,
+                      color: Colors.grey,
+                    ),
+                  ),
                ],
mobile-v3/lib/src/app/auth/bloc/ForgotPasswordBloc/forgot_password_event.dart (1)

8-15: Consider adding email validation in RequestPasswordReset.

The email parameter should be validated before creating the event to ensure it meets basic email format requirements.

 class RequestPasswordReset extends PasswordResetEvent {
   final String email;
 
-  RequestPasswordReset(this.email);
+  RequestPasswordReset(this.email) {
+    assert(email.contains('@') && email.contains('.'), 'Invalid email format');
+  }
 
   @override
   List<Object?> get props => [email];
 }
mobile-v3/lib/src/app/auth/bloc/ForgotPasswordBloc/forgot_password_state.dart (2)

19-26: Enhance PasswordResetSuccess state with message validation.

The message parameter is required but could be empty. Consider adding validation or making it optional if empty messages are valid.

 class PasswordResetSuccess extends PasswordResetState {
   final String message;
 
-  const PasswordResetSuccess({String? email, required this.message}) : super(email: email);
+  const PasswordResetSuccess({String? email, String? message}) 
+      : this.message = message ?? 'Password reset successful',
+        super(email: email);

28-36: Consider adding error type classification in PasswordResetError.

Adding error types would help in handling different error scenarios more effectively.

 class PasswordResetError extends PasswordResetState {
   final String message;
+  final PasswordResetErrorType errorType;
 
-  const PasswordResetError({String? email, required this.message})
-      : super(email: email);
+  const PasswordResetError({
+    String? email, 
+    required this.message,
+    this.errorType = PasswordResetErrorType.unknown,
+  }) : super(email: email);
 
   @override
-  List<Object?> get props => [email, message];
+  List<Object?> get props => [email, message, errorType];
 }
+
+enum PasswordResetErrorType {
+  invalidEmail,
+  invalidToken,
+  networkError,
+  unknown,
+}
mobile-v3/lib/src/meta/utils/colors.dart (2)

11-11: Remove commented hex color values.

The inline comment with hex values #E2E3E5 #7A7F87 #2E2F33 #1C1D20 should be removed as these values are now properly defined as color constants.


12-21: Consolidate duplicate color definitions.

Several colors are defined both as static constants and within ThemeData. Consider using a single source of truth for color definitions.

-  static Color primaryColor = Color(0xff145FFF);
-  static Color backgroundColor = Color(0xffF9FAFB);
-  static Color highlightColor = Color(0xffF3F6F8);
-  static Color boldHeadlineColor = Color(0xff6F87A1);
-  static Color boldHeadlineColor2 = Color(0xff9EA3AA);
-  static Color boldHeadlineColor3 = Color(0xff7A7F87);
-  static Color boldHeadlineColor4 = Color(0xff2E2F33);
-  static Color highlightColor2= Color(0xffE2E3E5);
-  static Color secondaryHeadlineColor = Color(0xff6F87A1);
-  static Color darkThemeBackground= Color(0xff1C1D20);
+  // Light theme colors
+  static const lightColors = _AppThemeColors(
+    primary: Color(0xff145FFF),
+    background: Color(0xffF9FAFB),
+    highlight: Color(0xffF3F6F8),
+    boldHeadline: Color(0xff6F87A1),
+    // ... other colors
+  );
+
+  // Dark theme colors
+  static const darkColors = _AppThemeColors(
+    primary: Color(0xff145FFF),
+    background: Color(0xff1C1D20),
+    highlight: Color(0xff2E2F33),
+    boldHeadline: Color(0xff9EA3AA),
+    // ... other colors
+  );
mobile-v3/lib/src/app/auth/pages/password_reset/reset_success.dart (2)

17-22: Consider replacing back navigation with direct route to login.

The back button allows users to return to previous steps in the password reset flow, which could be confusing after a successful reset. Consider removing the back button or replacing it with direct navigation to the login page.

-        leading: IconButton(
-          icon: Icon(Icons.arrow_back),
-          onPressed: () {
-            Navigator.of(context).pop();
-          },
-        ),

44-50: Extract text strings for localization.

Consider extracting hardcoded strings to a localization file for better maintainability and future internationalization support.

mobile-v3/lib/src/app/auth/pages/password_reset/forgot_password.dart (1)

162-162: Improve user experience during form submission.

The email field is cleared immediately after submission, before knowing if the request was successful. Consider clearing the field only after receiving a success response.

- emailController.clear();
  passwordResetBloc.add(RequestPasswordReset(
      emailController.text.trim()
  ));
+ if (state is PasswordResetSuccess) {
+   emailController.clear();
+ }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c06dcca and c79031f.

⛔ Files ignored due to path filters (1)
  • mobile-v3/pubspec.lock is excluded by !**/*.lock
📒 Files selected for processing (13)
  • mobile-v3/lib/main.dart (4 hunks)
  • mobile-v3/lib/src/app/auth/bloc/ForgotPasswordBloc/forgot_password_bloc.dart (1 hunks)
  • mobile-v3/lib/src/app/auth/bloc/ForgotPasswordBloc/forgot_password_event.dart (1 hunks)
  • mobile-v3/lib/src/app/auth/bloc/ForgotPasswordBloc/forgot_password_state.dart (1 hunks)
  • mobile-v3/lib/src/app/auth/pages/login_page.dart (3 hunks)
  • mobile-v3/lib/src/app/auth/pages/password_reset/forgot_password.dart (1 hunks)
  • mobile-v3/lib/src/app/auth/pages/password_reset/password_reset.dart (1 hunks)
  • mobile-v3/lib/src/app/auth/pages/password_reset/reset_link_sent.dart (1 hunks)
  • mobile-v3/lib/src/app/auth/pages/password_reset/reset_success.dart (1 hunks)
  • mobile-v3/lib/src/app/auth/pages/welcome_screen.dart (2 hunks)
  • mobile-v3/lib/src/app/auth/repository/auth_repository.dart (2 hunks)
  • mobile-v3/lib/src/meta/utils/colors.dart (1 hunks)
  • mobile-v3/pubspec.yaml (1 hunks)
🔇 Additional comments (4)
mobile-v3/lib/src/app/auth/pages/password_reset/password_reset.dart (1)

16-17: Add token validation.

The token is accepted without validation. Consider validating the token's format and expiration before allowing password reset.

mobile-v3/pubspec.yaml (1)

59-60: Verify the necessity of unused dependencies.

The pin_code_fields package is added but not used in the provided code. If it's planned for future use, consider adding a TODO comment or remove it to keep dependencies minimal.

✅ Verification successful

The pin_code_fields package is actively used in the codebase

The package is properly implemented in mobile-v3/lib/src/app/auth/pages/password_reset/reset_link_sent.dart for handling password reset verification codes.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for usage of pin_code_fields package
rg "pin_code_fields" --type dart

Length of output: 156


Script:

#!/bin/bash
# Check implementation in reset_link_sent.dart
ast-grep --pattern 'PinCodeTextField' && cat mobile-v3/lib/src/app/auth/pages/password_reset/reset_link_sent.dart

Length of output: 6343

mobile-v3/lib/src/app/auth/pages/login_page.dart (2)

71-71: LGTM!

The color change maintains consistency with the application's color scheme.


191-204: LGTM!

The forgot password link implementation follows standard patterns:

  • Clear visibility with primary color
  • Standard placement below the form
  • Straightforward navigation

Copy link
Collaborator

@Baalmart Baalmart left a comment

Choose a reason for hiding this comment

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

Thanks @Karagwa for the great work.

I do notice that you need to resolve some merge conflicts in your PR.

Please act accordingly by merging the most recent staging into your development branch.

Thanks.

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

🧹 Nitpick comments (2)
mobile-v3/lib/main.dart (2)

122-123: Add trailing comma for better git diffs.

While the BlocProvider implementation is correct, adding a trailing comma would improve git diff readability and maintain consistency with other BlocProviders in the list.

-        BlocProvider(create: (context) => PasswordResetBloc(authRepository: authRepository),
-        )
+        BlocProvider(
+          create: (context) => PasswordResetBloc(authRepository: authRepository),
+        ),

122-123: Password reset feature follows clean architecture principles.

The integration of the password reset feature at the root level with proper dependency injection and state management demonstrates good architectural decisions:

  1. Follows the BLoC pattern consistently
  2. Reuses the existing auth repository
  3. Maintains proper separation of concerns
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c79031f and 7e2864c.

📒 Files selected for processing (1)
  • mobile-v3/lib/main.dart (3 hunks)
🔇 Additional comments (2)
mobile-v3/lib/main.dart (2)

3-3: LGTM! Clean import structure.

The import follows the project's feature-based organization pattern, maintaining good separation of concerns.


Line range hint 133-133: Theme logic is now correct.

The theme implementation now correctly maps isLightTheme to the appropriate theme values:

theme: isLightTheme ? AppTheme.lightTheme : AppTheme.darkTheme

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 comments (1)
mobile-v3/lib/src/app/dashboard/widgets/analytics_card.dart (1)

56-57: Add null safety checks for measurement values.

The code accesses measurement.pm25!.value! without proper null checks, which could lead to runtime errors.

Apply this diff to add null safety:

-                            getAirQualityIcon(measurement, measurement.pm25!.value!),
+                            measurement.pm25?.value != null
+                                ? getAirQualityIcon(measurement, measurement.pm25!.value!)
+                                : 'assets/images/shared/default_air_quality.svg',

Also applies to: 80-81

🧹 Nitpick comments (9)
mobile-v3/lib/src/meta/utils/colors.dart (4)

19-19: Fix inconsistent spacing in property declarations.

There's missing spacing after the = operator in some color declarations.

-  static Color highlightColor2= Color(0xffE2E3E5);
+  static Color highlightColor2 = Color(0xffE2E3E5);
-  static Color darkThemeBackground= Color(0xff1C1D20);
+  static Color darkThemeBackground = Color(0xff1C1D20);

Also applies to: 21-21


52-54: Fix inconsistent spacing in TextStyle declaration.

The titleMedium TextStyle declaration has inconsistent spacing.

-      titleMedium:TextStyle(
-          color: const Color(0xff000000)
-      ) ,
+      titleMedium: TextStyle(
+        color: const Color(0xff000000)
+      ),

84-86: Fix inconsistent spacing in dark theme TextStyle declaration.

The titleMedium TextStyle declaration in dark theme has inconsistent spacing.

-      titleMedium:TextStyle(
-        color: const Color(0xffE2E3E5)
-      ) ,
+      titleMedium: TextStyle(
+        color: const Color(0xffE2E3E5)
+      ),

13-14: Consider extracting theme colors to a separate constants file.

The background and highlight colors are defined in both AppColors and theme configurations. Consider extracting these values to a separate constants file to maintain a single source of truth.

Also applies to: 71-72

mobile-v3/lib/src/app/auth/pages/password_reset/forgot_password.dart (2)

27-28: Remove redundant controller initialization.

The TextEditingController is initialized twice - once in the declaration and again in initState. Remove the initialization from the declaration to avoid redundancy.

- late TextEditingController emailController = TextEditingController();
+ late TextEditingController emailController;

37-42: Enhance error handling for BLoC initialization.

While errors are logged, the user isn't notified of initialization failures. Consider showing a user-friendly error message and providing a retry option.

 try {
   passwordResetBloc = context.read<PasswordResetBloc>();
 } catch (e) {
   logError('Failed to initialize PasswordResetBloc: $e');
+  ScaffoldMessenger.of(context).showSnackBar(
+    SnackBar(
+      content: Text('Failed to initialize. Please try again.'),
+      action: SnackBarAction(
+        label: 'Retry',
+        onPressed: () {
+          setState(() {
+            // Retry initialization
+          });
+        },
+      ),
+    ),
+  );
 }
mobile-v3/lib/src/app/auth/pages/password_reset/password_reset.dart (2)

27-30: Clean up controller declarations.

Two issues need to be addressed:

  1. Remove redundant controller initialization
  2. Remove unused resetController
- late TextEditingController passwordConfirmController = TextEditingController();
- late TextEditingController passwordController = TextEditingController();
- late TextEditingController resetController= TextEditingController();
+ late TextEditingController passwordConfirmController;
+ late TextEditingController passwordController;

182-191: Clean up form submission logic.

Remove the unnecessary resetController.clear() call as this controller is unused.

 passwordResetBloc.add(UpdatePassword(
     confirmPassword: passwordConfirmController.text.trim(),
     token: widget.token,
     password:passwordController.text.trim()));
 }
- resetController.clear();
 passwordConfirmController.clear();
 passwordController.clear();
mobile-v3/lib/src/app/dashboard/pages/dashboard_page.dart (1)

322-334: Optimize list filtering performance.

The current implementation rebuilds the entire ListView when filtering measurements. Consider memoizing the filtered results or using a more efficient data structure.

Consider this improvement:

+ // Add this to your state variables
+ late Map<String, List<Measurement>> _filteredMeasurementsCache = {};

  void filterByCountry(String country, List<Measurement> measurements) {
+   if (_filteredMeasurementsCache.containsKey(country)) {
+     setState(() {
+       filteredMeasurements = _filteredMeasurementsCache[country]!;
+       currentFilter = country;
+     });
+     return;
+   }
+
+   final filtered = measurements.where((measurement) {
+     if (measurement.siteDetails != null) {
+       return measurement.siteDetails!.country == country;
+     }
+     return false;
+   }).toList();
+
    setState(() {
-     filteredMeasurements = measurements.where((measurement) {
-       if (measurement.siteDetails != null) {
-         return measurement.siteDetails!.country == country;
-       }
-       return false;
-     }).toList();
+     _filteredMeasurementsCache[country] = filtered;
+     filteredMeasurements = filtered;
      currentFilter = country;
    });
  }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e9cbd2b and 8c52ed7.

⛔ Files ignored due to path filters (1)
  • mobile-v3/pubspec.lock is excluded by !**/*.lock
📒 Files selected for processing (13)
  • mobile-v3/lib/main.dart (3 hunks)
  • mobile-v3/lib/src/app/auth/bloc/ForgotPasswordBloc/forgot_password_bloc.dart (1 hunks)
  • mobile-v3/lib/src/app/auth/pages/login_page.dart (4 hunks)
  • mobile-v3/lib/src/app/auth/pages/password_reset/forgot_password.dart (1 hunks)
  • mobile-v3/lib/src/app/auth/pages/password_reset/password_reset.dart (1 hunks)
  • mobile-v3/lib/src/app/auth/pages/password_reset/reset_link_sent.dart (1 hunks)
  • mobile-v3/lib/src/app/auth/pages/password_reset/reset_success.dart (1 hunks)
  • mobile-v3/lib/src/app/auth/pages/welcome_screen.dart (4 hunks)
  • mobile-v3/lib/src/app/dashboard/pages/dashboard_page.dart (4 hunks)
  • mobile-v3/lib/src/app/dashboard/widgets/analytics_card.dart (3 hunks)
  • mobile-v3/lib/src/app/profile/pages/guest_profile page.dart (2 hunks)
  • mobile-v3/lib/src/app/profile/pages/widgets/settings_tile.dart (2 hunks)
  • mobile-v3/lib/src/meta/utils/colors.dart (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (6)
  • mobile-v3/lib/src/app/auth/pages/password_reset/reset_success.dart
  • mobile-v3/lib/src/app/auth/pages/login_page.dart
  • mobile-v3/lib/src/app/auth/pages/welcome_screen.dart
  • mobile-v3/lib/main.dart
  • mobile-v3/lib/src/app/auth/pages/password_reset/reset_link_sent.dart
  • mobile-v3/lib/src/app/auth/bloc/ForgotPasswordBloc/forgot_password_bloc.dart
🔇 Additional comments (5)
mobile-v3/lib/src/meta/utils/colors.dart (1)

6-10: Good cleanup of commented code!

Removing the commented-out color definitions improves code readability.

mobile-v3/lib/src/app/auth/pages/password_reset/forgot_password.dart (2)

123-128: Add proper email format validation.

The current validation only checks if the field is empty. Add email format validation to prevent invalid email submissions.


61-63: Implement user-friendly error messages.

Displaying raw error messages could expose sensitive information. Consider mapping error messages to user-friendly versions.

mobile-v3/lib/src/app/auth/pages/password_reset/password_reset.dart (1)

120-149: Implement password strength requirements.

The current implementation lacks password strength validation. Also, the password confirmation check should be after the empty check.

mobile-v3/lib/src/app/profile/pages/guest_profile page.dart (1)

1-155: Verify the loading state handling.

The loading state is set but never used in the UI for the "Create Account" button. The button shows a spinner only when isLoading is true, but the navigation happens immediately after setting isLoading to false, making the loading state ineffective.

Consider this improvement:

  void handleCreateAccount() async {
    setState(() {
      isLoading = true;
    });

-   // Simulate a delay for account creation or call an API here
-   await Future.delayed(Duration(seconds: 2));
-
-   setState(() {
-     isLoading = false;
-   });
-
-   // Navigate to CreateAccountScreen or handle success
-   Navigator.of(context).push(MaterialPageRoute(builder: (context) => CreateAccountScreen()));
+   try {
+     // Call your API here
+     await Future.delayed(Duration(seconds: 2)); // Replace with actual API call
+     Navigator.of(context).push(MaterialPageRoute(builder: (context) => CreateAccountScreen()));
+   } finally {
+     setState(() {
+       isLoading = false;
+     });
+   }
  }

@Karagwa Karagwa requested a review from Baalmart February 2, 2025 16:13
Copy link
Collaborator

@Baalmart Baalmart left a comment

Choose a reason for hiding this comment

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

Thanks @Karagwa , this is wonderful progress. Keep it up!

I have just reviewed and left some comments for your consideration.

Thank you!

Comment on lines 117 to 146
validator: (value) {

if (value == null || value.isEmpty) {
return "This field cannot be blank.";
}
return null;
},
hintText: "Enter your password",
label: "Password",
isPassword: true,
controller: passwordController),
SizedBox(height: 16),
FormFieldWidget(
prefixIcon: Container(
padding: const EdgeInsets.all(13.5),
child: SvgPicture.asset(
"assets/icons/password.svg",
height: 10,
),
),
validator: (value) {
if(value != passwordController.text){
return "Passwords do not match";
}

if (value == null || value.isEmpty) {
return "This field cannot be blank.";
}
return null;
},
Copy link
Collaborator

Choose a reason for hiding this comment

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

Thanks @Karagwa

Just in case we wish to do password validation in the frontend, please check out the regex we are using in the backend, it is shared below:

const passwordReg = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@#?!$%^&*,.]{6,}$/;

@Karagwa Karagwa requested a review from Baalmart February 5, 2025 13:17
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: 1

🧹 Nitpick comments (4)
mobile-v3/lib/src/app/auth/bloc/ForgotPasswordBloc/forgot_password_bloc.dart (2)

11-19: Don't expose the raw error details to users.
While emit(PasswordResetError(message: e.toString())); surfaces valuable debugging information, it can display internal or sensitive details. Consider substituting with a user-friendly message.


40-48: Improve PIN verification logic.
Relying on a simple 5-digit regex may be limiting if you anticipate more complex codes or other data formats. Enhance this logic to handle additional edge cases, such as alphanumeric tokens or variable lengths.

mobile-v3/lib/src/app/auth/bloc/ForgotPasswordBloc/forgot_password_state.dart (1)

3-9: Assess the need to store email in all states.
Carrying the email property across states is convenient, but it can be redundant or pose a minor risk of data leakage. Verify if every state truly requires it.

mobile-v3/lib/main.dart (1)

122-123: Add trailing comma for consistent formatting.

Add a trailing comma after the BlocProvider to maintain consistent formatting with other providers.

-        BlocProvider(create: (context) => PasswordResetBloc(authRepository: authRepository),
-        )
+        BlocProvider(
+          create: (context) => PasswordResetBloc(authRepository: authRepository),
+        ),
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 31d74a4 and 4920e34.

📒 Files selected for processing (6)
  • mobile-v3/lib/main.dart (4 hunks)
  • mobile-v3/lib/src/app/auth/bloc/ForgotPasswordBloc/forgot_password_bloc.dart (1 hunks)
  • mobile-v3/lib/src/app/auth/bloc/ForgotPasswordBloc/forgot_password_event.dart (1 hunks)
  • mobile-v3/lib/src/app/auth/bloc/ForgotPasswordBloc/forgot_password_state.dart (1 hunks)
  • mobile-v3/lib/src/app/auth/pages/password_reset/password_reset.dart (1 hunks)
  • mobile-v3/lib/src/app/auth/pages/password_reset/reset_link_sent.dart (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • mobile-v3/lib/src/app/auth/pages/password_reset/reset_link_sent.dart
  • mobile-v3/lib/src/app/auth/pages/password_reset/password_reset.dart
🔇 Additional comments (3)
mobile-v3/lib/src/app/auth/bloc/ForgotPasswordBloc/forgot_password_bloc.dart (1)

21-33: 🛠️ Refactor suggestion

⚠️ Potential issue

Standardize how email and token errors are handled.
Right now, PasswordResetLoading(email: event.email) is used in RequestPasswordReset but omitted in UpdatePassword. Also, line 31 may accidentally reveal the reset token in the user-facing error message.

Below is a recommended fix snippet removing the token from the error message while preserving consistent handling of email data:

- emit(PasswordResetError(message: 'Failed to update password. \nPlease re-check the code you entered '+event.token));
+ emit(PasswordResetError(message: 'Failed to update password. Please ensure the code is correct.'));

Likely invalid or redundant comment.

mobile-v3/lib/src/app/auth/bloc/ForgotPasswordBloc/forgot_password_event.dart (1)

17-30: Duplicate suggestion: add password validation logic.
Consider ensuring that password matches confirmPassword and meets minimum security requirements. This helps avoid unexpected runtime errors.

mobile-v3/lib/main.dart (1)

3-3: LGTM! Clean import organization.

The new imports for password reset functionality are well-organized and follow the project's feature-based structure.

Also applies to: 5-5

mobile-v3/lib/main.dart Outdated Show resolved Hide resolved
@Baalmart Baalmart merged commit a2316d2 into staging Feb 7, 2025
31 checks passed
@Baalmart Baalmart deleted the passwordResetFeature branch February 7, 2025 10:24
@Baalmart Baalmart mentioned this pull request Feb 7, 2025
1 task
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.

3 participants