login impl api

This commit is contained in:
MooN 2026-02-14 02:16:02 +06:30
parent 9b59c9eb07
commit 77e94b5ec0
15 changed files with 591 additions and 131 deletions

View File

@ -0,0 +1,6 @@
class AppConfig {
const AppConfig._();
static const String apiBaseUrl = 'https://api-tms-uat.kbzbank.com:8443';
static const String eReceiptSecret = 'y812J21lhha11OS';
}

View File

@ -0,0 +1,87 @@
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
class LoggingHttpClient extends http.BaseClient {
LoggingHttpClient([http.Client? innerClient])
: _innerClient = innerClient ?? http.Client();
final http.Client _innerClient;
@override
Future<http.StreamedResponse> send(http.BaseRequest request) async {
final requestBody = request is http.Request ? request.body : null;
_logRequest(request, requestBody);
try {
final response = await _innerClient.send(request);
final responseBytes = await response.stream.toBytes();
final responseBody = utf8.decode(responseBytes);
_logResponse(response, responseBody);
return http.StreamedResponse(
Stream<List<int>>.fromIterable([responseBytes]),
response.statusCode,
contentLength: response.contentLength,
request: response.request,
headers: response.headers,
isRedirect: response.isRedirect,
persistentConnection: response.persistentConnection,
reasonPhrase: response.reasonPhrase,
);
} catch (error, stackTrace) {
debugPrint('[API][ERROR] ${request.method} ${request.url}');
debugPrint('[API][ERROR] $error');
debugPrint('[API][ERROR] $stackTrace');
rethrow;
}
}
@override
void close() {
_innerClient.close();
super.close();
}
void _logRequest(http.BaseRequest request, String? requestBody) {
final safeHeaders = _sanitizeHeaders(request.headers);
debugPrint('[API][REQUEST] ${request.method} ${request.url}');
debugPrint('[API][REQUEST][HEADERS] ${request.headers}');
if (requestBody != null && requestBody.isNotEmpty) {
debugPrint('[API][REQUEST][BODY] $requestBody');
}
}
void _logResponse(http.StreamedResponse response, String responseBody) {
final safeHeaders = _sanitizeHeaders(response.headers);
debugPrint(
'[API][RESPONSE] ${response.statusCode} ${response.request?.method} ${response.request?.url}',
);
debugPrint('[API][RESPONSE][HEADERS] $safeHeaders');
if (responseBody.isNotEmpty) {
debugPrint('[API][RESPONSE][BODY] $responseBody');
}
}
Map<String, String> _sanitizeHeaders(Map<String, String> headers) {
final safeHeaders = Map<String, String>.from(headers);
const sensitiveKeys = {
'authorization',
'x-api-key',
'api-key',
'x-signature',
'cookie',
'set-cookie',
};
for (final key in safeHeaders.keys.toList()) {
if (sensitiveKeys.contains(key.toLowerCase())) {
safeHeaders[key] = '***';
}
}
return safeHeaders;
}
}

View File

@ -0,0 +1,78 @@
import 'dart:convert';
import 'package:e_receipt_mobile/domain/entities/login_user.dart';
import 'package:e_receipt_mobile/domain/repositories/auth_repository.dart';
import 'package:crypto/crypto.dart';
import 'package:http/http.dart' as http;
class ApiAuthRepository implements AuthRepository {
ApiAuthRepository({
required this.baseUrl,
required this.eReceiptSecret,
http.Client? client,
}) : _client = client ?? http.Client();
final String baseUrl;
final String eReceiptSecret;
final http.Client _client;
@override
Future<LoginUser> login({
required String username,
required String password,
}) async {
final uri = Uri.parse('$baseUrl/receipt/auth/login');
final requestBody = jsonEncode({
'username': username.trim().toLowerCase(),
'password': password,
});
final encodedApiKey = _generateApiKey(requestBody);
final response = await _client.post(
uri,
headers: {
'Content-Type': 'application/json',
'x-api-key': encodedApiKey,
},
body: requestBody,
);
if (response.statusCode >= 200 && response.statusCode < 300) {
final data = _asMap(response.body);
final apiUsername = (data['username'] ?? data['email'])?.toString();
return LoginUser(
username: apiUsername?.trim().isNotEmpty == true
? apiUsername!.trim()
: username.trim(),
);
}
throw Exception(_extractErrorMessage(response.body));
}
String _generateApiKey(String bodyString) {
final dataToHash = '$bodyString$eReceiptSecret';
return sha256.convert(utf8.encode(dataToHash)).toString();
}
Map<String, dynamic> _asMap(String body) {
try {
final decoded = jsonDecode(body);
if (decoded is Map<String, dynamic>) {
return decoded;
}
return <String, dynamic>{};
} catch (_) {
return <String, dynamic>{};
}
}
String _extractErrorMessage(String body) {
final data = _asMap(body);
final message = data['message'] ?? data['error'] ?? data['detail'];
if (message == null) {
return 'Login failed';
}
return message.toString();
}
}

