Commit 863e6aca authored by Ester Alfonzo's avatar Ester Alfonzo

mejoras

parent 83ec685b
import 'dart:io';
import '../data/SharedPref.dart';
import 'SharedPref.dart';
class ConectionApi {
List<Cookie> cookies = [];
......
import 'package:firebase_auth/firebase_auth.dart';
/*import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
......@@ -110,3 +110,4 @@ class Authentication {
);
}
}
*/
\ No newline at end of file
class UnauthorizedException implements Exception {}
class NotFoundException implements Exception {
String message = "";
NotFoundException({required this.message});
}
class ServerException implements Exception {}
import 'package:ealu_flutter/core/api.dart';
import 'package:ealu_flutter/data/models/LoginModel.dart';
class LoginRemote {
import '../../core/apiResponses.dart';
class RemoteLogin {
Api api;
LoginRemote(this.api);
Future<LoginModel> requestloginUser(dynamic params, dynamic body) async {
RemoteLogin(this.api);
Future<LoginModel?> remoteloginUser(dynamic params, dynamic body) async {
var response = await api.post('', params, body);
if (response != null) {
return LoginModelFromJson(response.data);
} else {}
if (response.statusCode == 200) {
return LoginModel.fromJson(response.data);
} else {
if (response.statusCode == 401) {
throw UnauthorizedException();
} else if (response.statusCode == 404) {
throw NotFoundException(message: "xxxx");
} else {
throw ServerException();
}
}
}
return null;
}
}
......@@ -2,15 +2,15 @@ import 'dart:convert';
import '../../domain/entities/login.dart';
import 'UserModel.dart';
LoginModel LoginModelFromJson(String str) =>
LoginModel loginModelFromJson(String str) =>
LoginModel.fromJson(json.decode(str));
String LoginModelToJson(LoginModel data) => json.encode(data.toJson());
String loginModelToJson(LoginModel data) => json.encode(data.toJson());
class LoginModel extends Login {
bool logged;
dynamic csrf;
UserModel user;
UserModel userModel;
List<String> permissionList;
dynamic msg;
String appVersion;
......@@ -19,7 +19,7 @@ class LoginModel extends Login {
LoginModel({
required this.logged,
this.csrf,
required this.user,
required this.userModel,
required this.permissionList,
this.msg,
required this.appVersion,
......@@ -27,7 +27,7 @@ class LoginModel extends Login {
}) : super(
logged: logged,
csrf: csrf,
user: user,
user: userModel,
permissionList: permissionList,
msg: msg,
appVersion: appVersion,
......@@ -36,7 +36,7 @@ class LoginModel extends Login {
factory LoginModel.fromJson(Map<String, dynamic> json) => LoginModel(
logged: json["logged"],
csrf: json["csrf"],
user: UserModel.fromJson(json["user"]),
userModel: UserModel.fromJson(json["user"]),
permissionList: List<String>.from(json["permissionList"].map((x) => x)),
msg: json["msg"],
appVersion: json["appVersion"],
......@@ -46,7 +46,7 @@ class LoginModel extends Login {
Map<String, dynamic> toJson() => {
"logged": logged,
"csrf": csrf,
"user": user.toJson(),
"user": userModel.toJson(),
"permissionList": List<dynamic>.from(permissionList.map((x) => x)),
"msg": msg,
"appVersion": appVersion,
......
import '../../core/apiResponses.dart';
import '../../domain/entities/user.dart';
import '../../services/toastService.dart';
import '../datasources/login_remote.dart';
class AuthRepository {
final RemoteLogin remoteLogin;
//final LocalDataSource localDataSource;
AuthRepository({
required this.remoteLogin,
//required this.localDataSource,
});
@override
Future<User?> login(String email, String password) async {
try {
final loginModel = await remoteLogin.remoteloginUser(email, password);
final user = User.fromModel(loginModel!.userModel);
//await localDataSource.cacheAuth(Auth);
return user;
} on UnauthorizedException {
showToastError("No autorizado");
return null;
} on ServerException {
showToastError("Error de servidor");
return null;
} on Exception {
showToastError("Error desconocido'");
return null;
}
return null;
}
}
import 'package:equatable/equatable.dart';
import '../../data/models/UserModel.dart';
class User extends Equatable {
User({
required this.id,
......@@ -19,4 +21,14 @@ class User extends Equatable {
@override
List<Object> get props => [id, username, name];
factory User.fromModel(UserModel userModel) {
return User(
id: userModel.id,
name: userModel.name,
surname: userModel.surname,
nameAndSurname: userModel.nameAndSurname,
username: userModel.surname,
);
}
}
import '../../data/repositories/auth_repository.dart';
import '../entities/user.dart';
class LoginUseCase {
final AuthRepository authRepository;
LoginUseCase(this.authRepository);
Future<User?> login(String username, String password) {
return authRepository.login(username, password);
}
}
class LogoutUseCase {
final AuthRepository repository;
LogoutUseCase(this.repository);
/*Future<void> logout() {
return repository.logout();
}*/
}
import 'dart:io';
import 'package:bloc/bloc.dart';
import 'package:ealu_flutter/data/datasources/login_remote.dart';
import 'package:ealu_flutter/domain/usecases/authentication_case_use.dart';
import 'package:equatable/equatable.dart';
part 'login_event.dart';
part 'login_state.dart';
class LoginBloc extends Bloc<LoginEvent, LoginState> {
LoginBloc() : super(LoginInitial()) {
on<LogInRemote>((event, emit) async {
LoginUseCase authUseCase;
emit(LoginLoading());
try {
var log = await authUseCase.login(event.email, event.password);
if (log == null) {
emit(LoginError(""));
} else {
emit(LoginLoaded());
}
} catch (e) {
emit(LoginError(""));
}
});
on<LogOutRemote>((event, emit) {});
}
}
part of 'login_bloc.dart';
abstract class LoginEvent extends Equatable {
const LoginEvent();
@override
List<Object> get props => [];
}
class LogInRemote extends LoginEvent {
final String email;
final String password;
LogInRemote({required this.email, required this.password});
@override
List<Object> get props => [email, password];
}
class LogOutRemote extends LoginEvent {}
part of 'login_bloc.dart';
abstract class LoginState extends Equatable {
const LoginState();
@override
List<Object> get props => [];
}
class LoginInitial extends LoginState {}
class LoginLoading extends LoginState {}
class LoginLoaded extends LoginState {}
class LoginError extends LoginState {
final String error;
LoginError(this.error);
}
import 'dart:convert';
import 'package:etramite_flutter/clases/GoogleAuth.dart';
import 'package:etramite_flutter/clases/SharedPref.dart';
import 'package:etramite_flutter/screens/HomeScreen.dart';
import 'package:etramite_flutter/screens/SingUpScreen.dart';
import 'package:etramite_flutter/services/toastService.dart';
import 'package:etramite_flutter/widgets/OptionsGradient.dart';
import 'package:etramite_flutter/widgets/RecuperarPassword.dart';
import 'package:etramite_flutter/widgets/ButtonLoginWithGoogle.dart';
import 'package:flutter/material.dart';
import 'package:etramite_flutter/services/authService.dart' as apiResponse;
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../core/SharedPref.dart';
import '../../blocs/login/login_bloc.dart';
import '../services/loadingService.dart';
class LoginScreen extends StatefulWidget {
const LoginScreen({Key? key}) : super(key: key);
@override
_LoginScreenState createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
final TextEditingController _nameController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
bool _isObscure = true;
dynamic user;
@override
void initState() {
super.initState();
getDataUser();
}
_handleLoginDB(BuildContext context, usuario, pass) async {
var body = {'username': usuario, 'password': pass};
await showPresent('');
var _apiResponse = await apiResponse.getLoginDB(context, usuario, pass);
/*print('apiiii');
print(_apiResponse);*/
if (_apiResponse == null) {
await dismissPresent();
} else {
await sharedPrefs.save('user', usuario);
await sharedPrefs.save('passw', pass);
await sharedPrefs.save('login', 'yes');
//await sharedPrefs.save('usuario', jsonEncode(_apiResponse['user']));
await sharedPrefs.save('usuario', _apiResponse['user']['nameAndSurname']);
await dismissPresent();
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute<void>(
builder: (BuildContext context) => const HomeScreen(),
),
ModalRoute.withName('/home'),
);
}
}
getDataUser() {
if (sharedPrefs.containsKey('user') == true &&
sharedPrefs.containsKey('passw') == true) {
setState(() {
_nameController.text = sharedPrefs.read('user');
_passwordController.text = sharedPrefs.read('passw');
});
}
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: BlocProvider<LoginBloc>(
create: (context) => LoginBloc(),
child: ListView(
children: <Widget>[
Container(
alignment: Alignment.center,
padding: const EdgeInsets.only(top: 30, bottom: 30),
child: ClipRRect(
child: Image.asset(
'assets/e-tramite-logo.png',
width: MediaQuery.of(context).size.width / 2.5,
),
),
),
Center(
child: Container(
width: MediaQuery.of(context).size.width * 0.95,
decoration: BoxDecoration(
borderRadius: const BorderRadius.all(Radius.circular(5)),
color: Theme.of(context).cardColor,
),
child: Container(
padding: const EdgeInsets.only(
top: 20, bottom: 5, left: 10, right: 10),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const Text(
'Inicia sesión o regístrate para continuar',
style: TextStyle(fontSize: 14),
),
const SizedBox(
height: 20,
),
TextField(
controller: _nameController,
decoration: const InputDecoration(
//labelText: 'Usuario',
hintText: 'Usuario',
isDense: true,
prefixIcon: Icon(
Icons.person,
size: 22,
),
),
),
const SizedBox(
height: 20,
),
TextField(
obscureText: _isObscure,
controller: _passwordController,
decoration: InputDecoration(
prefixIcon: const Icon(
Icons.lock_sharp,
size: 22,
),
isDense: true,
suffixIcon: IconButton(
icon: Icon(
_isObscure
? Icons.visibility
: Icons.visibility_off,
size: 22,
),
onPressed: () => setState(
() {
_isObscure = !_isObscure;
},
),
),
hintText: 'Contraseña',
),
),
const SizedBox(
height: 20,
),
TextButton(
child: const Text(
'¿Olvidaste tu contraseña?',
),
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return buildDialogPage(context);
},
);
},
),
ElevatedButton(
child: const Text(
'INICIAR SESIÓN',
),
onPressed: () {
print(_nameController.text);
print(_passwordController.text);
if (_nameController.text != '' &&
_passwordController.text != '') {
_handleLoginDB(context, _nameController.text,
_passwordController.text);
} else {
showToastError('Complete todos los campos');
}
},
),
const SizedBox(
height: 15,
),
optionsGradient(context, 'O', 0.40),
const SizedBox(
height: 15,
),
FutureBuilder(
future: Authentication.initializeFirebase(context),
builder: (context, snapshot) {
if (snapshot.hasError) {
return const Text('Error de Inicialización');
} else if (snapshot.connectionState ==
ConnectionState.done) {
return GoogleSignInButton(
onGoogleButtomPressed: handleLoginGoogle,
contentText: 'Continúa con Google',
);
}
return CircularProgressIndicator(
strokeWidth: 2,
backgroundColor: Colors.white,
valueColor: AlwaysStoppedAnimation<Color>(
(Theme.of(context).primaryColor),
),
);
},
),
Row(
children: <Widget>[
const Text(
'¿No tienes ninguna cuenta?',
),
TextButton(
child: const Text(
'Regístrate',
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const SingUpScreen(),
),
);
},
)
],
mainAxisAlignment: MainAxisAlignment.center,
),
],
),
),
),
),
const SizedBox(
height: 12,
)
],
),
),
),
);
}
}
......@@ -152,6 +152,14 @@ packages:
description: flutter
source: sdk
version: "0.0.0"
fluttertoast:
dependency: "direct main"
description:
name: fluttertoast
sha256: "2f9c4d3f4836421f7067a28f8939814597b27614e021da9d63e5d3fb6e212d25"
url: "https://pub.dev"
source: hosted
version: "8.2.1"
http_parser:
dependency: transitive
description:
......
name: ealu_flutter
description: A new Flutter project.
# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 1.0.0+1
environment:
sdk: '>=2.19.2 <3.0.0'
# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
flutter_bloc: ^8.1.2
intl: ^0.18.0
......@@ -44,56 +21,16 @@ dependencies:
cookie_jar: ^4.0.1
dio: ^5.1.1
dio_cookie_manager: ^3.0.0
fluttertoast: ^8.2.1
dev_dependencies:
flutter_test:
sdk: flutter
# The "flutter_lints" package below contains a set of recommended lints to
# encourage good coding practices. The lint set provided by the package is
# activated in the `analysis_options.yaml` file located at the root of your
# package. See that file for information about deactivating specific lint
# rules and activating additional ones.
flutter_lints: ^2.0.0
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter packages.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment