Interface de connexion avec connexion réussie au serveur

This commit is contained in:
DahoudG
2024-08-27 16:52:39 +00:00
parent 59331ddd7d
commit e233f9f392
9 changed files with 216 additions and 165 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 131 KiB

View File

@@ -1,5 +1,5 @@
class Urls { class Urls {
static const String baseUrl = 'http://localhost:8085'; static const String baseUrl = 'http://192.168.1.145:8085';
// static const String login = baseUrl + 'auth/login'; // static const String login = baseUrl + 'auth/login';
// static const String events = baseUrl + 'events'; // static const String events = baseUrl + 'events';
// Ajoute d'autres URLs ici // Ajoute d'autres URLs ici

View File

@@ -1,3 +1,12 @@
class ServerException implements Exception {} class ServerException implements Exception {}
class CacheException implements Exception {} class CacheException implements Exception {}
class AuthenticationException implements Exception {
final String message;
AuthenticationException(this.message);
@override
String toString() => 'AuthenticationException: $message';
}

View File

@@ -10,6 +10,30 @@ class UserRemoteDataSource {
UserRemoteDataSource(this.client); UserRemoteDataSource(this.client);
Future<UserModel> authenticateUser(String email, String password) async {
if (email.isEmpty || password.isEmpty) {
throw Exception('Email ou mot de passe vide');
}
final response = await client.post(
Uri.parse('${Urls.baseUrl}/users/authenticate'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({
'email': email,
'motDePasse': password,
}),
);
if (response.statusCode == 200) {
final jsonResponse = json.decode(response.body);
return UserModel.fromJson(jsonResponse);
} else if (response.statusCode == 401) {
throw AuthenticationException('Email ou mot de passe incorrect');
} else {
throw ServerException();
}
}
Future<UserModel> getUser(String id) async { Future<UserModel> getUser(String id) async {
final response = await client.get(Uri.parse('${Urls.baseUrl}/user/$id')); final response = await client.get(Uri.parse('${Urls.baseUrl}/user/$id'));

View File

@@ -1,6 +1,7 @@
import 'package:afterwork/domain/entities/user.dart'; import 'package:afterwork/domain/entities/user.dart';
import 'package:afterwork/domain/repositories/user_repository.dart'; import 'package:afterwork/domain/repositories/user_repository.dart';
import 'package:afterwork/data/datasources/user_remote_data_source.dart'; import 'package:afterwork/data/datasources/user_remote_data_source.dart';
import 'package:afterwork/data/models/user_model.dart';
class UserRepositoryImpl implements UserRepository { class UserRepositoryImpl implements UserRepository {
final UserRemoteDataSource remoteDataSource; final UserRemoteDataSource remoteDataSource;
@@ -9,6 +10,12 @@ class UserRepositoryImpl implements UserRepository {
@override @override
Future<User> getUser(String id) async { Future<User> getUser(String id) async {
return await remoteDataSource.getUser(id); UserModel userModel = await remoteDataSource.getUser(id);
return userModel; // Retourne un UserModel qui est un sous-type de User
}
Future<User> authenticateUser(String email, String password) async {
UserModel userModel = await remoteDataSource.authenticateUser(email, password);
return userModel; // Retourne un UserModel qui est un sous-type de User
} }
} }

View File

@@ -1,26 +1,37 @@
import 'package:afterwork/domain/entities/user.dart';
import '../../domain/entities/user.dart';
class UserModel extends User { class UserModel extends User {
const UserModel({ const UserModel({
required super.id, required String id,
required super.name, required String nom,
required super.email, required String prenoms,
}); required String email,
required String motDePasse,
}) : super(
id: id,
nom: nom,
prenoms: prenoms,
email: email,
motDePasse: motDePasse,
);
factory UserModel.fromJson(Map<String, dynamic> json) { factory UserModel.fromJson(Map<String, dynamic> json) {
return UserModel( return UserModel(
id: json['id'], id: json['id'] ?? '',
name: json['name'], nom: json['nom'] ?? '',
email: json['email'], prenoms: json['prenoms'] ?? '',
email: json['email'] ?? '',
motDePasse: json['motDePasse'] ?? '',
); );
} }
Map<String, dynamic> toJson() { Map<String, dynamic> toJson() {
return { return {
'id': id, 'id': id,
'name': name, 'nom': nom,
'prenoms': prenoms,
'email': email, 'email': email,
'motDePasse': motDePasse,
}; };
} }
} }

View File

@@ -2,11 +2,19 @@ import 'package:equatable/equatable.dart';
class User extends Equatable { class User extends Equatable {
final String id; final String id;
final String name; final String nom;
final String prenoms;
final String email; final String email;
final String motDePasse;
const User({required this.id, required this.name, required this.email}); const User({
required this.id,
required this.nom,
required this.prenoms,
required this.email,
required this.motDePasse,
});
@override @override
List<Object?> get props => [id, name, email]; List<Object?> get props => [id, nom, prenoms, email, motDePasse];
} }

View File

@@ -1,45 +1,22 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:afterwork/data/datasources/user_remote_data_source.dart';
import 'package:afterwork/data/models/user_model.dart';
import 'package:http/http.dart' as http;
class LoginScreen extends StatefulWidget { class LoginScreen extends StatefulWidget {
const LoginScreen({Key? key}) : super(key: key); const LoginScreen({super.key});
@override @override
_LoginScreenState createState() => _LoginScreenState(); _LoginScreenState createState() => _LoginScreenState();
} }
class _LoginScreenState extends State<LoginScreen> with SingleTickerProviderStateMixin { class _LoginScreenState extends State<LoginScreen> {
final _formKey = GlobalKey<FormState>(); final _formKey = GlobalKey<FormState>();
String _email = ''; String _email = ''; // Initialisation par défaut
String _password = ''; String _password = ''; // Initialisation par défaut
bool _isPasswordVisible = false; bool _isPasswordVisible = false;
late AnimationController _animationController; final UserRemoteDataSource _userRemoteDataSource = UserRemoteDataSource(http.Client());
late Animation<Offset> _slideAnimation;
@override
void initState() {
super.initState();
_animationController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 500),
);
_slideAnimation = Tween<Offset>(
begin: const Offset(0.0, 1.0),
end: Offset.zero,
).animate(CurvedAnimation(
parent: _animationController,
curve: Curves.easeOut,
));
_animationController.forward();
}
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
void _togglePasswordVisibility() { void _togglePasswordVisibility() {
setState(() { setState(() {
@@ -47,11 +24,32 @@ class _LoginScreenState extends State<LoginScreen> with SingleTickerProviderStat
}); });
} }
void _submit() { void _submit() async {
if (_formKey.currentState!.validate()) { if (_formKey.currentState!.validate()) {
_formKey.currentState!.save(); _formKey.currentState!.save();
print('Email: $_email, Password: $_password'); // Utilisation des valeurs
// Implémente la logique de connexion ici print('Email: $_email'); // Pour vérifier la valeur de l'email
print('Mot de passe: $_password'); // Pour vérifier la valeur du mot de passe
if (_email.isEmpty || _password.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Veuillez remplir tous les champs')),
);
return;
}
try {
UserModel user = await _userRemoteDataSource.authenticateUser(_email, _password);
print('Connexion réussie : ${user.email}');
// Naviguer vers la page d'accueil ou autre
} catch (e) {
print('Erreur lors de la connexion: $e');
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(e.toString())),
);
}
} else {
print('Formulaire invalide');
} }
} }
@@ -61,15 +59,24 @@ class _LoginScreenState extends State<LoginScreen> with SingleTickerProviderStat
return Scaffold( return Scaffold(
backgroundColor: Colors.white, backgroundColor: Colors.white,
body: Center( body: Stack(
children: [
// Arrière-plan
Positioned.fill(
child: Image.asset(
'lib/assets/images/background.webp', // Remplace par le chemin de ton image
fit: BoxFit.cover,
),
),
// Contenu de la page
Center(
child: SingleChildScrollView( child: SingleChildScrollView(
padding: const EdgeInsets.all(16.0), padding: const EdgeInsets.all(16.0),
child: SlideTransition( child: Form(
position: _slideAnimation, key: _formKey,
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center,
children: [ children: [
// Logo
Image.asset( Image.asset(
'lib/assets/images/logo.png', 'lib/assets/images/logo.png',
height: size.height * 0.2, height: size.height * 0.2,
@@ -84,13 +91,6 @@ class _LoginScreenState extends State<LoginScreen> with SingleTickerProviderStat
), ),
), ),
const SizedBox(height: 40), const SizedBox(height: 40),
// Formulaire de connexion
Form(
key: _formKey,
child: Column(
children: [
// Champ Email
TextFormField( TextFormField(
decoration: const InputDecoration( decoration: const InputDecoration(
labelText: 'Email', labelText: 'Email',
@@ -108,12 +108,10 @@ class _LoginScreenState extends State<LoginScreen> with SingleTickerProviderStat
return null; return null;
}, },
onSaved: (value) { onSaved: (value) {
_email = value!; _email = value ?? ''; // Utiliser une chaîne vide si value est null
}, },
), ),
const SizedBox(height: 20), const SizedBox(height: 20),
// Champ Mot de passe
TextFormField( TextFormField(
decoration: InputDecoration( decoration: InputDecoration(
labelText: 'Mot de passe', labelText: 'Mot de passe',
@@ -121,9 +119,7 @@ class _LoginScreenState extends State<LoginScreen> with SingleTickerProviderStat
prefixIcon: const Icon(Icons.lock), prefixIcon: const Icon(Icons.lock),
suffixIcon: IconButton( suffixIcon: IconButton(
icon: Icon( icon: Icon(
_isPasswordVisible _isPasswordVisible ? Icons.visibility : Icons.visibility_off,
? Icons.visibility
: Icons.visibility_off,
), ),
onPressed: _togglePasswordVisibility, onPressed: _togglePasswordVisibility,
), ),
@@ -139,12 +135,10 @@ class _LoginScreenState extends State<LoginScreen> with SingleTickerProviderStat
return null; return null;
}, },
onSaved: (value) { onSaved: (value) {
_password = value!; _password = value ?? ''; // Utiliser une chaîne vide si value est null
}, },
), ),
const SizedBox(height: 20), const SizedBox(height: 20),
// Bouton de connexion
SizedBox( SizedBox(
width: double.infinity, width: double.infinity,
child: ElevatedButton( child: ElevatedButton(
@@ -161,8 +155,6 @@ class _LoginScreenState extends State<LoginScreen> with SingleTickerProviderStat
), ),
), ),
const SizedBox(height: 20), const SizedBox(height: 20),
// Lien pour s'inscrire
TextButton( TextButton(
onPressed: () { onPressed: () {
// Naviguer vers la page d'inscription // Naviguer vers la page d'inscription
@@ -175,11 +167,10 @@ class _LoginScreenState extends State<LoginScreen> with SingleTickerProviderStat
], ],
), ),
), ),
),
),
], ],
), ),
),
),
),
); );
} }
} }

View File

@@ -39,6 +39,7 @@ flutter:
assets: assets:
- lib/assets/images/logo.png - lib/assets/images/logo.png
- lib/assets/images/background.webp
# To add assets to your application, add an assets section, like this: # To add assets to your application, add an assets section, like this:
# assets: # assets: