第二次提交
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:maibu_satabot_v2/core/consts/http_api_consts.dart';
|
||||
|
||||
import '../../models/user_model.dart';
|
||||
import '../auth_http_datasource.dart';
|
||||
@@ -11,7 +12,7 @@ class AuthHttpDataSourceImpl implements AuthHttpDataSource {
|
||||
@override
|
||||
Future<UserModel> login(String username, String password, sourceType) async {
|
||||
final response = await dio.post(
|
||||
'/login',
|
||||
HttpApiConsts.loginUrl,
|
||||
data: {
|
||||
'username': username,
|
||||
'password': password,
|
||||
@@ -19,11 +20,21 @@ class AuthHttpDataSourceImpl implements AuthHttpDataSource {
|
||||
},
|
||||
);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
print('runtimeType = ${response.data.runtimeType}');
|
||||
return UserModel.fromJson(response.data);
|
||||
} else {
|
||||
throw Exception(response.data['message'] ?? 'Login failed');
|
||||
if (response.statusCode != 200) {
|
||||
throw Exception('网络请求失败: ${response.statusCode}');
|
||||
}
|
||||
|
||||
final responseData = response.data;
|
||||
|
||||
if (responseData['code'] != 200) {
|
||||
throw Exception(responseData['msg'] ?? '业务异常');
|
||||
}
|
||||
|
||||
final loginUsername = responseData['username'];
|
||||
if (loginUsername == null || loginUsername == '') {
|
||||
throw Exception('服务器返回的数据结构不完整(缺少用户信息)');
|
||||
}
|
||||
var userModel = UserModel.fromJson(responseData);
|
||||
return userModel;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import 'package:maibu_satabot_v2/core/data/base_model.dart';
|
||||
|
||||
import '../../../../core/domain/entities/user_entity.dart';
|
||||
|
||||
class UserModel extends UserEntity {
|
||||
class UserModel extends UserEntity implements BaseModel {
|
||||
UserModel({
|
||||
required super.userId,
|
||||
required super.username,
|
||||
|
||||
@@ -1,37 +1,40 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
import 'package:maibu_satabot_v2/core/storage/user_storage.dart';
|
||||
|
||||
import '../../../../core/domain/entities/user_entity.dart';
|
||||
import '../../domain/errors/auth_failure.dart';
|
||||
import '../../domain/repositories/auth_repository.dart';
|
||||
import '../datasources/auth_http_datasource.dart';
|
||||
|
||||
class AuthRepositoryImpl implements AuthRepository {
|
||||
final AuthHttpDataSource remote;
|
||||
final AuthHttpDataSource httpRemote;
|
||||
final UserStorage localTokenStorage;
|
||||
|
||||
AuthRepositoryImpl({required this.remote, required this.localTokenStorage});
|
||||
AuthRepositoryImpl({
|
||||
required this.httpRemote,
|
||||
required this.localTokenStorage,
|
||||
});
|
||||
|
||||
@override
|
||||
// 注意 1:返回类型应该是 Domain 层的 UserEntity,而不是 UserModel
|
||||
Future<UserEntity> login(
|
||||
Future<Either<AuthFailure, UserEntity>> login(
|
||||
String username,
|
||||
String password,
|
||||
int sourceType,
|
||||
) async {
|
||||
try {
|
||||
// 1. 从数据源获取 Data Model
|
||||
final userModel = await remote.login(username, password, sourceType);
|
||||
final userModel = await httpRemote.login(username, password, sourceType);
|
||||
|
||||
// 2. 职责核心:将 Model 转换为 Entity (解耦业务与 JSON 结构)
|
||||
if (userModel != null) {
|
||||
await localTokenStorage.saveUser(userModel);
|
||||
}
|
||||
await localTokenStorage.saveUser(userModel);
|
||||
|
||||
// 2. 只返回纯粹的用户信息实体
|
||||
return userModel.toEntity();
|
||||
return Right(userModel.toEntity());
|
||||
} on DioException catch (e) {
|
||||
final String serverMessage = e.response?.data['msg'] ?? "网络连接异常";
|
||||
return Left(AuthFailure(serverMessage));
|
||||
} catch (e) {
|
||||
// 3. 职责核心:异常翻译
|
||||
// 不直接抛出 Dio 异常,而是抛出业务层定义的自定义异常或返回 Failure
|
||||
throw Exception(e.toString());
|
||||
final cleanMessage = e.toString().replaceFirst('Exception: ', '');
|
||||
return Left(AuthFailure(cleanMessage));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
14
lib/features/auth/domain/errors/auth_failure.dart
Normal file
14
lib/features/auth/domain/errors/auth_failure.dart
Normal file
@@ -0,0 +1,14 @@
|
||||
import 'package:maibu_satabot_v2/core/error/failure.dart';
|
||||
|
||||
class AuthFailure extends Failure implements Exception {
|
||||
final int? code;
|
||||
AuthFailure(super.message, {this.code});
|
||||
}
|
||||
|
||||
class InvalidCredentialsFailure extends AuthFailure {
|
||||
InvalidCredentialsFailure(String message) : super(message);
|
||||
}
|
||||
|
||||
class ServerFailure extends AuthFailure {
|
||||
ServerFailure(String message, int code) : super(message, code: code);
|
||||
}
|
||||
@@ -1,5 +1,12 @@
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
|
||||
import '../../../../core/domain/entities/user_entity.dart';
|
||||
import '../errors/auth_failure.dart';
|
||||
|
||||
abstract class AuthRepository {
|
||||
Future<UserEntity> login(String username, String password, int sourceType);
|
||||
Future<Either<AuthFailure, UserEntity>> login(
|
||||
String username,
|
||||
String password,
|
||||
int sourceType,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
|
||||
import '../../../../core/domain/entities/user_entity.dart';
|
||||
import '../../../../core/domain/usecases/base_usecase.dart';
|
||||
import '../errors/auth_failure.dart';
|
||||
import '../repositories/auth_repository.dart';
|
||||
|
||||
class LoginUseCase implements BaseUseCase<UserEntity, LoginParams> {
|
||||
@@ -8,8 +11,8 @@ class LoginUseCase implements BaseUseCase<UserEntity, LoginParams> {
|
||||
LoginUseCase(this.repository);
|
||||
|
||||
@override
|
||||
Future<UserEntity> call(LoginParams params) {
|
||||
return repository.login(
|
||||
Future<Either<AuthFailure, UserEntity>> call(LoginParams params) async {
|
||||
return await repository.login(
|
||||
params.username,
|
||||
params.password,
|
||||
params.sourceType,
|
||||
|
||||
@@ -5,7 +5,7 @@ import 'package:maibu_satabot_v2/core/consts/tcp_consts.dart';
|
||||
import 'package:maibu_satabot_v2/core/domain/entities/user_entity.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/net_message_dispatcher.dart';
|
||||
|
||||
import '../../../../core/app/app_cubit.dart';
|
||||
import '../../../../core/app/app_user_cubit.dart';
|
||||
import '../../../../core/network/tcp/tcp_client.dart';
|
||||
import '../../../../core/storage/user_storage.dart';
|
||||
import 'auth_state.dart';
|
||||
@@ -17,7 +17,7 @@ import 'auth_state.dart';
|
||||
class AuthCubit extends Cubit<AuthState> {
|
||||
final UserStorage storage;
|
||||
final TcpClient tcp;
|
||||
final AppCubit appCubit;
|
||||
final AppUserCubit appCubit;
|
||||
final NetMessageDispatcher dispatcher;
|
||||
StreamSubscription? _kickOutSub; // 新增:用于管理监听生命周期
|
||||
|
||||
|
||||
@@ -11,11 +11,13 @@ class LoginBloc extends Bloc<LoginEvent, LoginState> {
|
||||
on<LoginSubmitted>((event, emit) async {
|
||||
emit(LoginLoading());
|
||||
try {
|
||||
final user = await loginUseCase(
|
||||
final result = await loginUseCase(
|
||||
LoginParams(event.username, event.password, event.sourceType),
|
||||
);
|
||||
print('✅ Got user: $user');
|
||||
emit(LoginSuccess(user));
|
||||
result.fold(
|
||||
(failure) => emit(LoginFailure(failure.message)),
|
||||
(user) => emit(LoginSuccess(user)),
|
||||
);
|
||||
} catch (e) {
|
||||
emit(LoginFailure(e.toString()));
|
||||
}
|
||||
|
||||
@@ -17,11 +17,13 @@ class LoginCubit extends Cubit<LoginState> {
|
||||
Future<void> login(String username, String password, sourceType) async {
|
||||
emit(LoginLoading());
|
||||
try {
|
||||
final resultUser = await loginUseCase.call(
|
||||
final result = await loginUseCase.call(
|
||||
LoginParams(username, password, sourceType),
|
||||
);
|
||||
authCubit.loginSuccess(resultUser);
|
||||
emit(LoginSuccess(resultUser));
|
||||
result.fold((failure) => emit(LoginFailure(failure.message)), (user) {
|
||||
emit(LoginSuccess(user));
|
||||
authCubit.loginSuccess(user);
|
||||
});
|
||||
} catch (e) {
|
||||
emit(LoginFailure(e.toString()));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class ChangePasswordPage extends StatelessWidget {
|
||||
const ChangePasswordPage({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('ChangePwd')),
|
||||
body: Center(child: Text('Welcome ChangePwd page')),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,42 +7,259 @@ import '../../../../core/router/route_paths.dart';
|
||||
import '../bloc/login_cubit.dart';
|
||||
import '../bloc/login_state.dart';
|
||||
|
||||
class LoginPage extends StatelessWidget {
|
||||
class LoginPage extends StatefulWidget {
|
||||
const LoginPage({super.key});
|
||||
|
||||
@override
|
||||
State<LoginPage> createState() => _LoginPageState();
|
||||
}
|
||||
|
||||
class _LoginPageState extends State<LoginPage> {
|
||||
final _userCtrl = TextEditingController();
|
||||
final _pwdCtrl = TextEditingController();
|
||||
bool _isAgreed = false; // 协议勾选状态
|
||||
bool _obscurePwd = true; // 密码可见性
|
||||
|
||||
LoginPage({super.key});
|
||||
@override
|
||||
void dispose() {
|
||||
_userCtrl.dispose();
|
||||
_pwdCtrl.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Login')),
|
||||
backgroundColor: Colors.white,
|
||||
// 保持 AppBar 简洁或直接去掉
|
||||
appBar: AppBar(backgroundColor: Colors.white, elevation: 0),
|
||||
body: BlocListener<LoginCubit, LoginState>(
|
||||
listener: (context, state) {
|
||||
if (state is LoginSuccess) {
|
||||
// Navigator.pushReplacement(
|
||||
// context,
|
||||
// MaterialPageRoute(builder: (_) => HomePage(user: state.user)),
|
||||
// );
|
||||
context.go(RoutePaths.home);
|
||||
} else if (state is LoginFailure) {
|
||||
// 可以在这里弹出简洁的黑白提示框
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text('登录失败,${state.message}')));
|
||||
}
|
||||
},
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 30.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const SizedBox(height: 40),
|
||||
const Text(
|
||||
"账号登录",
|
||||
style: TextStyle(
|
||||
fontSize: 28,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.black,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
const Text(
|
||||
"请填写以下信息以验证身份",
|
||||
style: TextStyle(fontSize: 15, color: Colors.grey),
|
||||
),
|
||||
const SizedBox(height: 40),
|
||||
|
||||
// 账号输入框
|
||||
_buildInputLabel("账号"),
|
||||
TextField(
|
||||
controller: _userCtrl,
|
||||
cursorColor: Colors.black,
|
||||
decoration: _inputDecoration(hint: "请输入用户名"),
|
||||
),
|
||||
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// 密码输入框
|
||||
_buildInputLabel("密码"),
|
||||
TextField(
|
||||
controller: _pwdCtrl,
|
||||
obscureText: _obscurePwd,
|
||||
cursorColor: Colors.black,
|
||||
decoration: _inputDecoration(
|
||||
hint: "请输入密码",
|
||||
suffixIcon: IconButton(
|
||||
icon: Icon(
|
||||
_obscurePwd
|
||||
? Icons.visibility_off_outlined
|
||||
: Icons.visibility_outlined,
|
||||
color: Colors.grey,
|
||||
size: 20,
|
||||
),
|
||||
onPressed: () => setState(() => _obscurePwd = !_obscurePwd),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// 协议勾选区域
|
||||
_buildProtocolSection(),
|
||||
|
||||
const SizedBox(height: 40),
|
||||
|
||||
// 登录按钮 (使用你的 CCPrimaryButton 并增加状态控制)
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: BlocBuilder<LoginCubit, LoginState>(
|
||||
builder: (context, state) {
|
||||
bool isLoading = state is LoginLoading; // 假设你有 Loading 状态
|
||||
|
||||
return CCPrimaryButton(
|
||||
onPressed: () {
|
||||
if (!_isAgreed) {
|
||||
// 如果没有勾选协议,弹出提示
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('请先阅读并同意用户协议')),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (state is! LoginLoading) {
|
||||
_handleLogin();
|
||||
}
|
||||
},
|
||||
text: state is LoginLoading ? '登录中...' : '登 录',
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// 执行登录逻辑
|
||||
void _handleLogin() {
|
||||
context.read<LoginCubit>().login(_userCtrl.text, _pwdCtrl.text, 2);
|
||||
}
|
||||
|
||||
// 辅助组件:输入框标签
|
||||
Widget _buildInputLabel(String label) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8.0),
|
||||
child: Text(
|
||||
label,
|
||||
style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// 辅助组件:输入框装饰
|
||||
InputDecoration _inputDecoration({required String hint, Widget? suffixIcon}) {
|
||||
return InputDecoration(
|
||||
hintText: hint,
|
||||
hintStyle: TextStyle(color: Colors.grey.shade400, fontSize: 14),
|
||||
filled: true,
|
||||
fillColor: Colors.grey.shade50,
|
||||
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
borderSide: BorderSide(color: Colors.grey.shade200),
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
borderSide: const BorderSide(color: Colors.black, width: 1),
|
||||
),
|
||||
suffixIcon: suffixIcon,
|
||||
);
|
||||
}
|
||||
|
||||
// 辅助组件:协议勾选
|
||||
Widget _buildProtocolSection() {
|
||||
return Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: [
|
||||
SizedBox(
|
||||
height: 24,
|
||||
width: 24,
|
||||
child: Checkbox(
|
||||
value: _isAgreed,
|
||||
activeColor: Colors.black,
|
||||
onChanged: (val) => setState(() => _isAgreed = val!),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Wrap(
|
||||
children: [
|
||||
const Text(
|
||||
"我已阅读并同意 ",
|
||||
style: TextStyle(fontSize: 13, color: Colors.grey),
|
||||
),
|
||||
_protocolText("《用户协议》", () => _showProtocolDetail("用户协议")),
|
||||
const Text(
|
||||
" 和 ",
|
||||
style: TextStyle(fontSize: 13, color: Colors.grey),
|
||||
),
|
||||
_protocolText("《隐私政策》", () => _showProtocolDetail("隐私政策")),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _protocolText(String text, VoidCallback onTap) {
|
||||
return GestureDetector(
|
||||
onTap: onTap,
|
||||
child: Text(
|
||||
text,
|
||||
style: const TextStyle(
|
||||
fontSize: 13,
|
||||
color: Colors.black,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _showProtocolDetail(String title) {
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
backgroundColor: Colors.white,
|
||||
shape: const RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
|
||||
),
|
||||
builder: (context) => Container(
|
||||
padding: const EdgeInsets.all(24),
|
||||
height: MediaQuery.of(context).size.height * 0.7,
|
||||
child: Column(
|
||||
children: [
|
||||
TextField(controller: _userCtrl),
|
||||
TextField(controller: _pwdCtrl, obscureText: true),
|
||||
CCPrimaryButton(
|
||||
onPressed: () {
|
||||
// context.read<LoginBloc>().add(
|
||||
// LoginSubmitted(_userCtrl.text, _pwdCtrl.text),
|
||||
// );
|
||||
context.read<LoginCubit>().login(
|
||||
_userCtrl.text,
|
||||
_pwdCtrl.text,
|
||||
2,
|
||||
);
|
||||
},
|
||||
text: 'Login',
|
||||
Text(
|
||||
title,
|
||||
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
|
||||
),
|
||||
const Divider(height: 32),
|
||||
Expanded(
|
||||
child: SingleChildScrollView(
|
||||
child: Text(
|
||||
"此处放置您的${title}详细内容...\n" * 20,
|
||||
style: const TextStyle(color: Colors.black87, height: 1.5),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: BlocBuilder<LoginCubit, LoginState>(
|
||||
builder: (context, state) {
|
||||
return CCPrimaryButton(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
text: "我已了解",
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class RegisterPage extends StatelessWidget {
|
||||
const RegisterPage({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Register')),
|
||||
body: Center(child: Text('Welcome Register page')),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
19
lib/features/auth/presentation/routes/auth_routes.dart
Normal file
19
lib/features/auth/presentation/routes/auth_routes.dart
Normal file
@@ -0,0 +1,19 @@
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:maibu_satabot_v2/core/router/route_paths.dart';
|
||||
import 'package:maibu_satabot_v2/features/auth/presentation/pages/login_page.dart';
|
||||
|
||||
import '../pages/register_page.dart';
|
||||
|
||||
class AuthRoutes {
|
||||
// 返回一个 List<RouteBase>
|
||||
static List<RouteBase> routes = [
|
||||
GoRoute(
|
||||
path: RoutePaths.login,
|
||||
builder: (context, state) => const LoginPage(),
|
||||
),
|
||||
GoRoute(
|
||||
path: RoutePaths.register,
|
||||
builder: (context, state) => const RegisterPage(),
|
||||
),
|
||||
];
|
||||
}
|
||||
Reference in New Issue
Block a user