feat: Phase 1 complete — Matrix login, rooms, chat, profile

- Direct m.login.password auth against matrix.m8chat.au
- Room list with unread badges, last message, timestamps
- Chat timeline (text, images, files, replies, reactions)
- Profile screen with expandable Notifications and Security sections
- Olm E2EE initialisation (web WASM bootstrap)
- Global error handler preventing Matrix SDK crashes
- GoRouter with refreshListenable (no recreation on auth change)
- Feature-first clean architecture: Riverpod + GoRouter + Drift
- Deployed to https://app2.m8chat.au

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-04-02 06:26:57 +10:00
commit 8f13c725a4
114 changed files with 4336 additions and 0 deletions

View File

@@ -0,0 +1,95 @@
// Version: 1.0.3 | Created: 2026-04-01
// Auth repository: handles all Matrix login/logout API interactions.
// Uses the Matrix Dart SDK — no raw HTTP calls for auth.
import 'package:matrix/matrix.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../../../core/config/app_config.dart';
import '../../../core/network/matrix_client.dart';
import '../domain/auth_failure.dart';
part 'auth_repository.g.dart';
@riverpod
AuthRepository authRepository(Ref ref) {
return AuthRepository(client: ref.watch(matrixClientProvider));
}
/// Handles authentication interactions with the Matrix homeserver.
class AuthRepository {
AuthRepository({required Client client}) : _client = client;
final Client _client;
/// Attempts password login. Returns [LoginResponse] on success,
/// throws [AuthFailure] on failure.
///
/// Matrix error codes mapped:
/// M_FORBIDDEN → [InvalidCredentials]
/// M_USER_DEACTIVATED → [AccountDisabled]
/// Network error → [NetworkError]
Future<LoginResponse> login({
required String username,
required String password,
}) async {
try {
// Set homeserver directly — avoids network round-trips and version checks
// that checkHomeserver() makes. The setter is public in matrix 0.33.0.
_client.homeserver = Uri.parse(AppConfig.matrixBaseUrl);
return await _client.login(
LoginType.mLoginPassword,
identifier: AuthenticationUserIdentifier(user: username),
password: password,
initialDeviceDisplayName: 'M8Chat',
);
} on MatrixException catch (e) {
throw switch (e.errcode) {
'M_FORBIDDEN' => const AuthFailure.invalidCredentials(),
'M_USER_DEACTIVATED' => const AuthFailure.accountDisabled(),
_ => AuthFailure.serverError(
statusCode: e.response?.statusCode,
message: e.errorMessage,
),
};
} on Exception catch (e) {
// Covers SocketException, TimeoutException, etc.
final msg = e.toString().toLowerCase();
if (msg.contains('socket') ||
msg.contains('connection') ||
msg.contains('host lookup') ||
msg.contains('timeout')) {
throw AuthFailure.networkError(message: e.toString());
}
throw AuthFailure.unknown(message: e.toString());
}
}
/// Logs out the current session on the homeserver.
/// Silently succeeds if the token is already invalid (network-first logout).
Future<void> logout() async {
try {
await _client.logout();
} on MatrixException {
// Token already invalid — treat as successful logout.
} on Exception {
// Network offline — proceed with local cleanup regardless.
}
}
/// Restores an existing Matrix session using a stored access token.
Future<void> restoreSession({
required String accessToken,
required String userId,
required String deviceId,
}) async {
await _client.init(
newToken: accessToken,
newUserID: userId,
newDeviceID: deviceId,
newDeviceName: 'M8Chat',
newHomeserver: Uri.parse(AppConfig.matrixBaseUrl),
newOlmAccount: null,
);
}
}

View File

@@ -0,0 +1,41 @@
// Version: 1.0.0 | Created: 2026-04-01
// Typed failure hierarchy for authentication errors.
// UI maps these to human-readable messages — never expose raw exception text.
import 'package:freezed_annotation/freezed_annotation.dart';
part 'auth_failure.freezed.dart';
/// All ways authentication can fail.
@freezed
sealed class AuthFailure with _$AuthFailure {
/// Username or password was incorrect.
const factory AuthFailure.invalidCredentials() = InvalidCredentials;
/// Could not reach the Matrix homeserver.
const factory AuthFailure.networkError({String? message}) = NetworkError;
/// The server returned an unexpected response.
const factory AuthFailure.serverError({int? statusCode, String? message}) =
ServerError;
/// User's account has been disabled or deactivated.
const factory AuthFailure.accountDisabled() = AccountDisabled;
/// An unexpected error that doesn't fit the categories above.
const factory AuthFailure.unknown({required String message}) = UnknownFailure;
}
/// Maps an [AuthFailure] to a user-facing string (Australian English).
extension AuthFailureMessage on AuthFailure {
String get userMessage => switch (this) {
InvalidCredentials() => 'Incorrect username or password. Please try again.',
NetworkError() =>
'Could not connect to the server. Check your internet connection and try again.',
ServerError(statusCode: final code) =>
'The server returned an error${code != null ? ' (code $code)' : ''}. Please try again shortly.',
AccountDisabled() =>
'Your account has been disabled. Please contact the administrator.',
UnknownFailure(message: final msg) => 'Something went wrong: $msg',
};
}

View File

@@ -0,0 +1,39 @@
// Version: 1.0.0 | Created: 2026-04-01
// Riverpod controller for the login form.
// Owns the loading state visible to the login screen widget.
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../../../core/auth/auth_notifier.dart';
import '../../../core/auth/auth_state.dart';
part 'login_controller.g.dart';
@riverpod
class LoginController extends _$LoginController {
@override
bool build() => false; // isLoading
/// Delegates to [AuthNotifier.login]. Returns the failure message if any,
/// or null on success.
Future<String?> login({
required String username,
required String password,
}) async {
state = true;
try {
await ref
.read(authProvider.notifier)
.login(username: username, password: password);
// Check if auth failed.
final authState = ref.read(authProvider);
return authState.maybeWhen(
unauthenticated: (failure) => failure,
orElse: () => null,
);
} finally {
state = false;
}
}
}

View File

@@ -0,0 +1,241 @@
// Version: 1.0.0 | Created: 2026-04-01
// Login screen. Username + password only. No registration link.
// Respects system theme preference.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'login_controller.dart';
class LoginScreen extends ConsumerStatefulWidget {
const LoginScreen({super.key});
@override
ConsumerState<LoginScreen> createState() => _LoginScreenState();
}
class _LoginScreenState extends ConsumerState<LoginScreen> {
final _formKey = GlobalKey<FormState>();
final _usernameController = TextEditingController();
final _passwordController = TextEditingController();
bool _passwordVisible = false;
@override
void dispose() {
_usernameController.dispose();
_passwordController.dispose();
super.dispose();
}
Future<void> _submit() async {
if (!(_formKey.currentState?.validate() ?? false)) return;
final failure = await ref
.read(loginControllerProvider.notifier)
.login(
username: _usernameController.text.trim(),
password: _passwordController.text,
);
if (failure != null && mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(failure),
backgroundColor: Theme.of(context).colorScheme.error,
),
);
}
}
@override
Widget build(BuildContext context) {
final isLoading = ref.watch(loginControllerProvider);
final theme = Theme.of(context);
return Scaffold(
body: SafeArea(
child: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 24),
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 400),
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_LogoSection(theme: theme),
const SizedBox(height: 48),
_UsernameField(controller: _usernameController),
const SizedBox(height: 16),
_PasswordField(
controller: _passwordController,
isVisible: _passwordVisible,
onToggleVisibility: () {
setState(() => _passwordVisible = !_passwordVisible);
},
onSubmit: _submit,
),
const SizedBox(height: 32),
_SignInButton(isLoading: isLoading, onPressed: _submit),
const SizedBox(height: 16),
_ServerLabel(theme: theme),
],
),
),
),
),
),
),
);
}
}
class _LogoSection extends StatelessWidget {
const _LogoSection({required this.theme});
final ThemeData theme;
@override
Widget build(BuildContext context) {
return Column(
children: [
Image.asset(
'assets/images/logo.png',
width: 96,
height: 96,
errorBuilder: (_, __, ___) => CircleAvatar(
radius: 48,
backgroundColor: theme.colorScheme.primary,
child: const Icon(Icons.chat_bubble, size: 48, color: Colors.white),
),
),
const SizedBox(height: 20),
Text(
'M8Chat',
style: theme.textTheme.headlineMedium?.copyWith(
fontWeight: FontWeight.bold,
color: theme.colorScheme.primary,
),
),
const SizedBox(height: 8),
Text(
'Sign in to continue',
style: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.onSurface.withAlpha(153),
),
),
],
);
}
}
class _UsernameField extends StatelessWidget {
const _UsernameField({required this.controller});
final TextEditingController controller;
@override
Widget build(BuildContext context) {
return TextFormField(
controller: controller,
decoration: const InputDecoration(
labelText: 'Username',
hintText: 'Enter your username',
prefixIcon: Icon(Icons.person_outline),
),
textInputAction: TextInputAction.next,
autocorrect: false,
enableSuggestions: false,
keyboardType: TextInputType.emailAddress,
validator: (value) {
if (value == null || value.trim().isEmpty) {
return 'Please enter your username.';
}
return null;
},
);
}
}
class _PasswordField extends StatelessWidget {
const _PasswordField({
required this.controller,
required this.isVisible,
required this.onToggleVisibility,
required this.onSubmit,
});
final TextEditingController controller;
final bool isVisible;
final VoidCallback onToggleVisibility;
final VoidCallback onSubmit;
@override
Widget build(BuildContext context) {
return TextFormField(
controller: controller,
decoration: InputDecoration(
labelText: 'Password',
hintText: 'Enter your password',
prefixIcon: const Icon(Icons.lock_outline),
suffixIcon: IconButton(
icon: Icon(isVisible ? Icons.visibility_off : Icons.visibility),
onPressed: onToggleVisibility,
tooltip: isVisible ? 'Hide password' : 'Show password',
),
),
obscureText: !isVisible,
textInputAction: TextInputAction.done,
onFieldSubmitted: (_) => onSubmit(),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your password.';
}
return null;
},
);
}
}
class _SignInButton extends StatelessWidget {
const _SignInButton({required this.isLoading, required this.onPressed});
final bool isLoading;
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: isLoading ? null : onPressed,
child: isLoading
? const SizedBox(
height: 22,
width: 22,
child: CircularProgressIndicator(
strokeWidth: 2.5,
color: Colors.white,
),
)
: const Text('Sign In'),
);
}
}
class _ServerLabel extends StatelessWidget {
const _ServerLabel({required this.theme});
final ThemeData theme;
@override
Widget build(BuildContext context) {
return Text(
'matrix.m8chat.au',
textAlign: TextAlign.center,
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurface.withAlpha(102),
),
);
}
}