Skip to content

Commit

Permalink
fixing bug from blitz
Browse files Browse the repository at this point in the history
  • Loading branch information
avichaljadeja2002 committed Feb 5, 2025
1 parent 792e355 commit ab7d289
Show file tree
Hide file tree
Showing 6 changed files with 164 additions and 76 deletions.
6 changes: 3 additions & 3 deletions app/_layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,6 @@ const CustomTopBar = ({ navigation }: StackHeaderProps) => {
<TouchableOpacity onPress={() => navigation.navigate('mainMealTracker')}>
<Ionicons name="fast-food-outline" size={28} color="black" />
</TouchableOpacity>
<TouchableOpacity onPress={() => navigation.navigate('accountSetting')}>
<Ionicons name="person-circle-outline" size={28} color="black" />
</TouchableOpacity>
<TouchableOpacity onPress={() => navigation.navigate('mainFinanceTracker')}>
<Ionicons name="wallet-outline" size={28} color="black" />
</TouchableOpacity>
Expand All @@ -48,6 +45,9 @@ const CustomTopBar = ({ navigation }: StackHeaderProps) => {
<TouchableOpacity onPress={() => navigation.navigate('notes')}>
<Ionicons name="pencil-outline" size={28} color="black" />
</TouchableOpacity>
<TouchableOpacity onPress={() => navigation.navigate('accountSetting')}>
<Ionicons name="person-circle-outline" size={28} color="black" />
</TouchableOpacity>
</View>
);
};
Expand Down
78 changes: 66 additions & 12 deletions app/accountSetting.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,47 +14,63 @@ export default function AccountSetting() {
type Prop = StackNavigationProp<RootStackParamList, keyof RootStackParamList>;
const navigation = useNavigation<Prop>();

const [alertModal, setAlertModal] = useState({
visible: false,
header: '',
message: '',
});

const showAlert = (header: string, message: string) => {
setAlertModal({ visible: true, header, message });
};

const handleSave = async () => {
const token = await AsyncStorage.getItem('token'); // Retrieve token from AsyncStorage
const token = await AsyncStorage.getItem('token');

try {

if (!formData.name.trim()) {
showAlert('Invalid!', 'Name cannot be empty.');
return;
}

if (formData.age) {
const age = Number(formData.age);
if (isNaN(age) || age < 1 || age > 150) {
cLog(1, 'Invalid Age:', formData.age);
Alert.alert('Invalid Age', 'Please enter a valid age (1-150).');
showAlert('Invalid Age', 'Please enter a valid age (1-150).');
return;
}
}

const phoneRegex = /^[0-9]{7,15}$/;
if (formData.phone && !phoneRegex.test(formData.phone)) {
cLog(1, 'Invalid Phone:', formData.phone);
Alert.alert('Invalid Phone', 'Please enter a valid phone number (7-15 digits).');
showAlert('Invalid Phone', 'Please enter a valid phone number (7-15 digits).');
return;
}

await AsyncStorage.setItem('age', formData.age);
await AsyncStorage.setItem('phone', formData.phone);
await AsyncStorage.setItem('name', formData.name);
const response = await call(`/api/users/modify_user/${token}`, 'PUT', undefined, formData); // Send request with updated data
if (response.status == 401) {

const response = await call(`/api/users/modify_user/${token}`, 'PUT', undefined, formData);

if (response.status === 401) {
throw new Error(response.data.message);
} else {
Keyboard.dismiss();
Alert.alert('Success', 'Data saved successfully!');
showAlert('Success', 'Data saved successfully!');
cLog(1, 'Account Information saved successfully:', formData);
}
} catch (error) {
console.error('Error saving data:', error);
}
};


const handleChange = (name: string, value: string) => {
setFormData({ ...formData, [name]: value });
};

// Fetch local data from AsyncStorage
const getLocalValues = async () => {
try {
const name = await AsyncStorage.getItem('name');
Expand Down Expand Up @@ -159,6 +175,26 @@ export default function AccountSetting() {
</View>
</View>
</Modal>
<Modal
animationType="slide"
transparent={true}
visible={alertModal.visible}
onRequestClose={() => setAlertModal({ ...alertModal, visible: false })}
>
<View style={styles.centeredView}>
<View style={styles.modalView}>
<Text style={styles.modalHeader}>{alertModal.header}</Text>
<Text style={styles.modalMessage}>{alertModal.message}</Text>
<TouchableOpacity
style={[styles.button, styles.buttonClose]}
onPress={() => setAlertModal({ ...alertModal, visible: false })}
>
<Text style={styles.textStyle}>Close</Text>
</TouchableOpacity>
</View>
</View>
</Modal>

</View>
);
};
Expand Down Expand Up @@ -224,7 +260,7 @@ const styles = StyleSheet.create({
paddingHorizontal: 20,
backgroundColor: '#fff',
},
accountSetting:{
accountSetting: {
width: '100%',
flexDirection: 'row',
justifyContent: 'space-between',
Expand All @@ -241,7 +277,7 @@ const styles = StyleSheet.create({
fontSize: 14,
color: '#333',
textAlign: 'left',

},
textInput: {
height: 45,
Expand Down Expand Up @@ -280,4 +316,22 @@ const styles = StyleSheet.create({
fontSize: 16,
fontWeight: '600',
},
modalHeader: {
fontSize: 18,
fontWeight: 'bold',
marginBottom: 10,
textAlign: 'center',
},
modalMessage: {
fontSize: 14,
textAlign: 'center',
marginBottom: 20,
},
buttonClose: {
backgroundColor: "#2196F3",
paddingVertical: 10,
paddingHorizontal: 20,
borderRadius: 10,
},

});
3 changes: 2 additions & 1 deletion app/genericAddViewEventPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ const GenericAddViewPageForm: React.FC<GenericEventPageProps> = ({ title, initia
event_time: formData.event_time?.toTimeString().split(' ')[0],
repeating: Boolean(formData.repeat_timeline && formData.repeat_timeline),
repeat_timeline: formData.repeat_timeline,
ingredients: formData.ingredients?.join(',')
ingredients: formData.ingredients?.join(','),
money: formData.money
};
cLog(1, formattedData);
try {
Expand Down
68 changes: 41 additions & 27 deletions app/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,23 +26,23 @@ export default function AuthScreen() {
webClientId: process.env.EXPO_PUBLIC_CLIENT_ID,
redirectUri: 'http://localhost:8081',
});


useEffect(() => {
console.log("Google Auth Response:", response);
console.log("Google Auth Response:", response);

if (response?.type === 'success' && response.authentication) {
const idToken = response.authentication.accessToken;
const idToken = response.authentication.accessToken;
console.log(idToken)
if (idToken) {
if (idToken) {
handleGoogleLoginSuccess(idToken);
}
} else if (response?.type === 'error') {
console.error("Google login failed:", response);
Alert.alert("Google Login Failed", "Please try again.");
}
}, [response]);


const handleAuthRequest = async () => {
const url = isLogin ? '/api/users/login' : '/api/users/register';
Expand Down Expand Up @@ -81,25 +81,25 @@ export default function AuthScreen() {
const handleGoogleLoginSuccess = async (accessToken: string) => {
try {
console.log("Access Token = ", accessToken);

// Fetch user info from Google API
const userInfoResponse = await fetch("https://www.googleapis.com/oauth2/v3/userinfo", {
headers: { Authorization: `Bearer ${accessToken}` },
});

const userInfo = await userInfoResponse.json();
console.log("Google User Info:", userInfo);

const { email, name } = userInfo;

const response = await call('/api/users/google-login', 'POST', undefined, { email, name });

if (response.status === 200) {
const { token } = response.data;

await AsyncStorage.setItem('token', token);
await AsyncStorage.setItem('isLoggedIn', 'true');

Alert.alert('Success', 'Logged in with Google successfully!');
navigation.navigate('mainPage');
}
Expand All @@ -114,41 +114,57 @@ export default function AuthScreen() {
Alert.alert("Google Sign-In", "Google login is not ready yet. Please try again.");
return;
}

const result = await promptAsync();
console.log("Google Login Result:", result); // Debugging

if (result?.type === 'success' && result.authentication) {
const { idToken } = result.authentication;
console.log("ID Token from Google:", idToken);

if (idToken) {
handleGoogleLoginSuccess(idToken);
}
} else {
Alert.alert("Google Login Failed", "Authentication was not completed.");
}
};

const verifyLoginStatus = async () => {
const isLoggedIn = await AsyncStorage.getItem('isLoggedIn');
const token = await AsyncStorage.getItem('token');

cLog(1, token);
if (isLoggedIn === 'true' && token) {
cLog(1, `User is logged in with Token: ${token}`);
navigation.navigate('mainPage');
}
};

useEffect(() => {
verifyLoginStatus();
}, []);

return (
<View style={styles.authPage}>
<Text style={styles.headerText}>{isLogin ? 'Login' : 'Sign Up'}</Text>

<View style={styles.toggleContainer}>
<TouchableOpacity
style={[styles.toggleButton, isLogin && styles.toggleActive]}
onPress={() => setIsLogin(true)}
>
<Text style={[styles.toggleButtonText, isLogin && styles.toggleActiveText]}>Sign In</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.toggleButton, !isLogin && styles.toggleActive]}
onPress={() => setIsLogin(false)}
>
<Text style={[styles.toggleButtonText, !isLogin && styles.toggleActiveText]}>Sign Up</Text>
</TouchableOpacity>
</View>

<View style={{ height: "2%" }}></View>

<Text style={[styles.authPageNonheaderText, { textAlign: 'left', alignSelf: 'flex-start' }]}>
Email
</Text>
Expand All @@ -158,6 +174,7 @@ export default function AuthScreen() {
autoCapitalize="none"
onChangeText={(text) => setCredentials({ ...credentials, username: text })}
/>

<Text style={[styles.authPageNonheaderText, { textAlign: 'left', alignSelf: 'flex-start' }]}>
Password
</Text>
Expand All @@ -167,16 +184,13 @@ export default function AuthScreen() {
secureTextEntry
onChangeText={(text) => setCredentials({ ...credentials, password: text })}
/>

<TouchableOpacity style={styles.authButton} onPress={handleAuthRequest}>
<Text style={styles.authButtonText}>{isLogin ? 'Login' : 'Sign Up'}</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => setIsLogin(!isLogin)}>
<Text style={styles.switchText}>
{isLogin ? "Don't have an account? Sign Up" : 'Already have an account? Login'}
</Text>
<Text style={styles.authButtonText}>{isLogin ? 'Log In' : 'Sign Up'}</Text>
</TouchableOpacity>

<TouchableOpacity style={styles.googleButton} onPress={handleGoogleLogin}>
<Text style={styles.googleButtonText}>Sign in with Google</Text>
<Text style={styles.googleButtonText}>{isLogin ? 'Login with google' : 'Sign Up with google'}</Text>
</TouchableOpacity>
</View>
);
Expand Down
Loading

0 comments on commit ab7d289

Please sign in to comment.