Skip to content

Commit

Permalink
Se añadido la Authentication, registro desde el lado back-end y obtie…
Browse files Browse the repository at this point in the history
…ne el nombre del usuario en la ventana del home
  • Loading branch information
DomingoMG committed Sep 8, 2020
1 parent 9556f41 commit a96075f
Show file tree
Hide file tree
Showing 16 changed files with 377 additions and 45 deletions.
2 changes: 1 addition & 1 deletion android/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ android {
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.example.chatapp"
minSdkVersion 16
minSdkVersion 18
targetSdkVersion 28
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
Expand Down
1 change: 1 addition & 0 deletions ios/Flutter/Debug.xcconfig
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"
#include "Generated.xcconfig"
1 change: 1 addition & 0 deletions ios/Flutter/Release.xcconfig
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"
#include "Generated.xcconfig"
41 changes: 41 additions & 0 deletions ios/Podfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Uncomment this line to define a global platform for your project
# platform :ios, '9.0'

# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'

project 'Runner', {
'Debug' => :debug,
'Profile' => :release,
'Release' => :release,
}

def flutter_root
generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
unless File.exist?(generated_xcode_build_settings_path)
raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
end

File.foreach(generated_xcode_build_settings_path) do |line|
matches = line.match(/FLUTTER_ROOT\=(.*)/)
return matches[1].strip if matches
end
raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
end

require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)

flutter_ios_podfile_setup

target 'Runner' do
use_frameworks!
use_modular_headers!

flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end

post_install do |installer|
installer.pods_project.targets.each do |target|
flutter_additional_ios_build_settings(target)
end
end
17 changes: 12 additions & 5 deletions lib/main.dart
Original file line number Diff line number Diff line change
@@ -1,16 +1,23 @@
import 'package:chatapp/src/routes/routes.dart';
import 'package:chatapp/src/services/auth.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Chat App',
routes: appRoutes,
initialRoute: 'users',
return MultiProvider(
providers: [
ChangeNotifierProvider(create: ( _ ) => AuthService() )
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Chat App',
routes: appRoutes,
initialRoute: 'loading',
),
);
}
}
7 changes: 7 additions & 0 deletions lib/src/global/enviroment.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@

import 'dart:io';

class Environment {
static String apiURL = 'http://192.168.0.22:3000/api';
static String socketUrl = 'http://192.168.0.22:3000';
}
37 changes: 37 additions & 0 deletions lib/src/helpers/showAlert.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';


Future<bool> showSimpleAlert( BuildContext context, String title, String subtitle ){
if( Platform.isAndroid ){
return showDialog(
context: context,
builder: ( _ ) => AlertDialog(
title: Text('$title'),
content: Text('$subtitle'),
actions: [
MaterialButton(
child: Text('Aceptar'),
onPressed: () => Navigator.of(context).pop(),
)
],
)
);
} else {
return showDialog(
context: context,
builder: ( _ ) => CupertinoAlertDialog(
title: Text('$title'),
content: Text('$subtitle'),
actions: [
CupertinoDialogAction(
child: Text('Aceptar'),
onPressed: () => Navigator.of(context).pop(),
)
],
)
);
}
}
29 changes: 29 additions & 0 deletions lib/src/models/loginResponse.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import 'dart:convert';
import 'package:chatapp/src/models/user.dart';

LoginResponse loginResponseFromJson(String str) => LoginResponse.fromJson(json.decode(str));
String loginResponseToJson(LoginResponse data) => json.encode(data.toJson());

class LoginResponse {
LoginResponse({
this.ok,
this.user,
this.token,
});

bool ok;
User user;
String token;

factory LoginResponse.fromJson(Map<String, dynamic> json) => LoginResponse(
ok: json["ok"],
user: User.fromJson(json["user"]),
token: json["token"],
);

Map<String, dynamic> toJson() => {
"ok": ok,
"user": user.toJson(),
"token": token,
};
}
33 changes: 21 additions & 12 deletions lib/src/models/user.dart
Original file line number Diff line number Diff line change
@@ -1,18 +1,27 @@

class User {

final bool isOnline;
final String email;
final String name;
final String uid;

User({
this.isOnline,
this.email,
this.name,
this.uid
this.isOnline,
this.name,
this.email,
this.uid,
});


bool isOnline;
String name;
String email;
String uid;

factory User.fromJson(Map<String, dynamic> json) => User(
isOnline: json["isOnline"],
name: json["name"],
email: json["email"],
uid: json["uid"]
);

Map<String, dynamic> toJson() => {
"isOnline": isOnline,
"name": name,
"email": email,
"uid": uid
};
}
35 changes: 34 additions & 1 deletion lib/src/pages/loading.dart
Original file line number Diff line number Diff line change
@@ -1,10 +1,43 @@
import 'package:chatapp/src/pages/login.dart';
import 'package:chatapp/src/pages/users.dart';
import 'package:chatapp/src/services/auth.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class LoadingPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(