View File

@ -0,0 +1,22 @@
import 'package:e_receipt_mobile/domain/entities/login_user.dart';
import 'package:e_receipt_mobile/domain/repositories/auth_repository.dart';
class MockAuthRepository implements AuthRepository {
@override
Future<LoginUser> login({
required String username,
required String password,
}) async {
await Future<void>.delayed(const Duration(milliseconds: 800));
if (username.trim().isEmpty || password.isEmpty) {
throw Exception('Username and password are required.');
}
if (password.length < 6) {
throw Exception('Password must be at least 6 characters.');
}
return LoginUser(username: username.trim());
}
}

View File

@ -0,0 +1,5 @@
class LoginUser {
const LoginUser({required this.username});
final String username;
}

View File

@ -0,0 +1,5 @@
import 'package:e_receipt_mobile/domain/entities/login_user.dart';
abstract class AuthRepository {
Future<LoginUser> login({required String username, required String password});
}

View File

@ -1,122 +1,24 @@
import 'package:e_receipt_mobile/presentation/login/login_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
void main() {
runApp(const MyApp());
runApp(const ProviderScope(child: EReceiptApp()));
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
class EReceiptApp extends StatelessWidget {
const EReceiptApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
title: 'E-Receipt',
debugShowCheckedModeBanner: false,
theme: ThemeData(
// This is the theme of your application.
//
// TRY THIS: Try running your application with "flutter run". You'll see
// the application has a purple toolbar. Then, without quitting the app,
// try changing the seedColor in the colorScheme below to Colors.green
// and then invoke "hot reload" (save your changes or press the "hot
// reload" button in a Flutter-supported IDE, or press "r" if you used
// the command line to start the app).
//
// Notice that the counter didn't reset back to zero; the application
// state is not lost during the reload. To reset the state, use hot
// restart instead.
//
// This works for code too, not just values: Most code changes can be
// tested with just a hot reload.
colorScheme: .fromSeed(seedColor: Colors.deepPurple),
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// TRY THIS: Try changing the color here to a specific color (to
// Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
// change color while the other colors stay the same.
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
//
// TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
// action in the IDE, or press "p" in the console), to see the
// wireframe for each widget.
mainAxisAlignment: .center,
children: [
const Text('You have pushed the button this many times:'),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
useMaterial3: true,
),
home: const LoginPage(),
);
}
}

View File

@ -0,0 +1,75 @@
import 'package:flutter/material.dart';
Widget roundedInput({
required TextEditingController controller,
required String hint,
required IconData icon,
bool isPassword = false,
}) {
return RoundedInput(
controller: controller,
hint: hint,
icon: icon,
isPassword: isPassword,
);
}
class RoundedInput extends StatefulWidget {
const RoundedInput({
super.key,
required this.controller,
required this.hint,
required this.icon,
this.isPassword = false,
});
final TextEditingController controller;
final String hint;
final IconData icon;
final bool isPassword;
@override
State<RoundedInput> createState() => _RoundedInputState();
}
class _RoundedInputState extends State<RoundedInput> {
late bool _obscured;
@override
void initState() {
super.initState();
_obscured = widget.isPassword;
}
@override
Widget build(BuildContext context) {
return TextField(
controller: widget.controller,
obscureText: _obscured,
decoration: InputDecoration(
hintText: widget.hint,
prefixIcon: Icon(widget.icon, color: Colors.grey),
suffixIcon: widget.isPassword
? IconButton(
onPressed: () {
setState(() {
_obscured = !_obscured;
});
},
icon: Icon(
_obscured ? Icons.visibility : Icons.visibility_off,
color: Colors.grey,
),
)
: null,
filled: true,
fillColor: const Color(0xFFE9EEF3),
contentPadding: const EdgeInsets.symmetric(vertical: 16),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(30),
borderSide: BorderSide.none,
),
),
);
}
}

View File

@ -0,0 +1,18 @@
import 'package:flutter/material.dart';
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Home'),
centerTitle: true,
),
body: const Center(
child: Text('Welcome to Home Screen'),
),
);
}
}

View File

@ -0,0 +1,124 @@
import 'package:e_receipt_mobile/presentation/components/rounded_input.dart';
import 'package:e_receipt_mobile/presentation/home/home_screen.dart';
import 'package:e_receipt_mobile/presentation/login/login_view_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class LoginPage extends ConsumerStatefulWidget {
const LoginPage({super.key});
@override
ConsumerState<LoginPage> createState() => _LoginPageState();
}
class _LoginPageState extends ConsumerState<LoginPage> {
final _formKey = GlobalKey<FormState>();
final _usernameController = TextEditingController();
final _passwordController = TextEditingController();
@override
void dispose() {
_usernameController.dispose();
_passwordController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final state = ref.watch(loginViewModelProvider);
ref.listen(loginViewModelProvider, (previous, next) {
if (!mounted) {
return;
}
if (next.errorMessage != null &&
previous?.errorMessage != next.errorMessage) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(next.errorMessage!),
backgroundColor: Colors.red,
),
);
}
if (next.successMessage != null &&
previous?.successMessage != next.successMessage) {
Navigator.of(context).pushReplacement(
MaterialPageRoute<void>(
builder: (_) => const HomeScreen(),
),
);
}
});
return Scaffold(
backgroundColor: Colors.blue,
body: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(32),
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 420),
child: Card(
elevation: 8,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(24),
),
child: Padding(
padding: const EdgeInsets.all(20),
child: Form(
key: _formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
'E-Receipt',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.headlineSmall,
),
const SizedBox(height: 20),
//Username
roundedInput(controller: _usernameController, hint: "Username", icon: Icons.person),
const SizedBox(height: 12),
//Password
roundedInput(controller: _passwordController, hint: "Password", icon: Icons.lock, isPassword: true),
const SizedBox(height: 20),
FilledButton(
onPressed: state.isLoading
? null
: () {
ref
.read(loginViewModelProvider.notifier)
.clearMessages();
if (_formKey.currentState?.validate() ??
false) {
ref
.read(loginViewModelProvider.notifier)
.login(
username: _usernameController.text,
password: _passwordController.text,
);
}
},
child: state.isLoading
? const SizedBox(
height: 20,
width: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
),
)
: const Text('Login'),
),
],
),
),
),
),
),
),
),
);
}
}

View File

@ -0,0 +1,27 @@
class LoginState {
const LoginState({
this.isLoading = false,
this.errorMessage,
this.successMessage,
});
final bool isLoading;
final String? errorMessage;
final String? successMessage;
LoginState copyWith({
bool? isLoading,
String? errorMessage,
String? successMessage,
bool clearError = false,
bool clearSuccess = false,
}) {
return LoginState(
isLoading: isLoading ?? this.isLoading,
errorMessage: clearError ? null : errorMessage ?? this.errorMessage,
successMessage: clearSuccess
? null
: successMessage ?? this.successMessage,
);
}
}

View File

@ -0,0 +1,60 @@
import 'package:e_receipt_mobile/core/config/app_config.dart';
import 'package:e_receipt_mobile/core/network/logging_http_client.dart';
import 'package:e_receipt_mobile/data/repositories/api_auth_repository.dart';
import 'package:e_receipt_mobile/domain/repositories/auth_repository.dart';
import 'package:e_receipt_mobile/presentation/login/login_state.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:http/http.dart' as http;
final httpClientProvider = Provider<http.Client>((ref) {
final client = LoggingHttpClient();
ref.onDispose(client.close);
return client;
});
final authRepositoryProvider = Provider<AuthRepository>((ref) {
return ApiAuthRepository(
baseUrl: AppConfig.apiBaseUrl,
eReceiptSecret: AppConfig.eReceiptSecret,
client: ref.watch(httpClientProvider),
);
});
final loginViewModelProvider =
StateNotifierProvider<LoginViewModel, LoginState>((ref) {
return LoginViewModel(ref.watch(authRepositoryProvider));
});
class LoginViewModel extends StateNotifier<LoginState> {
LoginViewModel(this._authRepository) : super(const LoginState());
final AuthRepository _authRepository;
Future<void> login({required String username, required String password}) async {
state = state.copyWith(
isLoading: true,
clearError: true,
clearSuccess: true,
);
try {
final user = await _authRepository.login(
username: username,
password: password,
);
state = state.copyWith(
isLoading: false,
successMessage: 'Welcome ${user.username}',
);
} catch (error) {
state = state.copyWith(
isLoading: false,
errorMessage: error.toString().replaceFirst('Exception: ', ''),
);
}
}
void clearMessages() {
state = state.copyWith(clearError: true, clearSuccess: true);
}
}

View File

@ -41,6 +41,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.19.1"
crypto:
dependency: "direct main"
description:
name: crypto
sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf
url: "https://pub.dev"
source: hosted
version: "3.0.7"
cupertino_icons:
dependency: "direct main"
description:
@ -70,11 +78,35 @@ packages:
url: "https://pub.dev"
source: hosted
version: "6.0.0"
flutter_riverpod:
dependency: "direct main"
description:
name: flutter_riverpod
sha256: "9532ee6db4a943a1ed8383072a2e3eeda041db5657cdf6d2acecf3c21ecbe7e1"
url: "https://pub.dev"
source: hosted
version: "2.6.1"
flutter_test:
dependency: "direct dev"
description: flutter
source: sdk
version: "0.0.0"
http:
dependency: "direct main"
description:
name: http
sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412"
url: "https://pub.dev"
source: hosted
version: "1.6.0"
http_parser:
dependency: transitive
description:
name: http_parser
sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571"
url: "https://pub.dev"
source: hosted
version: "4.1.2"
leak_tracker:
dependency: transitive
description:
@ -139,6 +171,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.9.1"
riverpod:
dependency: transitive
description:
name: riverpod
sha256: "59062512288d3056b2321804332a13ffdd1bf16df70dcc8e506e411280a72959"
url: "https://pub.dev"
source: hosted
version: "2.6.1"
sky_engine:
dependency: transitive
description: flutter
@ -160,6 +200,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.12.1"
state_notifier:
dependency: transitive
description:
name: state_notifier
sha256: b8677376aa54f2d7c58280d5a007f9e8774f1968d1fb1c096adcb4792fba29bb
url: "https://pub.dev"
source: hosted
version: "1.0.0"
stream_channel:
dependency: transitive
description:
@ -192,6 +240,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.7.7"
typed_data:
dependency: transitive
description:
name: typed_data
sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006
url: "https://pub.dev"
source: hosted
version: "1.4.0"
vector_math:
dependency: transitive
description:
@ -208,6 +264,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "15.0.2"
web:
dependency: transitive
description:
name: web
sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a"
url: "https://pub.dev"
source: hosted
version: "1.1.1"
sdks:
dart: ">=3.10.7 <4.0.0"
flutter: ">=3.18.0-18.0.pre.54"

View File

@ -34,6 +34,9 @@ dependencies:
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.8
flutter_riverpod: ^2.6.1
http: ^1.2.2
crypto: ^3.0.6
dev_dependencies:
flutter_test:

View File

@ -1,30 +1,14 @@
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:e_receipt_mobile/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
testWidgets('Login page smoke test', (WidgetTester tester) async {
await tester.pumpWidget(const ProviderScope(child: EReceiptApp()));
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
expect(find.text('Login'), findsOneWidget);
expect(find.text('Sign In'), findsOneWidget);
expect(find.text('Username'), findsOneWidget);
expect(find.text('Password'), findsOneWidget);
});
}