aboutsummaryrefslogtreecommitdiff
path: root/lib/screens/login_screen.dart
blob: c98a5651e3f7ecf8561b5195dae4981e14a003f8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:linkchat/settings/preferences.dart';
import 'package:social_login_buttons/social_login_buttons.dart';

import '../firebase/auth.dart';
import '../widgets/loading_modal_widget.dart';
import '../widgets/responsive.dart';

class LoginScreen extends StatefulWidget {
  const LoginScreen({super.key});

  @override
  State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;

  final Auth _auth = Auth();

  bool isLoading = false;
  bool isInit = false;

  final padding = 16.0;
  final spacer = const SizedBox(height: 16.0);

  // TextField controllers
  late TextEditingController _emailController;
  late TextEditingController _passwordController;

  @override
  void initState() {
    super.initState();
    _emailController = TextEditingController();
    _passwordController = TextEditingController();
    _controller = AnimationController(vsync: this);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  Widget logoItc() => Padding(
        padding: EdgeInsets.all(padding * 2),
        child: Image.asset('assets/logo.png', height: 120.0),
      );

  Widget loginForm() => Column(
        children: [
          spacer,
          Container(
            width: double.infinity,
            alignment: Alignment.centerLeft,
            padding: EdgeInsets.symmetric(horizontal: padding),
            child: Text(
              'Iniciar sesión',
              style: Theme.of(context).textTheme.displaySmall,
              textAlign: TextAlign.left,
            ),
          ),
          Card(
            margin: EdgeInsets.all(padding),
            child: Padding(
              padding: EdgeInsets.all(padding),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  TextField(
                    controller: _emailController,
                    decoration: const InputDecoration(
                      border: OutlineInputBorder(),
                      labelText: 'Correo electrónico',
                      hintText: 'test@example.com',
                    ),
                    keyboardType: TextInputType.emailAddress,
                  ),
                  spacer,
                  TextField(
                    controller: _passwordController,
                    obscureText: true,
                    decoration: const InputDecoration(
                      border: OutlineInputBorder(),
                      labelText: 'Contraseña',
                    ),
                  ),
                  spacer,
                  SocialLoginButton(
                    buttonType: SocialLoginButtonType.generalLogin,
                    text: 'Iniciar sesión',
                    backgroundColor: Theme.of(context).colorScheme.primary,
                    onPressed: () => onLoginClicked(context),
                  ),
                  spacer,
                  TextButton(
                    onPressed: () {
                      Navigator.of(context).pushNamed('/register');
                    },
                    child: const Text('Crear cuenta'),
                  ),
                ],
              ),
            ),
          ),
        ],
      );

  void onLoginClicked(BuildContext context) {
    setState(() {
      isLoading = true;
    });
    _auth
        .signInWithEmailAndPassword(
      email: _emailController.text,
      password: _passwordController.text,
    )
        .then((result) {
      setState(() {
        isLoading = false;
      });
      result.fold(
        (user) {
          if (user != null && user.emailVerified == false) {
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(content: Text('El correo no está verificado')),
            );
          } else {
            Preferences.getShowOnboarding().then((show) {
              Navigator.of(context)
                  .pushReplacementNamed(show ? '/onboard' : '/dash');
            });
          }
        },
        (error) => handleError(error),
      );
    });
  }

  void onGoogleLoginClicked(BuildContext context) {
    setState(() {
      isLoading = true;
    });
    _auth.signInWithGoogle().then((result) {
      setState(() {
        isLoading = false;
      });
      result.fold(
        (user) {},
        (error) => handleError(error),
      );
    });
  }

  void onGithubLoginClicked(BuildContext context) {
    setState(() {
      isLoading = true;
    });
    _auth.signInWithGithub().then((result) {
      setState(() {
        isLoading = false;
      });
      result.fold(
        (user) {},
        (error) => handleError(error),
      );
    });
  }

  void handleError(FirebaseException error) {
    String message;
    switch (error.code) {
      case 'invalid-email':
        message = 'El correo electrónico es inválido';
      case 'user-disabled':
        message = 'El usuario está desactivado';
      case 'user-not-found':
        message = 'El usuario no existe';
      case 'wrong-password':
        message = 'La contraseña es incorrecta.';
      default:
        message = 'Ocurrió un error desconocido';
    }
    ScaffoldMessenger.of(context)
        .showSnackBar(SnackBar(content: Text(message)));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          SingleChildScrollView(
            child: SafeArea(
              child: Responsive(
                mobile: Column(
                  children: [logoItc(), loginForm()],
                ),
                desktop: Row(
                  children: [
                    Expanded(child: logoItc()),
                    Expanded(child: loginForm()),
                  ],
                ),
              ),
            ),
          ),
          isLoading ? const LoadingModal() : const SizedBox.shrink(),
        ],
      ),
    );
  }
}