Skip to content

Commit

Permalink
eslint fixing
Browse files Browse the repository at this point in the history
  • Loading branch information
jasmineguru committed Dec 14, 2023
1 parent 4e6838d commit 6bbb337
Show file tree
Hide file tree
Showing 5 changed files with 111 additions and 55 deletions.
20 changes: 20 additions & 0 deletions backend/routes/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,3 +139,23 @@ def update_user_email(uid: str) -> Response:
return jsonify({"user": item})
except CarbonTrackError as e:
abort(code=400, description=f"{e}")

@users.route("/user/update_name/<user_id>", methods=["PATCH"])
@carbon_auth.auth.login_required
def update_user_name(user_id: str) -> Response:
try:
new_name = request.get_json().get("newName", "")

query = {"uid": user_id}

current_user = carbon_auth.auth.current_user()

CarbonTrackDB.users_coll.update_one(query, {"$set": {"full_name": new_name}})

item = CarbonTrackDB.users_coll.find_one(query)

item = User.from_json(item).to_json()

return jsonify({"user": item}), 200
except CarbonTrackError as e:
abort(code=400, description=f"{e}")
15 changes: 14 additions & 1 deletion frontend/src/APIs/UsersAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ export const UsersAPI = {

// Make the request to update the email with the new token
const res = await FLASK_HTTPS.patch(
routeName + `/user/update_email/${userId.toHexString()}`,
routeName + `/user/update_email/${firebaseUser.uid.toString()}`,
{ email },
{
headers: {
Expand All @@ -128,4 +128,17 @@ export const UsersAPI = {
return undefined;
}
},
updateUserName: async (user: User, newName: string) => {
try {
const res = await FLASK_HTTPS.patch(
routeName + `/user/update_name/${user.uid.toString()}`,
{ newName },
);

return res.data.user as User;
} catch (error) {
console.error('UsersAPI(frontend): updateUserEmailError:', error);
return undefined;
}
}
};
95 changes: 52 additions & 43 deletions frontend/src/screens/settings/updatePassword.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import { useNavigation } from '@react-navigation/native';
import Ionicons from '@expo/vector-icons/Ionicons';
import { useFonts } from 'expo-font';
import firebaseService from '../../utilities/firebase';
import { type User } from '../../models/User';
import {
onAuthStateChanged,
getAuth,
Expand All @@ -26,65 +25,76 @@ import {
export type StackNavigation = StackNavigationProp<RootStackParamList>;

export default function UpdateProfileScreen(): JSX.Element {

const navigation = useNavigation<StackNavigation>();
const [loaded] = useFonts({
Montserrat: require('../../../assets/fonts/MontserratThinRegular.ttf'),
Josefin: require('../../../assets/fonts/JosefinSansThinRegular.ttf'),
});
const [userid, setUserid] = useState<string>('');
const [rerenderKey, setRerenderKey] = useState<number>(0);
const [loggedUser, setLoggedUser] = useState<User | undefined>(undefined);
const [newPass, setNewPass] = useState<string | undefined>('');

const auth = getAuth();
onAuthStateChanged(auth, (user) => {
if (user === null) {
navigation.navigate('LogIn');
}
});
const [newPass, setNewPass] = useState<string | undefined>('');

useEffect(() => {
const fetchUserData = async (): Promise<void> => {
const user = await firebaseService.getFirebaseUser();
setUserid(user?.uid ?? '');
const checkAuthState = async (): Promise<void> => {
const currentUser = await firebaseService.getFirebaseUser();
if (currentUser === null) {
navigation.navigate('LogIn');
}
};
void fetchUserData();
}, [rerenderKey]);

const handleUpdatePassword = async (): Promise<void> => {
const unsubscribe = onAuthStateChanged(getAuth(), (currentUser) => {
if (currentUser === null) {
navigation.navigate('LogIn');
} else {
void checkAuthState();
}
});

return () => {
unsubscribe(); // Cleanup on component unmount
};
}, [navigation]);


const handleUpdatePassword = async ():Promise<void> => {
try {
const user = await firebaseService.getFirebaseUser();
if (user != null) {
if (newPass != null && user.email != null){
if (newPass != null && user.email != null) {
// get user password to reauth
const userCreds = await promptUserForCredentials();
if (userCreds != null){
const creds = EmailAuthProvider.credential(user.email, userCreds.password);
await reauthenticateWithCredential(user, creds)
.then( async (result) => {
await updatePassword(user, newPass)
.then(() => alert('Password reset email has be sent. Please check your inbox for next steps. You will now be logged out.'))
.catch((error: any) => console.log('update password after alert error:', error));
console.log('Firebase (frontend): Update password sucess (maybay)')

await firebaseService.signOutUser();
navigation.navigate('LogIn');
// await sendPasswordResetEmail(auth, user.email)
// .then(() => alert('Password reset email has be sent. Please check your inbox for next steps.'))
// .catch((error: any) => console.log('Password email error:', error))
if (userCreds != null) {
const creds = EmailAuthProvider.credential(user.email, userCreds.password);
// reauth user
try {
await reauthenticateWithCredential(user, creds);

// after reauthing, update password
try {
await updatePassword(user, newPass);
alert('Password reset email has been sent. Please check your inbox for next steps. You will now be logged out.');
console.log('Firebase (frontend): Update password success (maybe)');
// sign out user after changing password
await firebaseService.signOutUser();
navigation.navigate('LogIn');
} catch (updateError: any) {
console.error('Updating password error:', updateError);
if (updateError.code === "auth/weak-password") {
Alert.alert('Invalid Password', 'Please make sure your password is strong enough.');
}
}
);
} catch (reauthError: any) {
Alert.alert('Reauthentification Error', 'An error occured trying to reauthorize your account. Please try again.');
console.error('Reauthenticating user error:', reauthError);
}
}

}



}
} catch (error: any) {
// Log any errors
console.error('Error updating email in Update Password screen: ', error);
console.error('Error handling password update: ', error);
}
return await Promise.resolve();
};


const promptUserForCredentials = async (): Promise<{ password: string } | null> => {
return await new Promise((resolve) => {
Expand Down Expand Up @@ -123,15 +133,14 @@ export default function UpdateProfileScreen(): JSX.Element {
</View>
<View style={styles.profileContainer}>
<View style={styles.textInputBox}>
<Text style={styles.label}>Name</Text>
<Text style={styles.label}>New Password:</Text>
<TextInput
placeholder="New Password"
style={styles.textInput}
onChangeText={(text) => setNewPass(text)}
/>
</View>
<TouchableOpacity style={styles.saveButton} onPress={handleUpdatePassword} >
{/* f onPress={handleUpdatePassword} */}
<TouchableOpacity style={styles.saveButton} onPress={() => { void handleUpdatePassword()}}>
<Text style={styles.saveButtonText}> Update Password </Text>
</TouchableOpacity>
</View>
Expand Down
35 changes: 25 additions & 10 deletions frontend/src/screens/settings/updateProfile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import {
TouchableOpacity,
Image,
TextInput,
Modal,
Alert,
} from 'react-native';
import Colors from '../../../assets/colorConstants';
Expand Down Expand Up @@ -84,6 +83,7 @@ export default function UpdateProfileScreen(): JSX.Element {
// email update
await verifyBeforeUpdateEmail(user, newEmail);

// TODO: when Error (auth/missing-new-email).] --make alert (email up to date)
Alert.alert(
'A verification email has been sent to your new! Please verify it and login again.'
);
Expand Down Expand Up @@ -121,6 +121,17 @@ export default function UpdateProfileScreen(): JSX.Element {
});
};

const handleNewName = async (): Promise<void> => {
if (newName != null && loggedUser != null) {
const updatedUser = await UsersAPI.updateUserName(loggedUser, newName);

if (updatedUser != null) {
setLoggedUser(updatedUser);
console.log(loggedUser.full_name)
}
}
}

const handleProfilePictureUpload = async (): Promise<void> => {
try {
const result: ImagePickerResult = await launchImageLibraryAsync({
Expand Down Expand Up @@ -154,37 +165,40 @@ export default function UpdateProfileScreen(): JSX.Element {
</View>
<View style={styles.profileContainer}>
<View>
<Image source={{ uri: photoURL }} style={styles.profilePicture} />
<Image source={{ uri: photoURL ?? '' }} style={styles.profilePicture} />
<View style={styles.semiCircle}>
<TouchableOpacity onPress={handleProfilePictureUpload}>
<TouchableOpacity onPress={() => {void handleProfilePictureUpload}}>
<Text style={styles.editPhotoText}> Edit Photo </Text>
</TouchableOpacity>
</View>
</View>

<View style={styles.textInputBox}>
<Text style={styles.label}>Name</Text>
<Text style={styles.label}>New Name:</Text>
<TextInput
placeholder="new name"
placeholder="My New Name"
defaultValue={loggedUser?.full_name}
style={styles.textInput}
onChangeText={(text) => setNewName(text)}
/>

<Text style={styles.label}>Email</Text>
<Text style={styles.label}>New Email:</Text>
<TextInput
placeholder="new email"
placeholder="mynew@email.com"
defaultValue={loggedUser?.email}
style={styles.textInput}
onChangeText={(text) => setNewEmail(text)}
/>
</View>
<TouchableOpacity style={styles.saveButton} onPress={handleUpdateEmail}>
<Text style={styles.saveButtonText}> Update Profile </Text>
<TouchableOpacity style={styles.saveButton} onPress={() => { void handleUpdateEmail()}}>
<Text style={styles.saveButtonText}> Update Email </Text>
</TouchableOpacity>
<TouchableOpacity style={styles.saveButton} onPress={() => {void handleNewName()}} >
<Text style={styles.saveButtonText}> Update Name </Text>
</TouchableOpacity>
</View>
</ScrollView>
);
);
}
const styles = StyleSheet.create({
container: {
Expand Down Expand Up @@ -275,6 +289,7 @@ const styles = StyleSheet.create({
borderRadius: 5,
alignSelf: 'center',
top: '20%',
padding: 10,
},
saveButtonText: {
color: Colors.LIGHTFGREEN,
Expand Down
1 change: 0 additions & 1 deletion frontend/src/utilities/firebase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import {
updateEmail,
type User,
type UserCredential,
updatePassword,
} from 'firebase/auth';
import ReactNativeAsyncStorage from '@react-native-async-storage/async-storage';
import { getStorage, ref as storageRef, uploadBytes, getDownloadURL } from 'firebase/storage';
Expand Down

0 comments on commit 6bbb337

Please sign in to comment.