Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import 'package:flutter/material.dart';
- import 'package:http/http.dart' as http;
- import 'package:google_fonts/google_fonts.dart';
- import 'package:task_app_es/work_screen.dart';
- class LoginPage extends StatefulWidget {
- const LoginPage({Key? key}) : super(key: key);
- @override
- _LoginPageState createState() => _LoginPageState();
- }
- class _LoginPageState extends State<LoginPage> with WidgetsBindingObserver {
- final Map<String, String> credentials = {
- 'Char': 'Charanne556.',
- 'Lewis': 'PW',
- 'Andy': 'Polski123',
- 'Emmanuel': 'Kayari1'
- // Add more username/password pairs here
- };
- String enteredUsername = '';
- String enteredPassword = '';
- bool _isLoading = false;
- bool _loginFailed = false;
- bool _keyboardVisible = false;
- bool _pageVisible = false;
- @override
- void initState() {
- super.initState();
- WidgetsBinding.instance!.addObserver(this);
- // Delay to start fading in the page after 3 seconds
- Future.delayed(const Duration(milliseconds: 500), () {
- setState(() {
- _pageVisible = true;
- });
- });
- }
- @override
- void dispose() {
- WidgetsBinding.instance!.removeObserver(this);
- super.dispose();
- }
- @override
- void didChangeMetrics() {
- final bool isKeyboardOpen = MediaQuery.of(context).viewInsets.bottom > 0;
- setState(() {
- _keyboardVisible = isKeyboardOpen;
- });
- }
- @override
- Widget build(BuildContext context) {
- return Scaffold(
- backgroundColor: Colors.transparent,
- appBar: AppBar(
- toolbarHeight: 15,
- backgroundColor: const Color.fromARGB(255, 0, 0, 0),
- ),
- body: AnimatedOpacity(
- opacity: _pageVisible ? 1.0 : 0.0,
- duration: const Duration(milliseconds: 1500),
- child: GestureDetector(
- onTap: () {
- FocusScope.of(context).unfocus();
- },
- child: Stack(
- children: [
- Container(
- width: double.infinity,
- height: double.infinity,
- decoration: const BoxDecoration(
- gradient: LinearGradient(
- begin: Alignment.centerLeft,
- end: Alignment.centerRight,
- colors: [
- Color.fromARGB(255, 71, 0, 165),
- Color.fromARGB(255, 117, 0, 172),
- ],
- ),
- ),
- ),
- SingleChildScrollView(
- child: Center(
- child: Padding(
- padding: const EdgeInsets.all(0.0),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.center,
- children: [
- const SizedBox(height: 10.0),
- Center(
- child: Stack(
- children: [
- Text(
- 'Login',
- style: GoogleFonts.langar(
- textStyle: TextStyle(
- fontSize: 100,
- fontWeight: FontWeight.w400,
- foreground: Paint()
- ..shader = const LinearGradient(
- colors: [
- Color.fromARGB(59, 117, 1, 212),
- Color.fromARGB(54, 157, 45, 255),
- Color.fromARGB(50, 134, 0, 211),
- ],
- ).createShader(
- const Rect.fromLTWH(
- 100.0, // left position
- 0.0, // top position
- 200, // width
- 100.0, // height
- ),
- ),
- ),
- ),
- ),
- Text(
- 'Login',
- style: GoogleFonts.langar(
- textStyle: TextStyle(
- fontSize: 100,
- fontWeight: FontWeight.w800,
- foreground: Paint()
- ..style = PaintingStyle.stroke
- ..strokeWidth = 0.2
- ..color =
- const Color.fromARGB(95, 51, 1, 97),
- ),
- ),
- ),
- ],
- ),
- ),
- const SizedBox(height: 20.0),
- AnimatedContainer(
- duration: const Duration(milliseconds: 500),
- curve: Curves.easeInOut,
- width: 300.0,
- height: 150,
- padding: const EdgeInsets.symmetric(horizontal: 10.0),
- decoration: BoxDecoration(
- color: const Color.fromARGB(0, 0, 0, 0),
- borderRadius: BorderRadius.circular(10.0),
- border: Border.all(
- width: 2.0,
- color: const Color.fromARGB(0, 255, 255, 255),
- ),
- ),
- child: Column(
- children: [
- Container(
- decoration: BoxDecoration(
- color: const Color.fromARGB(78, 1, 0, 2),
- borderRadius: BorderRadius.circular(15.0),
- border: Border.all(
- width: 2.0,
- color: const Color.fromARGB(
- 141, 201, 137, 243),
- ),
- ),
- child: TextFormField(
- textAlign: TextAlign.center,
- style: GoogleFonts.kodeMono(
- fontSize: 22,
- color: const Color.fromARGB(
- 255, 229, 125, 255),
- ),
- decoration: InputDecoration.collapsed(
- hintText: 'Username',
- hintStyle: GoogleFonts.bebasNeue(
- fontSize: 28,
- color: const Color.fromARGB(
- 148, 235, 171, 255),
- ),
- ),
- onChanged: (value) {
- setState(() {
- enteredUsername = value;
- });
- },
- ),
- ),
- const SizedBox(height: 20.0),
- Container(
- decoration: BoxDecoration(
- color: const Color.fromARGB(78, 1, 0, 2),
- borderRadius: BorderRadius.circular(15.0),
- border: Border.all(
- width: 2.0,
- color: const Color.fromARGB(
- 141, 201, 137, 243),
- ),
- ),
- child: TextFormField(
- textAlign: TextAlign.center,
- obscureText: true,
- style: GoogleFonts.kodeMono(
- fontSize: 22,
- color: const Color.fromARGB(
- 255, 229, 125, 255),
- ),
- decoration: InputDecoration.collapsed(
- hintText: 'Password',
- hintStyle: GoogleFonts.bebasNeue(
- fontSize: 28,
- color: const Color.fromARGB(
- 148, 235, 171, 255),
- ),
- ),
- onChanged: (value) {
- setState(() {
- enteredPassword = value;
- });
- },
- ),
- ),
- ],
- ),
- ),
- const SizedBox(height: 10.0),
- _isLoading
- ? const CircularProgressIndicator()
- : SizedBox(
- height: 40.0,
- width: 150.0,
- child: InkWell(
- onTap: _login,
- child: Container(
- decoration: BoxDecoration(
- borderRadius: BorderRadius.circular(15.0),
- color: const Color.fromARGB(
- 124, 240, 201, 255),
- border: Border.all(
- width: 2.0,
- color: const Color.fromARGB(
- 255, 227, 214, 255),
- ),
- ),
- child: const Center(
- child: Text(
- 'Login',
- style: TextStyle(
- fontSize: 20.0,
- fontWeight: FontWeight.bold,
- color: Color.fromARGB(
- 193, 231, 190, 255),
- ),
- ),
- ),
- ),
- ),
- ),
- const SizedBox(height: 25.0),
- SizedBox(
- height: 40.0,
- width: 200.0,
- child: InkWell(
- onTap: () => _createUser(context),
- child: Container(
- decoration: BoxDecoration(
- borderRadius: BorderRadius.circular(15.0),
- color: const Color.fromARGB(124, 240, 201, 255),
- border: Border.all(
- width: 2.0,
- color:
- const Color.fromARGB(255, 227, 214, 255),
- ),
- ),
- child: const Center(
- child: Text(
- 'Create User',
- style: TextStyle(
- fontSize: 20.0,
- fontWeight: FontWeight.bold,
- color: Color.fromARGB(193, 231, 190, 255),
- ),
- ),
- ),
- ),
- ),
- ),
- ],
- ),
- ),
- ),
- ),
- AnimatedPositioned(
- duration: const Duration(milliseconds: 100),
- curve: Curves.easeInOut,
- bottom: _keyboardVisible ? 0 : 0,
- left: _keyboardVisible ? 0 : 100,
- child: AnimatedContainer(
- duration: const Duration(milliseconds: 100),
- curve: Curves.easeInOut,
- width: _keyboardVisible ? 45 : 200,
- height: _keyboardVisible ? 45 : 200,
- child: Image.asset(
- 'assets/cat_galaxy.gif',
- repeat: ImageRepeat.noRepeat,
- ),
- ),
- ),
- ],
- ),
- ),
- ),
- );
- }
- void showErrorPrompt(String message) {
- showDialog(
- context: context,
- builder: (context) => AlertDialog(
- title: const Text('Error'),
- content: Text(message),
- actions: [
- TextButton(
- onPressed: () => Navigator.of(context).pop(),
- child: const Text('OK'),
- ),
- ],
- ),
- );
- }
- void _login() {
- // Hide the keyboard
- FocusScope.of(context).unfocus();
- setState(() {
- _isLoading = true;
- });
- // Check if username and password are empty
- if (enteredUsername.isEmpty && enteredPassword.isEmpty) {
- showErrorPrompt('Please enter a username and password');
- setState(() {
- _isLoading = false;
- });
- return;
- }
- // Check if username is missing
- if (enteredUsername.isEmpty) {
- showErrorPrompt('Please enter a valid username to continue');
- setState(() {
- _isLoading = false;
- });
- return;
- }
- // Check if password is missing
- if (enteredPassword.isEmpty) {
- showErrorPrompt('Please enter a valid password to continue');
- setState(() {
- _isLoading = false;
- });
- return;
- }
- // Send the login request
- http.post(
- Uri.parse('https://notsoofriendly.co.uk/TaskApp_ES/handle_login.php'),
- body: {
- 'username': enteredUsername,
- 'password': enteredPassword,
- },
- ).then((response) {
- // Check if the response is valid
- if (response.statusCode == 200) {
- // Check if the response contains 'valid login'
- if (response.body.trim() == 'valid login') {
- // Navigate to WorkScreen
- Navigator.pushReplacement(
- context,
- MaterialPageRoute(builder: (context) => const WorkScreen()),
- );
- } else {
- // Invalid credentials
- showErrorPrompt(
- 'Username or Password is incorrect, please try again');
- }
- } else {
- // Show error message for failed request
- showErrorPrompt('Failed to log in. Please try again later.');
- }
- // Reset loading state
- setState(() {
- _isLoading = false;
- });
- }).catchError((error) {
- // Show error message for exceptions
- showErrorPrompt('An error occurred. Please try again later.');
- // Reset loading state
- setState(() {
- _isLoading = false;
- });
- });
- }
- void _createUser(BuildContext context) async {
- String errorMessage = '';
- String username = '';
- String password = '';
- String email = '';
- // Variables to track validation status of each input field
- bool isUsernameValid = false;
- bool isPasswordValid = false;
- bool isEmailValid = false;
- // Function to update validation status and check if all fields are valid
- bool isFormValid() {
- return isUsernameValid && isPasswordValid && isEmailValid;
- }
- // Function to get icon based on validation status
- Widget getIcon(bool isValid) {
- return isValid
- ? const Icon(Icons.check, color: Colors.green)
- : const Icon(Icons.close, color: Colors.red);
- }
- showDialog(
- context: context,
- builder: (context) => AlertDialog(
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(15.0), // Rounded corners
- ),
- backgroundColor: Colors.deepPurple.withOpacity(0.8),
- contentPadding: const EdgeInsets.all(15),
- content: ConstrainedBox(
- constraints: BoxConstraints(
- maxHeight: MediaQuery.of(context).size.height - 50,
- minWidth: MediaQuery.of(context).size.width - 10,
- ),
- child: SingleChildScrollView(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.center,
- mainAxisSize: MainAxisSize.min,
- children: [
- const Text(
- 'Create User',
- style: TextStyle(
- fontSize: 20,
- fontWeight: FontWeight.bold,
- color: Colors.white,
- ),
- ),
- const SizedBox(height: 20),
- Container(
- margin: const EdgeInsets.symmetric(horizontal: 5),
- decoration: BoxDecoration(
- borderRadius: BorderRadius.circular(20.0),
- color: Colors.transparent,
- ),
- child: ExpansionTile(
- expandedCrossAxisAlignment: CrossAxisAlignment.center,
- iconColor: const Color.fromARGB(255, 255, 196, 0),
- collapsedIconColor: Colors.white,
- title: const Text(
- 'User Creation Help',
- style: TextStyle(
- fontSize: 16,
- fontWeight: FontWeight.bold,
- color: Color.fromARGB(255, 255, 196, 0),
- ),
- ),
- initiallyExpanded: false,
- children: [
- const SizedBox(height: 10), // Gap of 10px
- Container(
- decoration: BoxDecoration(
- borderRadius: BorderRadius.circular(20.0),
- color: Colors.deepPurple.withOpacity(0.8),
- ),
- child: const ExpansionTile(
- title: Text(
- 'Username Creation',
- textAlign: TextAlign.center,
- style: TextStyle(
- fontSize: 14,
- fontWeight: FontWeight.bold,
- color: Colors.white,
- ),
- ),
- iconColor: Color.fromARGB(255, 255, 196, 0),
- collapsedIconColor: Colors.white,
- initiallyExpanded: false,
- children: [
- Padding(
- padding: EdgeInsets.symmetric(horizontal: 16.0),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.center,
- children: [
- Text(
- 'Username should be the same as your ES Computer Username:',
- style: TextStyle(
- fontSize: 14,
- fontWeight: FontWeight.bold,
- color: Colors.white,
- ),
- textAlign: TextAlign.center,
- ),
- Text(
- '"John.Doe"',
- style: TextStyle(
- fontSize: 13,
- fontStyle: FontStyle.italic,
- color: Colors.white,
- ),
- textAlign: TextAlign.center,
- ),
- ],
- ),
- ),
- ],
- ),
- ),
- const SizedBox(height: 10), // Gap of 10px
- Container(
- decoration: BoxDecoration(
- borderRadius: BorderRadius.circular(20.0),
- color: Colors.deepPurple.withOpacity(0.8),
- ),
- child: const ExpansionTile(
- title: Text(
- 'Password Creation',
- textAlign: TextAlign.center,
- style: TextStyle(
- fontSize: 14,
- fontWeight: FontWeight.bold,
- color: Colors.white,
- ),
- ),
- iconColor: Color.fromARGB(255, 255, 196, 0),
- collapsedIconColor: Colors.white,
- initiallyExpanded: false,
- children: [
- Padding(
- padding: EdgeInsets.symmetric(horizontal: 16.0),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.center,
- children: [
- Text(
- 'Password must contain 6 Characters, including a capital Letter, Lower Case Letter & 1 Special Character:',
- style: TextStyle(
- fontSize: 14,
- fontWeight: FontWeight.bold,
- color: Colors.white,
- ),
- textAlign: TextAlign.center,
- ),
- Text(
- '"ExamplePW24!"',
- style: TextStyle(
- fontSize: 13,
- fontStyle: FontStyle.italic,
- color: Colors.white,
- ),
- textAlign: TextAlign.center,
- ),
- ],
- ),
- ),
- ],
- ),
- ),
- const SizedBox(height: 10), // Gap of 10px
- Container(
- margin: const EdgeInsets.only(bottom: 10),
- decoration: BoxDecoration(
- borderRadius: BorderRadius.circular(20.0),
- color: Colors.deepPurple.withOpacity(0.8),
- ),
- child: const ExpansionTile(
- title: Text(
- 'Email Address Creation',
- textAlign: TextAlign.center,
- style: TextStyle(
- fontSize: 14,
- fontWeight: FontWeight.bold,
- color: Colors.white,
- ),
- ),
- iconColor: Color.fromARGB(255, 255, 196, 0),
- collapsedIconColor: Colors.white,
- initiallyExpanded: false,
- children: [
- Padding(
- padding: EdgeInsets.symmetric(horizontal: 16.0),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.center,
- children: [
- Text(
- 'ES Work Email Address must follow the format:',
- style: TextStyle(
- fontSize: 14,
- fontWeight: FontWeight.bold,
- color: Colors.white,
- ),
- textAlign: TextAlign.center,
- ),
- Text(
- '" firstname.lastname@epilepsysociety.org.uk"',
- style: TextStyle(
- fontSize: 13,
- fontStyle: FontStyle.italic,
- color: Colors.white,
- ),
- textAlign: TextAlign.center,
- ),
- ],
- ),
- ),
- ],
- ),
- ),
- ],
- ),
- ),
- const SizedBox(height: 20),
- TextFormField(
- decoration: InputDecoration(
- floatingLabelAlignment: FloatingLabelAlignment.center,
- labelText: 'ES Username:',
- labelStyle: const TextStyle(
- color: Color.fromARGB(255, 190, 131, 252),
- fontSize: 18,
- ),
- suffixIcon: getIcon(isUsernameValid),
- ),
- textAlign: TextAlign.left,
- style: const TextStyle(
- color: Color.fromARGB(255, 255, 255, 255),
- fontSize: 20,
- ),
- onChanged: (value) {
- setState(() {
- username = value;
- isUsernameValid = _validateUsername(username);
- });
- },
- ),
- // Password TextFormField
- TextFormField(
- decoration: InputDecoration(
- floatingLabelAlignment: FloatingLabelAlignment.center,
- labelText: 'Password:',
- labelStyle: const TextStyle(
- color: Color.fromARGB(255, 190, 131, 252),
- fontSize: 18,
- ),
- suffixIcon: getIcon(isPasswordValid),
- ),
- textAlign: TextAlign.left,
- style: const TextStyle(
- color: Color.fromARGB(255, 255, 255, 255),
- fontSize: 20,
- ),
- onChanged: (value) {
- setState(() {
- password = value;
- isPasswordValid = _validatePassword(password);
- });
- },
- ),
- // Email TextFormField
- TextFormField(
- decoration: InputDecoration(
- floatingLabelAlignment: FloatingLabelAlignment.center,
- labelText: 'ES Work Email Address:',
- labelStyle: const TextStyle(
- color: Color.fromARGB(255, 190, 131, 252),
- fontSize: 18,
- ),
- suffixIcon: getIcon(isEmailValid),
- ),
- textAlign: TextAlign.left,
- style: const TextStyle(
- color: Color.fromARGB(255, 255, 255, 255),
- fontSize: 12,
- ),
- onChanged: (value) {
- setState(() {
- email = value;
- isEmailValid = _validateEmail(email, username);
- });
- },
- ),
- const SizedBox(height: 20),
- Row(
- mainAxisAlignment: MainAxisAlignment.center,
- children: [
- TextButton(
- onPressed: () => Navigator.of(context).pop(),
- child: const Text(
- 'Cancel',
- style: TextStyle(color: Colors.white, fontSize: 22.0),
- ),
- ),
- const SizedBox(width: 20),
- TextButton(
- onPressed: isFormValid()
- ? () async {
- // Process user creation
- final response = await createUser(username, password, email);
- print(response);
- if (response == 'success') {
- // Close the form if user creation is successful
- Navigator.of(context).pop();
- return;
- } else {
- // Reset form if user creation failed
- errorMessage = 'Failed to create user';
- }
- // Print whether user creation is valid
- bool userCreationValid = errorMessage.isEmpty;
- print('User Creation Valid: $userCreationValid');
- // Show error prompt if necessary
- if (errorMessage.isNotEmpty) {
- _showErrorPrompt(errorMessage, context);
- }
- }
- : null,
- child: const Text(
- 'Create',
- style: TextStyle(color: Colors.white, fontSize: 22.0),
- ),
- ),
- ],
- ),
- ],
- ),
- ),
- ),
- ),
- );
- }
- Future<String> createUser(
- String username, String password, String email) async {
- final response = await http.post(
- Uri.parse('https://notsoofriendly.co.uk/TaskApp_ES/ta_add_user.php'),
- body: {
- 'username': username,
- 'password': password,
- 'email': email,
- },
- );
- if (response.statusCode == 200) {
- return 'success';
- } else {
- throw Exception('Failed to create user');
- }
- }
- bool _validateUsername(String username) {
- // Check if username matches the format firstname.lastname
- RegExp usernameRegExp = RegExp(r'^[a-zA-Z]+\.[a-zA-Z]+$');
- return usernameRegExp.hasMatch(username);
- }
- bool _validatePassword(String password) {
- // Password must contain 6 characters, including a capital letter, lowercase letter, and a special character
- RegExp passwordRegExp =
- RegExp(r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[^\w\s]).{6,}$');
- return passwordRegExp.hasMatch(password);
- }
- bool _validateEmail(String email, String username) {
- // Email must follow the format: firstname.lastname@epilepsysociety.org.uk
- String emailPattern = '${username.toLowerCase()}@epilepsysociety.org.uk';
- return email.toLowerCase() == emailPattern;
- }
- void _showErrorPrompt(String message, BuildContext context) {
- if (context != null && mounted) {
- showDialog(
- context: context,
- builder: (context) => AlertDialog(
- title: const Text('Error'),
- content: Text(message),
- actions: [
- TextButton(
- onPressed: () => Navigator.of(context).pop(),
- child: const Text('OK'),
- ),
- ],
- ),
- );
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement