AuthRepository class
Repository for managing authentication.
Handles user authentication and token management.
Architecture
This repository follows the Repository pattern from clean architecture:
- Manages authentication state (token storage)
- Returns Result types for type-safe error handling
- Abstracts the login API from business logic
Usage
final repository = AuthRepository();
// Login
final result = await repository.login(
username: 'johnd',
password: 'm38rmF\$',
);
switch (result) {
case Ok(:final value):
print('Token: ${value.token}');
print('Is authenticated: ${repository.isAuthenticated}');
case Error(:final error):
print('Login failed: $error');
}
// Check authentication status
if (repository.isAuthenticated) {
final token = repository.currentToken;
// Use token for authenticated requests
}
// Logout
repository.logout();
Token Management
The repository caches the authentication token after successful login. Use currentToken to retrieve it and isAuthenticated to check status. Call logout or clearCache to clear the token.
Test Credentials
Available test users from the Fake Store API:
- username:
johnd, password:m38rmF$ - username:
mor_2314, password:83r5^_
Constructors
- AuthRepository({FakeStoreApiService? apiService})
- Creates a new AuthRepository instance.
Properties
- currentToken → String?
-
Gets the current cached token.
no setter
- hashCode → int
-
The hash code for this object.
no setterinherited
- isAuthenticated → bool
-
Checks if user is authenticated.
no setter
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
Methods
-
clearCache(
) → void - Clears all cached authentication data.
-
login(
{required String username, required String password}) → Future< Result< LoginResponse> > - Authenticates a user with username and password.
-
logout(
) → void - Logs out the current user by clearing the cached token.
-
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
toString(
) → String -
A string representation of this object.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited