70 lines
2.4 KiB
Dart
70 lines
2.4 KiB
Dart
import 'package:dio/dio.dart';
|
||
import 'package:flutter/foundation.dart';
|
||
import '../consts/http_api_consts.dart';
|
||
|
||
/// 设备操作权限校验服务
|
||
/// 接口: GET /iot/device/hasPermission?deviceId=xxx
|
||
/// 通过条件: code==200 且 data==true,缺一不可
|
||
/// 安全原则: 仅明确收到 code=200 && data=true 才放行,其余所有情况一律阻止
|
||
class DevicePermissionService {
|
||
final Dio _dio;
|
||
|
||
DevicePermissionService(this._dio);
|
||
|
||
/// 校验当前用户是否有权操作指定设备
|
||
/// 返回 true 表示有权限,false 表示无权限或校验失败
|
||
Future<bool> checkPermission(String deviceId) async {
|
||
debugPrint('🔐 [权限校验] 开始校验 - deviceId: $deviceId');
|
||
|
||
try {
|
||
final response = await _dio.get(
|
||
HttpApiConsts.hasPermission,
|
||
queryParameters: {'deviceId': deviceId},
|
||
);
|
||
|
||
debugPrint('🔐 [权限校验] HTTP响应 - statusCode: ${response.statusCode}');
|
||
|
||
// HTTP 层面必须 200
|
||
if (response.statusCode != 200) {
|
||
debugPrint('🔐 [权限校验] ❌ HTTP状态码非200: ${response.statusCode}');
|
||
return false;
|
||
}
|
||
|
||
final body = response.data;
|
||
debugPrint('🔐 [权限校验] 响应体: $body');
|
||
|
||
// body 必须是 Map
|
||
if (body is! Map<String, dynamic>) {
|
||
debugPrint('🔐 [权限校验] ❌ 响应体格式异常,非Map类型');
|
||
return false;
|
||
}
|
||
|
||
final code = body['code'];
|
||
final data = body['data'];
|
||
|
||
debugPrint('🔐 [权限校验] code=$code (type: ${code.runtimeType}), data=$data (type: ${data.runtimeType})');
|
||
|
||
// code 必须是 200(兼容 int 和 String)
|
||
final codeMatch = code == 200 || code.toString() == '200';
|
||
// data 必须是 true
|
||
final dataMatch = data == true || data.toString() == 'true';
|
||
|
||
if (codeMatch && dataMatch) {
|
||
debugPrint('🔐 [权限校验] ✅ 校验通过 - code=200, data=true');
|
||
return true;
|
||
}
|
||
|
||
debugPrint('🔐 [权限校验] ❌ 校验未通过 - codeMatch=$codeMatch, dataMatch=$dataMatch');
|
||
return false;
|
||
} on DioException catch (e) {
|
||
// 网络异常(断网、超时、服务器不可达等)
|
||
debugPrint('🔐 [权限校验] ❌ DioException: ${e.type} - ${e.message}');
|
||
return false;
|
||
} catch (e) {
|
||
// 任何未知异常
|
||
debugPrint('🔐 [权限校验] ❌ 未知异常: $e');
|
||
return false;
|
||
}
|
||
}
|
||
}
|