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

Open
wants to merge 8 commits into
base: staging
Choose a base branch
from
Open

Password reset feature #2432

wants to merge 8 commits into from

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

📝 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 reset, 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 import for ForgotPasswordBloc.
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, and ResetLinkSentPage.
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.

Suggested Labels

ready for review

Suggested Reviewers

  • Baalmart
  • Mozart299
  • jordanopos

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

@@ -1,4 +1,5 @@
import 'package:airqo/src/app/auth/pages/login_page.dart';
import 'package:airqo/src/app/auth/pages/password_reset/forgot_password.dart';
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Remove unused import of forgot_password.dart

The import of forgot_password.dart is not used anywhere in the welcome screen implementation. The screen only provides navigation to login and account creation.

🔗 Analysis chain

Remove unused import.

The forgot_password.dart import appears to be unused in this file. The password reset functionality would typically be accessed from the login screen rather than the welcome screen.

Let's confirm if this import is used anywhere in the file:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any usage of ForgotPassword or related classes/functions
rg -l "ForgotPassword" "mobile-v3/lib/src/app/auth/pages/welcome_screen.dart"

Length of output: 75


Script:

#!/bin/bash
# Get the full content of the welcome screen file
cat "mobile-v3/lib/src/app/auth/pages/welcome_screen.dart"

# Case-insensitive search for forgot/password related terms
rg -i "forgot|password" "mobile-v3/lib/src/app/auth/pages/welcome_screen.dart"

Length of output: 4791

Comment on lines +17 to +30
class UpdatePassword extends PasswordResetEvent {
final String confirmPassword;
final String password;
final String token;

UpdatePassword({
required this.confirmPassword,
required this.password,
required this.token,
});

@override
List<Object?> get props => [confirmPassword, password, token];
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add password validation in UpdatePassword event.

The password and confirmPassword fields should be validated for matching values and minimum security requirements.

 class UpdatePassword extends PasswordResetEvent {
   final String confirmPassword;
   final String password;
   final String token;
 
   UpdatePassword({
     required this.confirmPassword,
     required this.password,
     required this.token,
-  });
+  }) {
+    assert(password == confirmPassword, 'Passwords do not match');
+    assert(password.length >= 8, 'Password must be at least 8 characters');
+    assert(token.isNotEmpty, 'Token cannot be empty');
+  }
📝 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
class UpdatePassword extends PasswordResetEvent {
final String confirmPassword;
final String password;
final String token;
UpdatePassword({
required this.confirmPassword,
required this.password,
required this.token,
});
@override
List<Object?> get props => [confirmPassword, password, token];
}
class UpdatePassword extends PasswordResetEvent {
final String confirmPassword;
final String password;
final String token;
UpdatePassword({
required this.confirmPassword,
required this.password,
required this.token,
}) {
assert(password == confirmPassword, 'Passwords do not match');
assert(password.length >= 8, 'Password must be at least 8 characters');
assert(token.isNotEmpty, 'Token cannot be empty');
}
@override
List<Object?> get props => [confirmPassword, password, token];
}

Comment on lines 21 to 33
on<UpdatePassword>((event, emit) async {
emit(PasswordResetLoading());
try {
final message = await authRepository.updatePassword(
confirmPassword: event.confirmPassword,
password: event.password,
token: event.token,
);
emit(PasswordResetSuccess(message: message));
} catch (error) {
emit(PasswordResetError(message: 'Failed to update password. \nPlease enter the correct code'));
}
});
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve error handling and messaging in UpdatePassword event handler.

