first commit
This commit is contained in:
@@ -0,0 +1,103 @@
|
||||
class AuthSessionModel {
|
||||
final String accessToken;
|
||||
final String? refreshToken;
|
||||
final int? expires;
|
||||
final String userId;
|
||||
final String firstName;
|
||||
final String lastName;
|
||||
final String email;
|
||||
final String? roleName;
|
||||
|
||||
const AuthSessionModel({
|
||||
required this.accessToken,
|
||||
this.refreshToken,
|
||||
this.expires,
|
||||
required this.userId,
|
||||
required this.firstName,
|
||||
required this.lastName,
|
||||
required this.email,
|
||||
this.roleName,
|
||||
});
|
||||
|
||||
String get fullName {
|
||||
final name = '$firstName $lastName'.trim();
|
||||
return name.isNotEmpty ? name : 'Dr. Luis A. Castro Sosa';
|
||||
}
|
||||
|
||||
/// Indica si el usuario actual tiene rol de Secretaria, Asistente o Recepción
|
||||
bool get isSecretary {
|
||||
final normalized = (roleName ?? '').trim().toLowerCase();
|
||||
return normalized.contains('secretari') ||
|
||||
normalized.contains('asistent') ||
|
||||
normalized.contains('recepc');
|
||||
}
|
||||
|
||||
/// Indica si el usuario actual es Doctor o Administrador
|
||||
bool get isDoctorOrAdmin => !isSecretary;
|
||||
|
||||
AuthSessionModel copyWith({
|
||||
String? accessToken,
|
||||
String? refreshToken,
|
||||
int? expires,
|
||||
String? userId,
|
||||
String? firstName,
|
||||
String? lastName,
|
||||
String? email,
|
||||
String? roleName,
|
||||
}) {
|
||||
return AuthSessionModel(
|
||||
accessToken: accessToken ?? this.accessToken,
|
||||
refreshToken: refreshToken ?? this.refreshToken,
|
||||
expires: expires ?? this.expires,
|
||||
userId: userId ?? this.userId,
|
||||
firstName: firstName ?? this.firstName,
|
||||
lastName: lastName ?? this.lastName,
|
||||
email: email ?? this.email,
|
||||
roleName: roleName ?? this.roleName,
|
||||
);
|
||||
}
|
||||
|
||||
factory AuthSessionModel.fromLoginAndUser({
|
||||
required Map<String, dynamic> loginData,
|
||||
required Map<String, dynamic> userData,
|
||||
}) {
|
||||
return AuthSessionModel(
|
||||
accessToken: loginData['access_token'] as String? ?? '',
|
||||
refreshToken: loginData['refresh_token'] as String?,
|
||||
expires: loginData['expires'] as int?,
|
||||
userId: userData['id'] as String? ?? '',
|
||||
firstName: userData['first_name'] as String? ?? '',
|
||||
lastName: userData['last_name'] as String? ?? '',
|
||||
email: userData['email'] as String? ?? '',
|
||||
roleName: (userData['role'] is Map)
|
||||
? userData['role']['name'] as String?
|
||||
: userData['role']?.toString(),
|
||||
);
|
||||
}
|
||||
|
||||
factory AuthSessionModel.fromJson(Map<String, dynamic> json) {
|
||||
return AuthSessionModel(
|
||||
accessToken: json['access_token'] as String? ?? '',
|
||||
refreshToken: json['refresh_token'] as String?,
|
||||
expires: json['expires'] as int?,
|
||||
userId: json['user_id'] as String? ?? '',
|
||||
firstName: json['first_name'] as String? ?? '',
|
||||
lastName: json['last_name'] as String? ?? '',
|
||||
email: json['email'] as String? ?? '',
|
||||
roleName: json['role_name'] as String?,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'access_token': accessToken,
|
||||
'refresh_token': refreshToken,
|
||||
'expires': expires,
|
||||
'user_id': userId,
|
||||
'first_name': firstName,
|
||||
'last_name': lastName,
|
||||
'email': email,
|
||||
'role_name': roleName,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
import 'dart:convert';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import '../../../../core/network/api_client.dart';
|
||||
import '../models/auth_session_model.dart';
|
||||
|
||||
class AuthService {
|
||||
static const String _sessionKey = 'hidalyx_med_auth_session';
|
||||
|
||||
final ApiClient apiClient;
|
||||
|
||||
AuthService({ApiClient? client}) : apiClient = client ?? ApiClient() {
|
||||
apiClient.onTokenRefresh = () async {
|
||||
final session = await refreshToken();
|
||||
return session?.accessToken;
|
||||
};
|
||||
}
|
||||
|
||||
Future<AuthSessionModel?> login({
|
||||
required String email,
|
||||
required String password,
|
||||
}) async {
|
||||
try {
|
||||
// 0. Limpiar cualquier token previo para garantizar petición limpia
|
||||
apiClient.clearAuthToken();
|
||||
|
||||
// 1. Autenticación en Directus
|
||||
final loginResponse = await apiClient.dio.post(
|
||||
'/auth/login',
|
||||
data: {
|
||||
'email': email.trim(),
|
||||
'password': password,
|
||||
},
|
||||
);
|
||||
|
||||
if (loginResponse.statusCode == 200 && loginResponse.data != null) {
|
||||
final loginData = loginResponse.data['data'] as Map<String, dynamic>;
|
||||
final token = loginData['access_token'] as String;
|
||||
|
||||
// 2. Establecer token para futuras peticiones
|
||||
apiClient.setAuthToken(token);
|
||||
|
||||
// 3. Consultar datos reales del usuario y su rol en Directus de forma segura
|
||||
Map<String, dynamic> userData = {
|
||||
'id': '',
|
||||
'first_name': email.contains('castro') ? 'Luis A.' : 'Usuario',
|
||||
'last_name': email.contains('castro') ? 'Castro Sosa' : '',
|
||||
'email': email,
|
||||
};
|
||||
|
||||
try {
|
||||
final userResponse = await apiClient.dio.get(
|
||||
'/users/me?fields=*.*,role.*',
|
||||
options: Options(headers: {'Authorization': 'Bearer $token'}),
|
||||
);
|
||||
if (userResponse.data != null && userResponse.data['data'] != null) {
|
||||
userData = userResponse.data['data'] as Map<String, dynamic>;
|
||||
}
|
||||
} catch (_) {
|
||||
try {
|
||||
final basicRes = await apiClient.dio.get(
|
||||
'/users/me',
|
||||
options: Options(headers: {'Authorization': 'Bearer $token'}),
|
||||
);
|
||||
if (basicRes.data != null && basicRes.data['data'] != null) {
|
||||
userData = basicRes.data['data'] as Map<String, dynamic>;
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
// 4. Crear modelo de sesión
|
||||
final session = AuthSessionModel.fromLoginAndUser(
|
||||
loginData: loginData,
|
||||
userData: userData,
|
||||
);
|
||||
|
||||
// 5. Guardar en SharedPreferences
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_sessionKey, jsonEncode(session.toJson()));
|
||||
|
||||
return session;
|
||||
}
|
||||
return null;
|
||||
} on DioException catch (e) {
|
||||
final errorMsg = e.response?.data?['errors']?[0]?['message'] ?? 'Credenciales incorrectas';
|
||||
throw Exception(errorMsg);
|
||||
} catch (e) {
|
||||
throw Exception('Error al iniciar sesión: $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// Refresca inmediatamente el token de acceso utilizando el endpoint POST /auth/refresh de Directus
|
||||
Future<AuthSessionModel?> refreshToken() async {
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final sessionJson = prefs.getString(_sessionKey);
|
||||
if (sessionJson == null) return null;
|
||||
|
||||
final currentSession = AuthSessionModel.fromJson(
|
||||
jsonDecode(sessionJson) as Map<String, dynamic>,
|
||||
);
|
||||
|
||||
final rToken = currentSession.refreshToken;
|
||||
if (rToken == null || rToken.isEmpty) {
|
||||
await logout();
|
||||
return null;
|
||||
}
|
||||
|
||||
// Cliente Dio dedicado para la petición de refresh (evita re-interceptar en caso de fallo)
|
||||
final refreshDio = Dio(
|
||||
BaseOptions(
|
||||
baseUrl: ApiClient.baseUrl,
|
||||
connectTimeout: const Duration(seconds: 15),
|
||||
receiveTimeout: const Duration(seconds: 15),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
),
|
||||
);
|
||||
|
||||
final refreshResponse = await refreshDio.post(
|
||||
'/auth/refresh',
|
||||
data: {
|
||||
'refresh_token': rToken,
|
||||
'mode': 'json',
|
||||
},
|
||||
);
|
||||
|
||||
if (refreshResponse.statusCode == 200 && refreshResponse.data != null) {
|
||||
final data = refreshResponse.data['data'] as Map<String, dynamic>;
|
||||
final newAccessToken = data['access_token'] as String;
|
||||
final newRefreshToken = (data['refresh_token'] as String?) ?? rToken;
|
||||
final expires = data['expires'] as int?;
|
||||
|
||||
final updatedSession = currentSession.copyWith(
|
||||
accessToken: newAccessToken,
|
||||
refreshToken: newRefreshToken,
|
||||
expires: expires,
|
||||
);
|
||||
|
||||
await prefs.setString(_sessionKey, jsonEncode(updatedSession.toJson()));
|
||||
apiClient.setAuthToken(newAccessToken);
|
||||
return updatedSession;
|
||||
}
|
||||
|
||||
await logout();
|
||||
return null;
|
||||
} catch (_) {
|
||||
await logout();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<AuthSessionModel?> loadSavedSession() async {
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final sessionJson = prefs.getString(_sessionKey);
|
||||
if (sessionJson != null) {
|
||||
final session = AuthSessionModel.fromJson(
|
||||
jsonDecode(sessionJson) as Map<String, dynamic>,
|
||||
);
|
||||
|
||||
if (session.accessToken.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Verificamos de inmediato si el token actual sigue activo o si ya expiró
|
||||
final verifyDio = Dio(
|
||||
BaseOptions(
|
||||
baseUrl: ApiClient.baseUrl,
|
||||
connectTimeout: const Duration(seconds: 6),
|
||||
receiveTimeout: const Duration(seconds: 6),
|
||||
headers: {
|
||||
'Authorization': 'Bearer ${session.accessToken}',
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
try {
|
||||
final meRes = await verifyDio.get('/users/me?fields=id');
|
||||
if (meRes.statusCode == 200) {
|
||||
apiClient.setAuthToken(session.accessToken);
|
||||
return session;
|
||||
}
|
||||
} catch (_) {
|
||||
// El token expiró: usar el refresh_token inmediatamente para renovarlo sin bloquear al doctor
|
||||
if (session.refreshToken != null && session.refreshToken!.isNotEmpty) {
|
||||
final refreshed = await refreshToken();
|
||||
if (refreshed != null) {
|
||||
apiClient.setAuthToken(refreshed.accessToken);
|
||||
return refreshed;
|
||||
}
|
||||
}
|
||||
await logout();
|
||||
return null;
|
||||
}
|
||||
|
||||
apiClient.setAuthToken(session.accessToken);
|
||||
return session;
|
||||
}
|
||||
return null;
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> logout() async {
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final sessionJson = prefs.getString(_sessionKey);
|
||||
|
||||
// Limpiar inmediatamente el estado local y los headers para evitar fugas de token o loops de refresh
|
||||
await prefs.remove(_sessionKey);
|
||||
apiClient.clearAuthToken();
|
||||
|
||||
if (sessionJson != null) {
|
||||
final session = AuthSessionModel.fromJson(
|
||||
jsonDecode(sessionJson) as Map<String, dynamic>,
|
||||
);
|
||||
if (session.refreshToken != null && session.refreshToken!.isNotEmpty) {
|
||||
try {
|
||||
final logoutDio = Dio(
|
||||
BaseOptions(
|
||||
baseUrl: ApiClient.baseUrl,
|
||||
connectTimeout: const Duration(seconds: 5),
|
||||
receiveTimeout: const Duration(seconds: 5),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
),
|
||||
);
|
||||
await logoutDio.post(
|
||||
'/auth/logout',
|
||||
data: {'refresh_token': session.refreshToken},
|
||||
);
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
} catch (_) {
|
||||
apiClient.clearAuthToken();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import 'package:mobx/mobx.dart';
|
||||
import '../../data/models/auth_session_model.dart';
|
||||
import '../../data/services/auth_service.dart';
|
||||
|
||||
part 'auth_store.g.dart';
|
||||
|
||||
// ignore: library_private_types_in_public_api
|
||||
class AuthStore = _AuthStoreBase with _$AuthStore;
|
||||
|
||||
abstract class _AuthStoreBase with Store {
|
||||
final AuthService authService;
|
||||
|
||||
_AuthStoreBase({AuthService? service})
|
||||
: authService = service ?? AuthService();
|
||||
|
||||
@observable
|
||||
bool isLoading = false;
|
||||
|
||||
@observable
|
||||
bool isPasswordVisible = false;
|
||||
|
||||
@observable
|
||||
AuthSessionModel? currentSession;
|
||||
|
||||
@observable
|
||||
String? errorMessage;
|
||||
|
||||
@computed
|
||||
bool get isAuthenticated => currentSession != null;
|
||||
|
||||
@action
|
||||
void togglePasswordVisibility() {
|
||||
isPasswordVisible = !isPasswordVisible;
|
||||
}
|
||||
|
||||
@action
|
||||
Future<bool> login({required String email, required String password}) async {
|
||||
isLoading = true;
|
||||
errorMessage = null;
|
||||
currentSession = null;
|
||||
try {
|
||||
final session = await authService.login(email: email, password: password);
|
||||
if (session != null) {
|
||||
currentSession = session;
|
||||
return true;
|
||||
}
|
||||
errorMessage = 'No se pudo iniciar sesión. Verifique sus credenciales.';
|
||||
return false;
|
||||
} catch (e) {
|
||||
errorMessage = e.toString().replaceAll('Exception: ', '');
|
||||
return false;
|
||||
} finally {
|
||||
isLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
@action
|
||||
Future<void> checkInitialSession() async {
|
||||
isLoading = true;
|
||||
try {
|
||||
final session = await authService.loadSavedSession();
|
||||
currentSession = session;
|
||||
} catch (_) {
|
||||
currentSession = null;
|
||||
} finally {
|
||||
isLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
@action
|
||||
Future<bool> refreshToken() async {
|
||||
isLoading = true;
|
||||
try {
|
||||
final session = await authService.refreshToken();
|
||||
if (session != null) {
|
||||
currentSession = session;
|
||||
return true;
|
||||
}
|
||||
currentSession = null;
|
||||
return false;
|
||||
} catch (_) {
|
||||
currentSession = null;
|
||||
return false;
|
||||
} finally {
|
||||
isLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
@action
|
||||
Future<void> logout() async {
|
||||
isLoading = true;
|
||||
errorMessage = null;
|
||||
try {
|
||||
await authService.logout();
|
||||
currentSession = null;
|
||||
} finally {
|
||||
isLoading = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'auth_store.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// StoreGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// ignore_for_file: non_constant_identifier_names, unnecessary_brace_in_string_interps, unnecessary_lambdas, prefer_expression_function_bodies, lines_longer_than_80_chars, avoid_as, avoid_annotating_with_dynamic, no_leading_underscores_for_local_identifiers
|
||||
|
||||
mixin _$AuthStore on _AuthStoreBase, Store {
|
||||
Computed<bool>? _$isAuthenticatedComputed;
|
||||
|
||||
@override
|
||||
bool get isAuthenticated => (_$isAuthenticatedComputed ??= Computed<bool>(
|
||||
() => super.isAuthenticated,
|
||||
name: '_AuthStoreBase.isAuthenticated',
|
||||
)).value;
|
||||
|
||||
late final _$isLoadingAtom = Atom(
|
||||
name: '_AuthStoreBase.isLoading',
|
||||
context: context,
|
||||
);
|
||||
|
||||
@override
|
||||
bool get isLoading {
|
||||
_$isLoadingAtom.reportRead();
|
||||
return super.isLoading;
|
||||
}
|
||||
|
||||
@override
|
||||
set isLoading(bool value) {
|
||||
_$isLoadingAtom.reportWrite(value, super.isLoading, () {
|
||||
super.isLoading = value;
|
||||
});
|
||||
}
|
||||
|
||||
late final _$isPasswordVisibleAtom = Atom(
|
||||
name: '_AuthStoreBase.isPasswordVisible',
|
||||
context: context,
|
||||
);
|
||||
|
||||
@override
|
||||
bool get isPasswordVisible {
|
||||
_$isPasswordVisibleAtom.reportRead();
|
||||
return super.isPasswordVisible;
|
||||
}
|
||||
|
||||
@override
|
||||
set isPasswordVisible(bool value) {
|
||||
_$isPasswordVisibleAtom.reportWrite(value, super.isPasswordVisible, () {
|
||||
super.isPasswordVisible = value;
|
||||
});
|
||||
}
|
||||
|
||||
late final _$currentSessionAtom = Atom(
|
||||
name: '_AuthStoreBase.currentSession',
|
||||
context: context,
|
||||
);
|
||||
|
||||
@override
|
||||
AuthSessionModel? get currentSession {
|
||||
_$currentSessionAtom.reportRead();
|
||||
return super.currentSession;
|
||||
}
|
||||
|
||||
@override
|
||||
set currentSession(AuthSessionModel? value) {
|
||||
_$currentSessionAtom.reportWrite(value, super.currentSession, () {
|
||||
super.currentSession = value;
|
||||
});
|
||||
}
|
||||
|
||||
late final _$errorMessageAtom = Atom(
|
||||
name: '_AuthStoreBase.errorMessage',
|
||||
context: context,
|
||||
);
|
||||
|
||||
@override
|
||||
String? get errorMessage {
|
||||
_$errorMessageAtom.reportRead();
|
||||
return super.errorMessage;
|
||||
}
|
||||
|
||||
@override
|
||||
set errorMessage(String? value) {
|
||||
_$errorMessageAtom.reportWrite(value, super.errorMessage, () {
|
||||
super.errorMessage = value;
|
||||
});
|
||||
}
|
||||
|
||||
late final _$loginAsyncAction = AsyncAction(
|
||||
'_AuthStoreBase.login',
|
||||
context: context,
|
||||
);
|
||||
|
||||
@override
|
||||
Future<bool> login({required String email, required String password}) {
|
||||
return _$loginAsyncAction.run(
|
||||
() => super.login(email: email, password: password),
|
||||
);
|
||||
}
|
||||
|
||||
late final _$checkInitialSessionAsyncAction = AsyncAction(
|
||||
'_AuthStoreBase.checkInitialSession',
|
||||
context: context,
|
||||
);
|
||||
|
||||
@override
|
||||
Future<void> checkInitialSession() {
|
||||
return _$checkInitialSessionAsyncAction.run(
|
||||
() => super.checkInitialSession(),
|
||||
);
|
||||
}
|
||||
|
||||
late final _$refreshTokenAsyncAction = AsyncAction(
|
||||
'_AuthStoreBase.refreshToken',
|
||||
context: context,
|
||||
);
|
||||
|
||||
@override
|
||||
Future<bool> refreshToken() {
|
||||
return _$refreshTokenAsyncAction.run(() => super.refreshToken());
|
||||
}
|
||||
|
||||
late final _$logoutAsyncAction = AsyncAction(
|
||||
'_AuthStoreBase.logout',
|
||||
context: context,
|
||||
);
|
||||
|
||||
@override
|
||||
Future<void> logout() {
|
||||
return _$logoutAsyncAction.run(() => super.logout());
|
||||
}
|
||||
|
||||
late final _$_AuthStoreBaseActionController = ActionController(
|
||||
name: '_AuthStoreBase',
|
||||
context: context,
|
||||
);
|
||||
|
||||
@override
|
||||
void togglePasswordVisibility() {
|
||||
final _$actionInfo = _$_AuthStoreBaseActionController.startAction(
|
||||
name: '_AuthStoreBase.togglePasswordVisibility',
|
||||
);
|
||||
try {
|
||||
return super.togglePasswordVisibility();
|
||||
} finally {
|
||||
_$_AuthStoreBaseActionController.endAction(_$actionInfo);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return '''
|
||||
isLoading: ${isLoading},
|
||||
isPasswordVisible: ${isPasswordVisible},
|
||||
currentSession: ${currentSession},
|
||||
errorMessage: ${errorMessage},
|
||||
isAuthenticated: ${isAuthenticated}
|
||||
''';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import '../../../../core/theme/app_colors.dart';
|
||||
import '../store/auth_store.dart';
|
||||
import '../widgets/login_form_widget.dart';
|
||||
import '../widgets/login_header_widget.dart';
|
||||
|
||||
class LoginView extends StatefulWidget {
|
||||
final AuthStore? store;
|
||||
|
||||
const LoginView({super.key, this.store});
|
||||
|
||||
@override
|
||||
State<LoginView> createState() => _LoginViewState();
|
||||
}
|
||||
|
||||
class _LoginViewState extends State<LoginView> {
|
||||
late final AuthStore _authStore;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_authStore = widget.store ?? AuthStore();
|
||||
}
|
||||
|
||||
void _onSuccess() {
|
||||
context.go('/');
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: AppColors.background,
|
||||
body: SafeArea(
|
||||
child: Center(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 32),
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 440),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(32),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
border: Border.all(color: AppColors.border),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: AppColors.primary.withValues(alpha: 0.04),
|
||||
blurRadius: 24,
|
||||
offset: const Offset(0, 8),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const LoginHeaderWidget(),
|
||||
const SizedBox(height: 28),
|
||||
LoginFormWidget(
|
||||
store: _authStore,
|
||||
onLoginSuccess: _onSuccess,
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
const Text(
|
||||
'Sistema protegido · Exclusivo Consultorio Dr. Luis Castro',
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
color: AppColors.textMuted,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_form_builder/flutter_form_builder.dart';
|
||||
import 'package:flutter_mobx/flutter_mobx.dart';
|
||||
import 'package:form_builder_validators/form_builder_validators.dart';
|
||||
import '../../../../core/theme/app_colors.dart';
|
||||
import '../store/auth_store.dart';
|
||||
|
||||
class LoginFormWidget extends StatefulWidget {
|
||||
final AuthStore store;
|
||||
final VoidCallback onLoginSuccess;
|
||||
|
||||
const LoginFormWidget({
|
||||
super.key,
|
||||
required this.store,
|
||||
required this.onLoginSuccess,
|
||||
});
|
||||
|
||||
@override
|
||||
State<LoginFormWidget> createState() => _LoginFormWidgetState();
|
||||
}
|
||||
|
||||
class _LoginFormWidgetState extends State<LoginFormWidget> {
|
||||
final _formKey = GlobalKey<FormBuilderState>();
|
||||
|
||||
Future<void> _submit() async {
|
||||
if (_formKey.currentState?.saveAndValidate() ?? false) {
|
||||
final values = _formKey.currentState!.value;
|
||||
final email = values['email'] as String;
|
||||
final password = values['password'] as String;
|
||||
|
||||
final success = await widget.store.login(
|
||||
email: email,
|
||||
password: password,
|
||||
);
|
||||
|
||||
if (success && mounted) {
|
||||
widget.onLoginSuccess();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Observer(
|
||||
builder: (_) {
|
||||
return FormBuilder(
|
||||
key: _formKey,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
// Mensaje de Error si existe
|
||||
if (widget.store.errorMessage != null) ...[
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.error.withValues(alpha: 0.1),
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
border: Border.all(color: AppColors.error.withValues(alpha: 0.3)),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.error_outline_rounded, color: AppColors.error, size: 20),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Text(
|
||||
widget.store.errorMessage!,
|
||||
style: const TextStyle(
|
||||
color: AppColors.error,
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
|
||||
// Campo Email
|
||||
const Text(
|
||||
'Correo Electrónico',
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: AppColors.textPrimary,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
FormBuilderTextField(
|
||||
name: 'email',
|
||||
initialValue: '[email protected]',
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
textInputAction: TextInputAction.next,
|
||||
decoration: const InputDecoration(
|
||||
hintText: '[email protected]',
|
||||
prefixIcon: Icon(Icons.mail_outline_rounded, color: AppColors.textMuted, size: 20),
|
||||
),
|
||||
validator: FormBuilderValidators.compose([
|
||||
FormBuilderValidators.required(errorText: 'El correo electrónico es requerido'),
|
||||
FormBuilderValidators.email(errorText: 'Ingrese un correo electrónico válido'),
|
||||
]),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Campo Contraseña
|
||||
const Text(
|
||||
'Contraseña',
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: AppColors.textPrimary,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
FormBuilderTextField(
|
||||
name: 'password',
|
||||
initialValue: 'LUIS',
|
||||
obscureText: !widget.store.isPasswordVisible,
|
||||
textInputAction: TextInputAction.done,
|
||||
onSubmitted: (_) => _submit(),
|
||||
decoration: InputDecoration(
|
||||
hintText: 'Ingrese su contraseña',
|
||||
prefixIcon: const Icon(Icons.lock_outline_rounded, color: AppColors.textMuted, size: 20),
|
||||
suffixIcon: IconButton(
|
||||
icon: Icon(
|
||||
widget.store.isPasswordVisible
|
||||
? Icons.visibility_off_outlined
|
||||
: Icons.visibility_outlined,
|
||||
color: AppColors.textMuted,
|
||||
size: 20,
|
||||
),
|
||||
onPressed: widget.store.togglePasswordVisibility,
|
||||
),
|
||||
),
|
||||
validator: FormBuilderValidators.compose([
|
||||
FormBuilderValidators.required(errorText: 'La contraseña es requerida'),
|
||||
]),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Botón de Inicio de Sesión
|
||||
ElevatedButton(
|
||||
onPressed: widget.store.isLoading ? null : _submit,
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: AppColors.primary,
|
||||
foregroundColor: Colors.white,
|
||||
padding: const EdgeInsets.symmetric(vertical: 16),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
elevation: 2,
|
||||
),
|
||||
child: widget.store.isLoading
|
||||
? const SizedBox(
|
||||
height: 20,
|
||||
width: 20,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
|
||||
),
|
||||
)
|
||||
: const Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(Icons.login_rounded, size: 18),
|
||||
SizedBox(width: 8),
|
||||
Text(
|
||||
'Ingresar al Consultorio',
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_svg/flutter_svg.dart';
|
||||
import '../../../../core/theme/app_colors.dart';
|
||||
|
||||
class LoginHeaderWidget extends StatelessWidget {
|
||||
const LoginHeaderWidget({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
// Logo de Hidalyx
|
||||
SvgPicture.asset(
|
||||
'assets/images/hidalyx_logo_blue.svg',
|
||||
height: 48,
|
||||
fit: BoxFit.contain,
|
||||
),
|
||||
const SizedBox(height: 18),
|
||||
const Text(
|
||||
'Hidalyx Med',
|
||||
style: TextStyle(
|
||||
fontSize: 26,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: AppColors.textPrimary,
|
||||
letterSpacing: -0.5,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
const Text(
|
||||
'Portal de Gestión Clínica · Dr. Luis A. Castro Sosa',
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
color: AppColors.textSecondary,
|
||||
fontWeight: FontWeight.w400,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user