Replies: 2 comments 1 reply
|
It looks spectacular. Can you check that everything is working properly? @Dynavy |
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Discussion: Full Authentication Flow Implementation
Summary
This flow covers the entire process for login, registration (step one and step two), handling API communication, token extraction and storage, error handling, and UI updates based on the changes in the AuthState. The implementation follows the MVVM (Model-View-ViewModel) architecture to ensure clean separation of concerns, scalability, and maintainability.
This process was initially introduced in version v1.0.0, as discussed in a previous post about the authentication flow. However, this version has seen considerable improvements, including refined API communication, enhanced response handling, robust error management, and a more structured approach to UI updates via AuthState. Additionally, new components have been introduced for user data extraction and session management, making the overall authentication flow even more robust and maintainable.
Detailed Breakdown of the Implementation
1. User Interface (UI Layer)
Screens:
The UI layer includes the
LoginScreen,RegisterStepOneScreen, andRegisterStepTwoScreen. These screens are responsible for gathering the necessary user inputs.Frontend Validation:
Upon data entry, the screens validate the inputs. If the data is correct, the authentication process is initiated; otherwise, appropriate error messages are displayed.
Error Display:
Validation failures trigger error messages in the UI to inform the user of any issues with the input.
2. AuthViewModel (ViewModel Layer for Authentication)
Invoking Auth Methods:
After successful frontend validation, the
AuthViewModelinvokes the necessary authentication methods via theUserRepository. This delegation ensures that business logic remains outside the ViewModel.Updating AuthState:
The
AuthViewModelreceives a response from theUserRepositoryin the form of anAuthState—indicating either success or error. The UI observes this state (using mechanisms likeLaunchedEffectin Compose) to provide real-time feedback, displaying success, error, or loading states as needed.Integrating User Data Extraction:
When authentication is successful, the
AuthViewModelleverages UserService to extract the required JSON fields (such as username, email, token, etc.) from the backend response. With these extracted fields, it callsUserSession.setUser(...)to create and store a user instance.3. UserRepository (Repository Layer)
Calling AuthService Methods:
The
UserRepositoryacts as an intermediary between theAuthViewModeland theAuthService. It invokes the appropriate methods in theAuthServicefor login or registration.Token Extraction & Error Handling:
On receiving a successful response from the
AuthService, the repository extracts the authentication token. In case of errors, it extracts the error message from the response and incorporates it into theAuthState, which is then observed by theAuthViewModel.Session Storage:
On a successful authentication, the token is securely stored (for example, in a
DataStoreManager), and the user data is updated via UserService and UserSession.4. Service Layer
AuthService
Making API Requests:
Responsible for making the actual API requests to the backend, using appropriate DTOs to ensure that correct data and tokens are sent.
Handling API Responses:
Once the backend responds,
AuthServicemaps the response to the appropriate DTO. If an authentication token is present, it is extracted and returned to theUserRepository.ApiService Interface Implementation:
By implementing the
ApiServiceinterface, theAuthServiceensures that API communication is decoupled from the rest of the application logic, which improves testability and maintainability.UserService
Extracting User Data:
Upon a successful authentication response, the
UserServiceextracts the necessary fields from the JSON response. This may include username, email, token, and any other relevant data.Triggering Session Updates:
With the extracted data,
UserServicecallsUserSession.setUser(...)to create an instance of theUserand store it for later use. This user instance is then made available to the UI through a dedicatedUserViewModel.5. Session Management and UserViewModel
UserSession
Source of Truth:
UserSessionserves as the central repository for the authenticated user's data and tokens. It stores this information in memory and persists it securely (using mechanisms such asDataStoreManageror encrypted storage).Global Access:
Any component that needs user information—be it services or ViewModels—accesses it through
UserSession.UserViewModel
A dedicated
UserViewModelis responsible for exposing the user data stored inUserSessionto the UI.Example of displaying the stored data in the Screens:
This allows any extracted field (like username, email, phone number,etc...) to be accessed in any Screen.
Flow Explanation
UI Layer: The flow begins when the user interacts with the login or registration screen. The UI validates the input data to ensure that all necessary fields are correctly filled before proceeding with the real authentication trough the backend.
ViewModel Layer: Once the inputs are validated, the
AuthViewModelcalls the necessary authentication methods via theAuthViewModel. It waits for the response from theUserRepository.Repository Layer: The
UserRepositorycommunicates with theAuthServiceto make the API call to the backend. It processes the response by extracting the token or error message and passes it back to theAuthViewModel.If the token is extracted successfully, it gets saved on the frontend via the
DataStoreManager.Service Layer: The
AuthServicemakes the API request using the appropriate DTOs and ensures the correct tokens are attached. It processes the response from the backend and returns the result to theUserRepository.Upon success,
UserServiceextracts the JSON fields from the response and callsUserSession.setUser(...)to update the session.Session Management:
UserSessionholds the authenticated user's data, which is then observed by the UserViewModel.Response Handling: Once the response is processed by the
UserRepository, it updates theAuthStateand returns it to theAuthViewModel.UI Update: The
AuthViewModelobserves the updatedAuthStateand updates the UI, which may display success, error, or loading states based on the result.The
UserViewModelhas the responsability to display the user stored data in the screens.Enhancements Made
Separation of Concerns
AuthViewModelandUserRepository.AuthService.UserService.UserSessionandUserViewModel.This clear division ensures a clean and maintainable codebase.
Robust Error Handling
AuthState.Interface Implementation
AuthServiceimplements theApiServiceinterface.Real-time UI Feedback
StateFlow) and Compose’sLaunchedEffect.User Session Integration
UserSessionand exposed throughUserViewModel.Related Links
State Management (Jetpack Compose + StateFlow): State Management (Jetpack Compose + StateFlow) #63
User Register flow in Backend: User Registration flow v2.0.0 copay-app-backend#97
User Login flow in Backend: User Login Flow copay-app-backend#38
AuthController Validation and Exceptions Flow in Backend: AuthController Validation and Exceptions Flow copay-app-backend#49
Mermaid Diagram
All reactions