The error message is hardcoded and the loading state doesn't preserve the context.

     on<UpdatePassword>((event, emit) async {
-      emit(PasswordResetLoading());
+      emit(PasswordResetLoading(email: state.email));
       try {
         final message = await authRepository.updatePassword(
           confirmPassword: event.confirmPassword,
           password: event.password,
           token: event.token,
         );
-        emit(PasswordResetSuccess(message: message));
+        emit(PasswordResetSuccess(email: state.email, message: message));
       } catch (error) {
-        emit(PasswordResetError(message: 'Failed to update password. \nPlease enter the correct code'));
+        final errorMessage = error is InvalidTokenException
+          ? 'Invalid or expired reset code. Please request a new one.'
+          : 'Failed to update password. Please try again.';
+        emit(PasswordResetError(
+          email: state.email,
+          message: errorMessage,
+          errorType: error is InvalidTokenException
+            ? PasswordResetErrorType.invalidToken
+            : PasswordResetErrorType.unknown,
+        ));
       }
     });

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +11 to +19
on<RequestPasswordReset>((event, emit) async {
try {
emit(PasswordResetLoading(email: event.email));
await authRepository.requestPasswordReset(event.email);
emit(PasswordResetSuccess(message: ''));
} catch (e) {
emit(PasswordResetError(message: e.toString()));
}
});
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance error handling in RequestPasswordReset event handler.

The current implementation catches all errors generically. Consider handling specific error types and preserving the email in error state.

     on<RequestPasswordReset>((event, emit) async {
       try {
         emit(PasswordResetLoading(email: event.email));
         await authRepository.requestPasswordReset(event.email);
-        emit(PasswordResetSuccess(message: ''));
+        emit(PasswordResetSuccess(
+          email: event.email,
+          message: 'Reset instructions sent to ${event.email}',
+        ));
       } catch (e) {
-        emit(PasswordResetError(message: e.toString()));
+        emit(PasswordResetError(
+          email: event.email,
+          message: e.toString(),
+          errorType: e is NetworkException 
+            ? PasswordResetErrorType.networkError 
+            : PasswordResetErrorType.unknown,
+        ));
       }
     });

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +66 to +69
InkWell(
onTap: () => Navigator.of(context).push(MaterialPageRoute(
builder: (context) => LoginPage())),
child: Container(
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use pushAndRemoveUntil for login navigation.

After a successful password reset, replace the entire navigation stack to prevent users from going back to previous screens.

-  onTap: () => Navigator.of(context).push(MaterialPageRoute(
-      builder: (context) => LoginPage())),
+  onTap: () => Navigator.of(context).pushAndRemoveUntil(
+    MaterialPageRoute(builder: (context) => LoginPage()),
+    (route) => false,
+  ),
📝 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
InkWell(
onTap: () => Navigator.of(context).push(MaterialPageRoute(
builder: (context) => LoginPage())),
child: Container(
InkWell(
onTap: () => Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(builder: (context) => LoginPage()),
(route) => false,
),
child: Container(

Comment on lines +142 to +153
InkWell(
onTap: () {
final email = context.read<PasswordResetBloc>().state.email;
if (email != null && email.isNotEmpty) {
context.read<PasswordResetBloc>().add(
RequestPasswordReset(email),
);
print("Resend requested for email: $email");
} else {
print("Email is null or empty. Cannot resend.");
}
},
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Improve resend functionality with rate limiting and proper feedback

The resend implementation needs enhancement:

  1. Remove debug print statements
  2. Add rate limiting to prevent abuse
  3. Provide visual feedback for resend action
+ DateTime? _lastResendTime;
+ final _resendCooldown = const Duration(minutes: 1);

 InkWell(
   onTap: () {
     final email = context.read<PasswordResetBloc>().state.email;
     if (email != null && email.isNotEmpty) {
+      final now = DateTime.now();
+      if (_lastResendTime != null && 
+          now.difference(_lastResendTime!) < _resendCooldown) {
+        ScaffoldMessenger.of(context).showSnackBar(SnackBar(
+          content: Text('Please wait before requesting another code'),
+        ));
+        return;
+      }
+      setState(() => _lastResendTime = now);
       context.read<PasswordResetBloc>().add(
         RequestPasswordReset(email),
       );
-      print("Resend requested for email: $email");
+      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
+        content: Text('Verification code resent'),
+      ));
     } else {
-      print("Email is null or empty. Cannot resend.");
+      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
+        content: Text('Unable to resend verification code'),
+      ));
     }
   },

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +106 to +129
InkWell(
onTap: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => PasswordResetPage(token: _pinController.text.trim()),
),
);
},
child: Container(
height: 56,
decoration: BoxDecoration(
color: AppColors.primaryColor,
borderRadius: BorderRadius.circular(4)),
child: Center(
child: Text(
"Continue",
style: TextStyle(
fontWeight: FontWeight.w500,
color: Colors.white,
),
),
),
),
),
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add token verification before navigation

The current implementation directly navigates to the password reset page without verifying the token's validity. This could lead to unnecessary server requests with invalid tokens.

 InkWell(
   onTap: () {
+    if (_pinController.text.trim().isEmpty) {
+      ScaffoldMessenger.of(context).showSnackBar(
+        SnackBar(content: Text('Please enter the verification code')),
+      );
+      return;
+    }
+    
+    // Show loading indicator
+    setState(() => _isLoading = true);
+    
+    // Verify token before navigation
+    context.read<PasswordResetBloc>().add(
+      VerifyResetToken(_pinController.text.trim()),
+    );
-    Navigator.of(context).push(
-      MaterialPageRoute(
-        builder: (context) => PasswordResetPage(token: _pinController.text.trim()),
-      ),
-    );
   },
   child: Container(
     height: 56,
     decoration: BoxDecoration(
         color: AppColors.primaryColor,
         borderRadius: BorderRadius.circular(4)),
-    child: Center(
+    child: _isLoading ? Spinner() : Center(
       child: Text(
         "Continue",

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +17 to +19
class _ResetLinkSentPageState extends State<ResetLinkSentPage> {
final TextEditingController _pinController = TextEditingController();

Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add proper state management and error handling

The page needs to handle different states from PasswordResetBloc to provide better user feedback.

 class _ResetLinkSentPageState extends State<ResetLinkSentPage> {
   final TextEditingController _pinController = TextEditingController();
+  bool _isLoading = false;
+
+  @override
+  Widget build(BuildContext context) {
+    return BlocListener<PasswordResetBloc, PasswordResetState>(
+      listener: (context, state) {
+        if (state is PasswordResetError) {
+          ScaffoldMessenger.of(context).showSnackBar(
+            SnackBar(content: Text(state.message)),
+          );
+          setState(() => _isLoading = false);
+        } else if (state is PasswordResetSuccess) {
+          setState(() => _isLoading = false);
+          Navigator.of(context).push(
+            MaterialPageRoute(
+              builder: (context) => PasswordResetPage(
+                token: _pinController.text.trim()
+              ),
+            ),
+          );
+        }
+      },
+      child: Scaffold(

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines 68 to 103
PinCodeTextField(
appContext: context,
length: 5, // Adjust length if needed
controller: _pinController,
keyboardType: TextInputType.number,
animationType: AnimationType.fade,
hintCharacter: "0",
//backgroundColor: AppColors.boldHeadlineColor4,


textStyle: TextStyle(
fontSize: 28,
fontWeight: FontWeight.w600,
color: AppColors.boldHeadlineColor3

),
pinTheme: PinTheme(

shape: PinCodeFieldShape.box,
borderRadius: BorderRadius.circular(4),

fieldHeight: 64,
fieldWidth: 60,
activeFillColor: AppColors.boldHeadlineColor4,
inactiveFillColor:AppColors.boldHeadlineColor4 ,
selectedFillColor: AppColors.darkThemeBackground,
activeColor: AppColors.boldHeadlineColor4,
inactiveColor: AppColors.boldHeadlineColor4,
selectedColor: AppColors.primaryColor,
fieldOuterPadding: EdgeInsets.symmetric(horizontal: 4),


),
enableActiveFill: true,
onChanged: (value) {},
),
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Enhance PIN verification security and validation

The current PIN implementation needs additional security measures:

  1. Consider increasing PIN length for better security
  2. Add validation for PIN format
  3. Implement rate limiting for failed attempts
  4. Handle PIN completion event
 PinCodeTextField(
   appContext: context,
-  length: 5, // Adjust length if needed
+  length: 6, // Standard OTP length
   controller: _pinController,
   keyboardType: TextInputType.number,
   animationType: AnimationType.fade,
   hintCharacter: "0",
+  beforeTextPaste: (text) {
+    // Validate pasted content
+    return text?.length == 6 && RegExp(r'^\d+$').hasMatch(text ?? '');
+  },
+  onCompleted: (pin) {
+    // Validate PIN format
+    if (RegExp(r'^\d{6}$').hasMatch(pin)) {
+      // Proceed with verification
+    }
+  },
   textStyle: TextStyle(
     fontSize: 28,
📝 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
PinCodeTextField(
appContext: context,
length: 5, // Adjust length if needed
controller: _pinController,
keyboardType: TextInputType.number,
animationType: AnimationType.fade,
hintCharacter: "0",
//backgroundColor: AppColors.boldHeadlineColor4,
textStyle: TextStyle(
fontSize: 28,
fontWeight: FontWeight.w600,
color: AppColors.boldHeadlineColor3
),
pinTheme: PinTheme(
shape: PinCodeFieldShape.box,
borderRadius: BorderRadius.circular(4),
fieldHeight: 64,
fieldWidth: 60,
activeFillColor: AppColors.boldHeadlineColor4,
inactiveFillColor:AppColors.boldHeadlineColor4 ,
selectedFillColor: AppColors.darkThemeBackground,
activeColor: AppColors.boldHeadlineColor4,
inactiveColor: AppColors.boldHeadlineColor4,
selectedColor: AppColors.primaryColor,
fieldOuterPadding: EdgeInsets.symmetric(horizontal: 4),
),
enableActiveFill: true,
onChanged: (value) {},
),
PinCodeTextField(
appContext: context,
length: 6, // Standard OTP length
controller: _pinController,
keyboardType: TextInputType.number,
animationType: AnimationType.fade,
hintCharacter: "0",
beforeTextPaste: (text) {
// Validate pasted content
return text?.length == 6 && RegExp(r'^\d+$').hasMatch(text ?? '');
},
onCompleted: (pin) {
// Validate PIN format
if (RegExp(r'^\d{6}$').hasMatch(pin)) {
// Proceed with verification
}
},
textStyle: TextStyle(
fontSize: 28,
fontWeight: FontWeight.w600,
color: AppColors.boldHeadlineColor3
),
pinTheme: PinTheme(
shape: PinCodeFieldShape.box,
borderRadius: BorderRadius.circular(4),
fieldHeight: 64,
fieldWidth: 60,
activeFillColor: AppColors.boldHeadlineColor4,
inactiveFillColor:AppColors.boldHeadlineColor4 ,
selectedFillColor: AppColors.darkThemeBackground,
activeColor: AppColors.boldHeadlineColor4,
inactiveColor: AppColors.boldHeadlineColor4,
selectedColor: AppColors.primaryColor,
fieldOuterPadding: EdgeInsets.symmetric(horizontal: 4),
),
enableActiveFill: true,
onChanged: (value) {},
),

Comment on lines 56 to 64
Text(
"Enter the verification code sent to ha ******@gmail.com",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w500,
color: AppColors.highlightColor2
),
),
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Replace hardcoded email with proper email masking

The email address is currently hardcoded. It should be dynamically masked based on the user's actual email address.

+ String maskEmail(String email) {
+   final parts = email.split('@');
+   if (parts.length != 2) return email;
+   final username = parts[0];
+   final domain = parts[1];
+   final maskedUsername = username.length > 2 
+     ? '${username.substring(0, 2)}${'*' * (username.length - 2)}'
+     : username;
+   return '$maskedUsername@$domain';
+ }

 Text(
-  "Enter the verification code sent to ha ******@gmail.com",
+  "Enter the verification code sent to ${maskEmail(context.read<PasswordResetBloc>().state.email ?? '')}",
   textAlign: TextAlign.center,
   style: TextStyle(

Committable suggestion skipped: line range outside the PR's diff.

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
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