-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.js
More file actions
997 lines (905 loc) · 31.2 KB
/
App.js
File metadata and controls
997 lines (905 loc) · 31.2 KB
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
/**
* ReactAuthExample - Welcome & Authentication Screen
* https://github.com/facebook/react-native
*
* @format
*/
import React, { useState, useEffect } from 'react';
import {
SafeAreaView,
StyleSheet,
Text,
View,
TouchableOpacity,
Alert,
StatusBar,
useColorScheme,
TextInput,
KeyboardAvoidingView,
Platform,
ScrollView,
} from 'react-native';
import * as Keychain from 'react-native-keychain';
// Import version from configuration files
const packageJson = require('./package.json');
const versionConfig = require('./version.json');
// API Configuration
const API_BASE_URL_LOCAL = 'http://localhost:8888/reactauth-api/api';
const API_BASE_URL_PROD = 'https://www.iclassicnu.com/reactauth-api/api';
const API_BASE_URL = __DEV__ ? API_BASE_URL_LOCAL : API_BASE_URL_PROD;
const API_ENDPOINTS = {
login: `${API_BASE_URL}/login.php`,
register: `${API_BASE_URL}/register.php`,
profile: `${API_BASE_URL}/profile.php`,
test: `${API_BASE_URL}/test.php`,
refresh: `${API_BASE_URL}/refresh.php`,
logout: `${API_BASE_URL}/logout.php`
};
function App() {
const isDarkMode = useColorScheme() === 'dark';
const [currentScreen, setCurrentScreen] = useState('welcome'); // 'welcome', 'login', or 'dashboard'
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [emailError, setEmailError] = useState('');
const [passwordError, setPasswordError] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [user, setUser] = useState(null);
const [authToken, setAuthToken] = useState(null);
const [refreshToken, setRefreshToken] = useState(null);
const [tokenExpiration, setTokenExpiration] = useState(null);
const [showPassword, setShowPassword] = useState(false);
const [profileData, setProfileData] = useState(null);
// Helper function for authenticated API calls
const makeAuthenticatedRequest = async (endpoint, options = {}) => {
// First check if we have an access token
if (!authToken) {
throw new Error('No authentication token available');
}
// Check if access token is expired
if (tokenExpiration && Date.now() >= tokenExpiration) {
console.log('Access token expired, attempting refresh...');
// Try to refresh the token
const refreshed = await refreshAccessToken();
if (!refreshed) {
// Refresh failed, clear auth and redirect to login
await clearAuthData();
Alert.alert('Session Expired', 'Please login again.');
setCurrentScreen('welcome');
throw new Error('Token refresh failed');
}
}
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${authToken}`,
...options.headers
};
const response = await fetch(endpoint, {
...options,
headers
});
if (response.status === 401) {
// Access token might be invalid, try to refresh
console.log('API returned 401, attempting token refresh...');
const refreshed = await refreshAccessToken();
if (refreshed) {
// Retry the original request with new token
return fetch(endpoint, {
...options,
headers: {
...headers,
'Authorization': `Bearer ${authToken}`
}
});
} else {
// Refresh failed, clear auth and redirect to login
await clearAuthData();
Alert.alert('Authentication Error', 'Please login again.');
setCurrentScreen('welcome');
throw new Error('Authentication failed');
}
}
return response;
};
// Function to refresh access token using refresh token
const refreshAccessToken = async () => {
try {
if (!refreshToken) {
console.log('No refresh token available');
return false;
}
console.log('Attempting to refresh access token...');
const response = await fetch(API_ENDPOINTS.refresh, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
refresh_token: refreshToken,
}),
});
const data = await response.json();
if (data.success && data.access_token) {
console.log('Access token refreshed successfully');
// Update the access token and expiration
const newExpiration = Date.now() + (data.expires_in * 1000);
setAuthToken(data.access_token);
setTokenExpiration(newExpiration);
// Update stored auth data
await Keychain.setInternetCredentials('authToken', 'token', data.access_token);
await Keychain.setInternetCredentials('tokenExpiration', 'expiration', newExpiration.toString());
console.log('New access token saved, expires:', new Date(newExpiration));
return true;
} else {
console.log('Token refresh failed:', data.error || 'Unknown error');
return false;
}
} catch (error) {
console.log('Token refresh error:', error);
return false;
}
};
// Load cached data on component mount
useEffect(() => {
loadCachedData();
}, []);
const loadCachedData = async () => {
try {
console.log('loadCachedData: Starting...');
// Load cached email
let cachedEmail = null;
try {
const emailCredentials = await Keychain.getInternetCredentials('userEmail');
cachedEmail = emailCredentials ? emailCredentials.username : null;
} catch (error) {
console.log('No cached email found');
}
console.log('loadCachedData: Retrieved email from cache:', cachedEmail);
if (cachedEmail) {
setEmail(cachedEmail);
console.log('loadCachedData: Email set to:', cachedEmail);
}
// Load cached tokens and user data
let cachedAccessToken = null;
let cachedRefreshToken = null;
let cachedUser = null;
let cachedExpiration = null;
try {
const accessTokenCredentials = await Keychain.getInternetCredentials('authToken');
cachedAccessToken = accessTokenCredentials ? accessTokenCredentials.password : null;
} catch (error) {
console.log('No access token found');
}
try {
const refreshTokenCredentials = await Keychain.getInternetCredentials('refreshToken');
cachedRefreshToken = refreshTokenCredentials ? refreshTokenCredentials.password : null;
} catch (error) {
console.log('No refresh token found');
}
try {
const userDataCredentials = await Keychain.getInternetCredentials('userData');
cachedUser = userDataCredentials ? userDataCredentials.password : null;
} catch (error) {
console.log('No user data found');
}
try {
const expirationCredentials = await Keychain.getInternetCredentials('tokenExpiration');
cachedExpiration = expirationCredentials ? expirationCredentials.password : null;
} catch (error) {
console.log('No expiration data found');
}
console.log('loadCachedData: Access token found:', !!cachedAccessToken);
console.log('loadCachedData: Refresh token found:', !!cachedRefreshToken);
console.log('loadCachedData: User data found:', !!cachedUser);
if (cachedRefreshToken && cachedUser) {
// We have a refresh token and user data
setRefreshToken(cachedRefreshToken);
setUser(JSON.parse(cachedUser));
if (cachedAccessToken && cachedExpiration) {
const expTime = parseInt(cachedExpiration);
const now = Date.now();
if (now < expTime) {
// Access token is still valid
setAuthToken(cachedAccessToken);
setTokenExpiration(expTime);
setCurrentScreen('dashboard');
console.log('loadCachedData: Valid access token restored, expires:', new Date(expTime));
return;
} else {
console.log('loadCachedData: Access token expired, will try refresh on first API call');
}
}
// Access token is expired or missing, but we have refresh token
// Navigate to dashboard and let the refresh happen on first API call
setCurrentScreen('dashboard');
console.log('loadCachedData: Refresh token restored, will refresh access token on demand');
} else {
// No valid tokens, user needs to login
console.log('loadCachedData: No valid tokens found');
}
} catch (error) {
console.log('Error loading cached data:', error);
}
};
const saveAuthData = async (accessToken, refreshTokenValue, userData, expiresIn) => {
try {
console.log('saveAuthData: expiresIn received:', expiresIn);
const expirationTime = Date.now() + (expiresIn * 1000);
console.log('saveAuthData: calculated expiration time:', new Date(expirationTime));
await Keychain.setInternetCredentials('authToken', 'token', accessToken);
if (refreshTokenValue) {
await Keychain.setInternetCredentials('refreshToken', 'token', refreshTokenValue);
}
await Keychain.setInternetCredentials('userData', 'data', JSON.stringify(userData));
await Keychain.setInternetCredentials('tokenExpiration', 'expiration', expirationTime.toString());
setAuthToken(accessToken);
if (refreshTokenValue) {
setRefreshToken(refreshTokenValue);
}
setUser(userData);
setTokenExpiration(expirationTime);
console.log('saveAuthData: Auth data saved, access token expires:', new Date(expirationTime));
} catch (error) {
console.log('Error saving auth data:', error);
}
};
const saveAuthDataLegacy = async (token, userData, expiresIn) => {
try {
console.log('saveAuthDataLegacy: expiresIn received:', expiresIn);
const expirationTime = Date.now() + (expiresIn * 1000);
console.log('saveAuthDataLegacy: calculated expiration time:', new Date(expirationTime));
await Keychain.setInternetCredentials('authToken', 'token', token);
await Keychain.setInternetCredentials('userData', 'data', JSON.stringify(userData));
await Keychain.setInternetCredentials('tokenExpiration', 'expiration', expirationTime.toString());
setAuthToken(token);
setUser(userData);
setTokenExpiration(expirationTime);
console.log('saveAuthDataLegacy: Auth data saved, expires:', new Date(expirationTime));
} catch (error) {
console.log('Error saving auth data:', error);
}
};
const clearAuthData = async () => {
try {
await Keychain.resetInternetCredentials('authToken');
await Keychain.resetInternetCredentials('refreshToken');
await Keychain.resetInternetCredentials('userData');
await Keychain.resetInternetCredentials('tokenExpiration');
setAuthToken(null);
setRefreshToken(null);
setUser(null);
setTokenExpiration(null);
console.log('clearAuthData: Auth data cleared');
} catch (error) {
console.log('Error clearing auth data:', error);
}
};
const saveCachedEmail = async (emailToSave) => {
try {
console.log('saveCachedEmail: Saving email:', emailToSave);
await Keychain.setInternetCredentials('userEmail', emailToSave, 'cached');
console.log('saveCachedEmail: Email saved successfully');
} catch (error) {
console.log('Error saving email:', error);
}
};
// Email validation function
const validateEmail = (email) => {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
};
// Password validation function
const validatePassword = (password) => {
const hasMinLength = password.length >= 8;
const hasUppercase = /[A-Z]/.test(password);
const hasLowercase = /[a-z]/.test(password);
const hasSpecialChar = /[!@#$%^&*(),.?":{}|<>]/.test(password);
return {
isValid: hasMinLength && hasUppercase && hasLowercase && hasSpecialChar,
hasMinLength,
hasUppercase,
hasLowercase,
hasSpecialChar
};
};
const showAboutDialog = () => {
Alert.alert(
'About ReactAuthExample',
`Version: ${versionConfig.version}\nBuild: ${versionConfig.buildNumber}\n\nA React Native CLI application example with welcome screen and authentication functionality.`,
[{ text: 'OK', style: 'default' }]
);
};
const handleLogin = async () => {
let hasErrors = false;
// Reset errors
setEmailError('');
setPasswordError('');
// Validate email
if (!email.trim()) {
setEmailError('Email is required');
hasErrors = true;
} else if (!validateEmail(email)) {
setEmailError('Please enter a valid email address');
hasErrors = true;
}
// Validate password
if (!password) {
setPasswordError('Password is required');
hasErrors = true;
} else {
const validation = validatePassword(password);
if (!validation.isValid) {
let errorMessage = 'Password must contain:\n';
if (!validation.hasMinLength) errorMessage += '• At least 8 characters\n';
if (!validation.hasUppercase) errorMessage += '• One uppercase letter\n';
if (!validation.hasLowercase) errorMessage += '• One lowercase letter\n';
if (!validation.hasSpecialChar) errorMessage += '• One special character\n';
setPasswordError(errorMessage.trim());
hasErrors = true;
}
}
// If validation passes, proceed with API call
if (!hasErrors) {
setIsLoading(true);
try {
const response = await fetch(API_ENDPOINTS.login, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: email.trim(),
password: password,
}),
});
// Debug: Log response details
console.log('Login response status:', response.status);
console.log('Login response headers:', response.headers);
// Get the raw response text first
const responseText = await response.text();
console.log('Login raw response text:', responseText);
// Try to parse as JSON
let data;
try {
data = JSON.parse(responseText);
console.log('Login parsed JSON:', data);
} catch (parseError) {
console.error('JSON parse error:', parseError);
console.log('Failed to parse this text as JSON:', responseText);
Alert.alert(
'Server Error',
'Server returned invalid response. Please check server configuration.',
[{ text: 'OK', style: 'default' }]
);
return;
}
if (data.success) {
// Login successful - check what tokens we got
console.log('Login successful - checking tokens...');
console.log('Has access_token:', !!data.access_token);
console.log('Has refresh_token:', !!data.refresh_token);
console.log('Has legacy token:', !!data.token);
setUser(data.user);
// Use access_token if available, fall back to token
const accessToken = data.access_token || data.token;
const refreshTokenValue = data.refresh_token;
if (refreshTokenValue) {
console.log('Using new refresh token system');
// Save both tokens
await saveAuthData(accessToken, refreshTokenValue, data.user, data.expires_in);
} else {
console.log('Using legacy single token system');
// Save single token only
await saveAuthDataLegacy(accessToken, data.user, data.expires_in);
}
// Save email for future logins
await saveCachedEmail(email.trim());
// Navigate to dashboard
setCurrentScreen('dashboard');
Alert.alert(
'Login Successful!',
`Welcome back, ${data.user.first_name}!\n\nUser ID: ${data.user.id}\nEmail: ${data.user.email}`,
[{ text: 'OK', style: 'default' }]
);
// Clear only the password, keep email cached
setPassword('');
} else {
// API returned an error
Alert.alert(
'Login Failed',
data.error || 'Invalid credentials. Please check your email and password.',
[{ text: 'OK', style: 'default' }]
);
}
} catch (error) {
// Network or other error
console.error('Login error:', error);
Alert.alert(
'Connection Error',
'Unable to connect to the server. Please check your connection and try again.',
[{ text: 'OK', style: 'default' }]
);
} finally {
setIsLoading(false);
}
}
};
const navigateToLogin = () => {
setCurrentScreen('login');
// Reset only password and errors, keep cached email
setPassword('');
setEmailError('');
setPasswordError('');
};
const navigateToWelcome = () => {
setCurrentScreen('welcome');
};
const handleLogout = async () => {
Alert.alert(
'Logout',
'Are you sure you want to logout?',
[
{ text: 'Cancel', style: 'cancel' },
{
text: 'Logout',
style: 'destructive',
onPress: async () => {
// Call logout API to revoke refresh token
if (refreshToken) {
try {
await fetch(API_ENDPOINTS.logout, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
refresh_token: refreshToken,
}),
});
console.log('Refresh token revoked on server');
} catch (error) {
console.log('Error revoking token on server:', error);
// Continue with local logout even if server logout fails
}
}
// Clear local auth data
await clearAuthData();
setCurrentScreen('welcome');
setProfileData(null);
Alert.alert('Logged Out', 'You have been logged out successfully.');
}
}
]
);
};
const fetchUserProfile = async () => {
try {
setIsLoading(true);
const response = await makeAuthenticatedRequest(API_ENDPOINTS.profile);
const data = await response.json();
if (data.success) {
setProfileData(data);
Alert.alert('Success', 'Profile data fetched successfully!');
} else {
setProfileData(null);
Alert.alert('Error', 'Failed to fetch profile data');
}
} catch (error) {
console.log('Error fetching profile:', error);
setProfileData(null);
Alert.alert('Error', 'Failed to fetch profile data');
} finally {
setIsLoading(false);
}
};
const backgroundStyle = {
backgroundColor: isDarkMode ? '#1a1a1a' : '#ffffff',
flex: 1,
};
const textColor = isDarkMode ? '#ffffff' : '#000000';
const subtextColor = isDarkMode ? '#cccccc' : '#666666';
const inputBackgroundColor = isDarkMode ? '#2a2a2a' : '#f5f5f5';
const inputBorderColor = isDarkMode ? '#444444' : '#dddddd';
// Dashboard Screen (authenticated)
if (currentScreen === 'dashboard' && authToken) {
return (
<SafeAreaView style={backgroundStyle}>
<StatusBar
barStyle={isDarkMode ? 'light-content' : 'dark-content'}
backgroundColor={backgroundStyle.backgroundColor}
/>
<View style={[styles.container, backgroundStyle]}>
<View style={styles.header}>
<Text style={[styles.title, { color: textColor }]}>
Dashboard
</Text>
<Text style={[styles.subtitle, { color: subtextColor }]}>
Welcome, {user?.first_name || 'User'}!
</Text>
</View>
<View style={styles.content}>
<View style={styles.userInfo}>
<Text style={[styles.infoTitle, { color: textColor }]}>User Information:</Text>
<Text style={[styles.infoText, { color: subtextColor }]}>
Email: {user?.email}
</Text>
<Text style={[styles.infoText, { color: subtextColor }]}>
Name: {user?.first_name} {user?.last_name}
</Text>
<Text style={[styles.infoText, { color: subtextColor }]}>
Token expires: {tokenExpiration ? new Date(tokenExpiration).toLocaleTimeString() : 'Unknown'}
</Text>
</View>
{profileData && (
<View style={styles.profileInfo}>
<Text style={[styles.infoTitle, { color: textColor }]}>Profile Data:</Text>
<Text style={[styles.infoText, { color: subtextColor }]}>
Last Login: {profileData.user?.last_login || 'N/A'}
</Text>
<Text style={[styles.infoText, { color: subtextColor }]}>
Account Created: {profileData.user?.created_at || 'N/A'}
</Text>
</View>
)}
</View>
<View style={styles.footer}>
<TouchableOpacity
style={[styles.button, styles.primaryButton]}
onPress={fetchUserProfile}
activeOpacity={0.8}
disabled={isLoading}
>
<Text style={styles.buttonText}>
{isLoading ? 'LOADING...' : 'FETCH PROFILE'}
</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.button, styles.secondaryButton]}
onPress={handleLogout}
activeOpacity={0.8}
>
<Text style={[styles.buttonText, styles.secondaryButtonText]}>LOGOUT</Text>
</TouchableOpacity>
</View>
</View>
</SafeAreaView>
);
}
// Welcome Screen
if (currentScreen === 'welcome') {
return (
<SafeAreaView style={backgroundStyle}>
<StatusBar
barStyle={isDarkMode ? 'light-content' : 'dark-content'}
backgroundColor={backgroundStyle.backgroundColor}
/>
<View style={[styles.container, backgroundStyle]}>
<View style={styles.header}>
<Text style={[styles.title, { color: textColor }]}>
Welcome to ReactAuthExample
</Text>
<Text style={[styles.subtitle, { color: subtextColor }]}>
Your React Native CLI Application
</Text>
</View>
<View style={styles.content}>
<Text style={[styles.description, { color: isDarkMode ? '#cccccc' : '#333333' }]}>
This is the starting point for your project. Choose an option below to continue.
</Text>
</View>
<View style={styles.footer}>
<TouchableOpacity
style={[styles.button, styles.primaryButton]}
onPress={navigateToLogin}
activeOpacity={0.8}
>
<Text style={styles.buttonText}>LOGIN</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.button, styles.secondaryButton]}
onPress={showAboutDialog}
activeOpacity={0.8}
>
<Text style={[styles.buttonText, styles.secondaryButtonText]}>ABOUT</Text>
</TouchableOpacity>
</View>
</View>
</SafeAreaView>
);
}
// Login Screen
return (
<SafeAreaView style={backgroundStyle}>
<StatusBar
barStyle={isDarkMode ? 'light-content' : 'dark-content'}
backgroundColor={backgroundStyle.backgroundColor}
/>
<KeyboardAvoidingView
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
style={{ flex: 1 }}
>
<ScrollView
style={[styles.container, backgroundStyle]}
contentContainerStyle={{ flexGrow: 1 }}
keyboardShouldPersistTaps="handled"
>
<View style={styles.loginHeader}>
<TouchableOpacity
style={styles.backButton}
onPress={navigateToWelcome}
activeOpacity={0.8}
>
<Text style={[styles.backButtonText, { color: '#007AFF' }]}>← Back</Text>
</TouchableOpacity>
<Text style={[styles.loginTitle, { color: textColor }]}>Login</Text>
<Text style={[styles.loginSubtitle, { color: subtextColor }]}>
Enter your credentials to continue
</Text>
</View>
<View style={styles.loginForm}>
<View style={styles.inputContainer}>
<Text style={[styles.inputLabel, { color: textColor }]}>Email</Text>
<TextInput
style={[
styles.input,
{
backgroundColor: inputBackgroundColor,
borderColor: emailError ? '#ff4444' : inputBorderColor,
color: textColor
}
]}
value={email}
onChangeText={(text) => {
setEmail(text);
if (emailError) setEmailError(''); // Clear error when user types
// Save email as user types (debounced by React's setState)
if (text.trim()) {
saveCachedEmail(text.trim());
}
}}
placeholder="Enter your email"
placeholderTextColor={subtextColor}
keyboardType="email-address"
autoCapitalize="none"
autoCorrect={false}
/>
{emailError ? <Text style={styles.errorText}>{emailError}</Text> : null}
</View>
<View style={styles.inputContainer}>
<Text style={[styles.inputLabel, { color: textColor }]}>Password</Text>
<View style={[
styles.passwordInputContainer,
{
backgroundColor: inputBackgroundColor,
borderColor: passwordError ? '#ff4444' : inputBorderColor,
}
]}>
<TextInput
style={[
styles.passwordInput,
{ color: textColor }
]}
value={password}
onChangeText={(text) => {
setPassword(text);
if (passwordError) setPasswordError(''); // Clear error when user types
}}
placeholder="Enter your password"
placeholderTextColor={subtextColor}
secureTextEntry={!showPassword}
autoCapitalize="none"
autoCorrect={false}
/>
<TouchableOpacity
style={styles.eyeIcon}
onPress={() => setShowPassword(!showPassword)}
activeOpacity={0.7}
>
<Text style={[styles.eyeIconText, { color: subtextColor }]}>
{showPassword ? '🙈' : '👁'}
</Text>
</TouchableOpacity>
</View>
{passwordError ? <Text style={styles.errorText}>{passwordError}</Text> : null}
</View>
<TouchableOpacity
style={[styles.button, styles.loginButton, isLoading && styles.disabledButton]}
onPress={handleLogin}
activeOpacity={0.8}
disabled={isLoading}
>
<Text style={styles.buttonText}>
{isLoading ? 'LOGGING IN...' : 'LOGIN'}
</Text>
</TouchableOpacity>
</View>
</ScrollView>
</KeyboardAvoidingView>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingHorizontal: 24,
paddingVertical: 20,
},
header: {
flex: 2,
justifyContent: 'center',
alignItems: 'center',
marginBottom: 40,
},
title: {
fontSize: 28,
fontWeight: 'bold',
textAlign: 'center',
marginBottom: 10,
},
subtitle: {
fontSize: 16,
textAlign: 'center',
fontWeight: '400',
},
content: {
flex: 2,
justifyContent: 'center',
paddingHorizontal: 20,
},
description: {
fontSize: 16,
lineHeight: 24,
textAlign: 'center',
marginBottom: 40,
},
footer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
gap: 15,
},
button: {
paddingHorizontal: 40,
paddingVertical: 15,
borderRadius: 25,
minWidth: 120,
elevation: 2,
shadowColor: '#000',
shadowOffset: {
width: 0,
height: 2,
},
shadowOpacity: 0.25,
shadowRadius: 3.84,
},
primaryButton: {
backgroundColor: '#007AFF',
},
secondaryButton: {
backgroundColor: 'transparent',
borderWidth: 2,
borderColor: '#007AFF',
elevation: 0,
shadowOpacity: 0,
},
buttonText: {
color: 'white',
fontSize: 18,
fontWeight: '600',
textAlign: 'center',
},
secondaryButtonText: {
color: '#007AFF',
},
// Login Screen Styles
loginHeader: {
paddingTop: 20,
paddingBottom: 40,
alignItems: 'center',
},
backButton: {
position: 'absolute',
left: 0,
top: 20,
padding: 10,
},
backButtonText: {
fontSize: 16,
fontWeight: '500',
},
loginTitle: {
fontSize: 32,
fontWeight: 'bold',
marginBottom: 8,
marginTop: 20,
},
loginSubtitle: {
fontSize: 16,
textAlign: 'center',
},
loginForm: {
flex: 1,
justifyContent: 'center',
paddingBottom: 50,
},
inputContainer: {
marginBottom: 20,
},
inputLabel: {
fontSize: 16,
fontWeight: '500',
marginBottom: 8,
},
input: {
borderWidth: 1,
borderRadius: 12,
paddingHorizontal: 16,
paddingVertical: 14,
fontSize: 16,
minHeight: 50,
},
errorText: {
color: '#ff4444',
fontSize: 14,
marginTop: 4,
lineHeight: 18,
},
loginButton: {
backgroundColor: '#007AFF',
marginTop: 30,
alignSelf: 'stretch',
minWidth: 'auto',
},
disabledButton: {
backgroundColor: '#cccccc',
opacity: 0.6,
},
passwordInputContainer: {
borderWidth: 1,
borderRadius: 12,
flexDirection: 'row',
alignItems: 'center',
minHeight: 50,
},
passwordInput: {
flex: 1,
paddingHorizontal: 16,
paddingVertical: 14,
fontSize: 16,
},
eyeIcon: {
paddingHorizontal: 12,
paddingVertical: 14,
justifyContent: 'center',
alignItems: 'center',
},
eyeIconText: {
fontSize: 20,
},
userInfo: {
marginBottom: 20,
padding: 20,
borderRadius: 12,
backgroundColor: 'rgba(0, 122, 255, 0.1)',
borderWidth: 1,
borderColor: 'rgba(0, 122, 255, 0.3)',
},
profileInfo: {
marginBottom: 20,
padding: 20,
borderRadius: 12,
backgroundColor: 'rgba(76, 217, 100, 0.1)',
borderWidth: 1,
borderColor: 'rgba(76, 217, 100, 0.3)',
},
infoTitle: {
fontSize: 18,
fontWeight: 'bold',
marginBottom: 10,
},
infoText: {
fontSize: 16,
marginBottom: 5,
lineHeight: 22,
},
});
export default App;