login_view_model.dart 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import 'package:flutter/material.dart';
  2. import '../data/api_response.dart';
  3. import '../data/session/session_storage.dart';
  4. import '../services/login_service.dart';
  5. enum Status { uninitialized, authenticated, authenticating, unauthenticated }
  6. class LoginViewModel extends ChangeNotifier {
  7. Status _status = Status.uninitialized;
  8. Status get status => _status;
  9. bool hasErrors = false;
  10. Map<String, dynamic>? _errores = {};
  11. bool _obscureText = true;
  12. int? _idUsuario;
  13. Map<String, dynamic>? get errores => _errores;
  14. bool get obscureText => _obscureText;
  15. int? get idUsuario => _idUsuario;
  16. //List<String> _permisos = [];
  17. //List<String> get permisos => _permisos;
  18. String _nombre = "";
  19. String get nombre => _nombre;
  20. String _correo = "";
  21. String get correo => _correo;
  22. String _error = "";
  23. String get error => _error;
  24. Future login(String username, String password) async {
  25. try {
  26. ApiResponse apiResponse = await LoginService().logIn(username, password);
  27. _errores = {};
  28. if (apiResponse.isOk) {
  29. _idUsuario = apiResponse.detalle?['id'];
  30. String token = apiResponse.detalle?['token'];
  31. if (token.isNotEmpty) {
  32. SessionStorage().saveToken(apiResponse.detalle?['token']);
  33. SessionStorage().saveId(apiResponse.detalle?['id']);
  34. SessionStorage().saveCorreo(apiResponse.detalle!['correo']);
  35. SessionStorage().saveNombre(apiResponse.detalle!['nombre']);
  36. _status = Status.authenticated;
  37. notifyListeners();
  38. }
  39. }
  40. if (apiResponse.isError) {
  41. hasErrors = true;
  42. _errores = apiResponse.errores;
  43. _status = Status.unauthenticated;
  44. notifyListeners();
  45. }
  46. } catch (e) {
  47. _status = Status.unauthenticated;
  48. notifyListeners();
  49. }
  50. }
  51. void checkSession() async {
  52. var token = await SessionStorage().getToken();
  53. var id = await SessionStorage().getId();
  54. if (token != null && token.isNotEmpty) {
  55. _status = Status.authenticated;
  56. _idUsuario = id;
  57. } else {
  58. _status = Status.unauthenticated;
  59. }
  60. notifyListeners();
  61. }
  62. logOut() async {
  63. await SessionStorage().clearToken();
  64. _status = Status.unauthenticated;
  65. notifyListeners();
  66. }
  67. void showPassword() {
  68. _obscureText = !_obscureText;
  69. notifyListeners();
  70. }
  71. setValores() async {
  72. _nombre = (await SessionStorage().getNombre()).toString();
  73. _correo = (await SessionStorage().getCorreo()).toString();
  74. notifyListeners();
  75. }
  76. bool validarEmail(String email) =>
  77. RegExp(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$')
  78. .hasMatch(email.trim());
  79. }