body: FutureBuilder<Object>(
future: checkLoginState( context ),
builder: (context, snapshot) {
return Center(
child: CircularProgressIndicator()
);
}
),
);
}

Future checkLoginState( BuildContext context ) async {
final AuthService authService = Provider.of<AuthService>(context, listen: false);
final isValidateToken = await authService.isLoggedIn();

if( isValidateToken ){
// TODO: Conectar al socket service
Navigator.of(context).pushReplacement(
PageRouteBuilder(
pageBuilder: ( _, __, ___ ) => UsersPage(),
transitionDuration: Duration(milliseconds: 0)
)
);
} else {
Navigator.of(context).pushReplacement(
PageRouteBuilder(
pageBuilder: ( _, __, ___ ) => LoginPage(),
transitionDuration: Duration(milliseconds: 0)
)
);
}
}
}
19 changes: 15 additions & 4 deletions lib/src/pages/login.dart
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import 'package:chatapp/src/helpers/showAlert.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:chatapp/src/widgets/customInput.dart';
import 'package:chatapp/src/widgets/customButton.dart';
import 'package:chatapp/src/widgets/labels.dart';
import 'package:chatapp/src/widgets/logo.dart';
import 'package:chatapp/src/services/auth.dart';

class LoginPage extends StatelessWidget {
@override
Expand Down Expand Up @@ -47,6 +50,7 @@ class __FormState extends State<_Form> {

@override
Widget build(BuildContext context) {
final AuthService authServices = Provider.of<AuthService>( context );
return Container(
margin: EdgeInsets.only(top: 40),
padding: EdgeInsets.symmetric(horizontal: 50),
Expand All @@ -66,10 +70,17 @@ class __FormState extends State<_Form> {
),
CustomButton(
title: 'Iniciar Sesión',
callback: (){
print( _txtEmail.text );
print( _txtPassword.text );
},
callback: authServices.isAuthNow ? null : () async {
FocusScope.of(context).unfocus();
final loginSuccess = await authServices.login( _txtEmail.text.trim(), _txtPassword.text );
if( loginSuccess ){
// TODO: Conectar a nuestro socket server
Navigator.of(context).pushReplacementNamed('users');
// TODO: Navegar a otra pantalla
} else {
showSimpleAlert(context, 'Login incorrecto', 'Email o contraseña incorrecto.');
}
}
)
],
),
Expand Down
14 changes: 11 additions & 3 deletions lib/src/pages/register.dart
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import 'package:chatapp/src/helpers/showAlert.dart';
import 'package:chatapp/src/services/auth.dart';
import 'package:flutter/material.dart';
import 'package:chatapp/src/widgets/customInput.dart';
import 'package:chatapp/src/widgets/customButton.dart';
import 'package:chatapp/src/widgets/labels.dart';
import 'package:chatapp/src/widgets/logo.dart';
import 'package:provider/provider.dart';

class RegisterPage extends StatelessWidget {
@override
Expand Down Expand Up @@ -48,6 +51,7 @@ class __FormState extends State<_Form> {

@override
Widget build(BuildContext context) {
final AuthService authService = Provider.of<AuthService>( context );
return Container(
margin: EdgeInsets.only(top: 40),
padding: EdgeInsets.symmetric(horizontal: 50),
Expand All @@ -73,9 +77,13 @@ class __FormState extends State<_Form> {
),
CustomButton(
title: 'Crear cuenta',
callback: (){
print( _txtEmail.text );
print( _txtPassword.text );
callback: authService.isAuthNow ? null : () async {
final registerSuccess = await authService.register(_txtName.text, _txtEmail.text.trim(), _txtPassword.text);
if( registerSuccess ){
showSimpleAlert(context, 'Completado', 'Se ha registrado con éxito.').then((value) => Navigator.of(context).pushReplacementNamed('login'));
} else {
showSimpleAlert(context, 'Error', 'Ya existe una cuenta con este correo electrónico');
}
},
)
],
Expand Down
12 changes: 10 additions & 2 deletions lib/src/pages/users.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import 'package:chatapp/src/services/auth.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:chatapp/src/models/user.dart';

Expand All @@ -21,14 +23,20 @@ class _UsersPageState extends State<UsersPage> {

@override
Widget build(BuildContext context) {
final authService = Provider.of<AuthService>(context);
final user = authService.user;
return Scaffold(
appBar: AppBar(
title: Text('Mi nombre', style: TextStyle(color: Colors.black87)),
title: Text('${user.name}', style: TextStyle(color: Colors.black87)),
elevation: 1,
backgroundColor: Colors.white,
leading: IconButton(
icon: Icon( Icons.exit_to_app, color: Colors.black87 ),
onPressed: (){},
onPressed: (){
// TODO: Desconectar el socket server
Navigator.of(context).pushReplacementNamed('login');
AuthService.deleteToken();
},
),
actions: [
Container(
Expand Down
Loading

0 comments on commit a96075f

Please sign in to comment.