From 7db66226ed21ebf3152210af3d0f9a2f5aa243ea Mon Sep 17 00:00:00 2001 From: aman190 Date: Mon, 13 Mar 2023 11:57:02 +0530 Subject: [PATCH 1/6] Fix login/sign with email & password --- app/screens/LoginScreen/loginScreen.js | 76 ++++++++----------- app/screens/SignupScreen/signupScreen.js | 95 +++++++++++------------- 2 files changed, 74 insertions(+), 97 deletions(-) diff --git a/app/screens/LoginScreen/loginScreen.js b/app/screens/LoginScreen/loginScreen.js index 319f953..fe38954 100644 --- a/app/screens/LoginScreen/loginScreen.js +++ b/app/screens/LoginScreen/loginScreen.js @@ -10,62 +10,56 @@ import { ScrollView, } from "react-native"; import { AccessToken, LoginManager } from "react-native-fbsdk"; -import { f, auth } from "../../../config/config.js"; +import { app, auth, db } from "../../../config/config.js"; +import { signInWithEmailAndPassword, onAuthStateChanged } from "firebase/auth"; import * as EmailValidator from "email-validator"; -import styles from "./style"; import { SocialIcon } from "react-native-elements"; +import styles from "./style"; + export default class LoginScreen extends Component { constructor(props) { super(props); this.state = { email: "", - Password: "", + password: "", }; } componentDidMount() { var that = this; - - auth.onAuthStateChanged(function (user) { + onAuthStateChanged(auth, function (user) { if (user) { that.redirectUser(); } }); } - login() { - let email = this.state.email; - let password = this.state.Password; - - let { navigate } = this.props.navigation; - - auth - .signInWithEmailAndPassword(email, password) - .then(function (data) { - navigate("App"); - }) - .catch(function (error) { - var errorMessage = error.message; - alert(errorMessage.toString()); - }); - } - redirectUser() { const { navigate } = this.props.navigation; navigate("App"); } - _signInAsync = async () => { - if (EmailValidator.validate(this.state.email) === true) { - if (this.state.Pasword != "") { - this.login(); - } else { - alert("Enter the password"); - } + async login() { + try { + let email = this.state.email; + let password = this.state.password; + + const res = await signInWithEmailAndPassword(auth, email, password); + console.log("User signed in successfully!"); + } catch (error) { + alert(error.message.toString()); + } + } + + async _signInAsync() { + if (!EmailValidator.validate(this.state.email)) { + alert("Please enter a valid email!"); + } else if (this.state.password == "") { + alert("Enter your password!"); } else { - alert("Please enter A Valid Email"); + this.login(); } - }; + } onPressLogin() { LoginManager.logInWithReadPermissions(["public_profile", "email"]).then( @@ -124,17 +118,9 @@ export default class LoginScreen extends Component { .update({ ...userData, ...defaults }); }; - _signInAsync = async () => { - if (EmailValidator.validate(this.state.email) === true) { - if (this.state.Pasword != "") { - this.login(); - } else { - alert("Enter the password"); - } - } else { - alert("Please enter A Valid Email"); - } - }; + handleInput(input, text) { + this.setState(prevState => ({ ...prevState, [input]: text })); + } render() { return ( @@ -151,7 +137,7 @@ export default class LoginScreen extends Component { keyboardType="email-address" placeholderTextColor="rgba(255,255,255,0.7)" style={styles.input} - onChangeText={text => this.setState({ email: text })} + onChangeText={text => this.handleInput("email", text)} ref={input => { this.textInput = input; }} @@ -161,14 +147,14 @@ export default class LoginScreen extends Component { secureTextEntry={true} placeholderTextColor="rgba(255,255,255,0.7)" style={styles.input} - onChangeText={text => this.setState({ Password: text })} + onChangeText={text => this.handleInput("password", text)} ref={input => { this.textInput = input; }} /> - + Sign In diff --git a/app/screens/SignupScreen/signupScreen.js b/app/screens/SignupScreen/signupScreen.js index e66cfee..6b8c619 100644 --- a/app/screens/SignupScreen/signupScreen.js +++ b/app/screens/SignupScreen/signupScreen.js @@ -12,7 +12,8 @@ import { import styles from "./style"; import * as EmailValidator from "email-validator"; import { AccessToken, LoginManager } from "react-native-fbsdk"; -import { f, auth } from "../../../config/config.js"; +import { auth, db } from "../../../config/config.js"; +import { createUserWithEmailAndPassword, onAuthStateChanged, updateProfile } from "firebase/auth"; import { SocialIcon } from "react-native-elements"; export default class SignUpScreen extends Component { @@ -21,14 +22,14 @@ export default class SignUpScreen extends Component { this.state = { email: "", name: "", - Password: "", - ConfirmPassword: "", + password: "", + confirmPassword: "", }; } componentDidMount() { var that = this; - auth.onAuthStateChanged(function (user) { + onAuthStateChanged(auth, function (user) { if (user) { that.redirectUser(); } @@ -40,6 +41,35 @@ export default class SignUpScreen extends Component { navigate("App"); } + async signup() { + try { + let name = this.state.name; + let email = this.state.email; + let password = this.state.password; + + const { user } = await createUserWithEmailAndPassword(auth, email, password); + await updateProfile(user, { displayName: name }); + console.log("\n\nUpdated user data successfully! : ", auth.currentUser); + } catch (error) { + console.log(error); + alert(error.message.toString()); + } + } + + async _signUpAsync() { + if (this.state.name == "") { + alert("Please enter your name!"); + } else if (!EmailValidator.validate(this.state.email)) { + alert("Please enter a valid email!"); + } else if (this.state.password == "") { + alert("Please enter a password!"); + } else if (this.state.password != this.state.confirmPassword) { + alert("Password and Confirm password must be same"); + } else { + this.signup(); + } + } + onPressLogin() { LoginManager.logInWithReadPermissions(["public_profile", "email"]).then( result => this._handleCallBack(result), @@ -97,6 +127,10 @@ export default class SignUpScreen extends Component { .update({ ...userData, ...defaults }); }; + handleInput(input, text) { + this.setState(prevState => ({ ...prevState, [input]: text })); + } + render() { return ( @@ -111,32 +145,32 @@ export default class SignUpScreen extends Component { placeholder="Name" placeholderTextColor="rgba(255,255,255,0.7)" style={styles.input} - onChangeText={text => this.setState({ name: text })} + onChangeText={text => this.handleInput("name", text)} /> this.setState({ email: text })} + onChangeText={text => this.handleInput("email", text)} /> this.setState({ Password: text })} + onChangeText={text => this.handleInput("password", text)} /> this.setState({ ConfirmPassword: text })} + onChangeText={text => this.handleInput("confirmPassword", text)} /> - + Sign Up @@ -166,47 +200,4 @@ export default class SignUpScreen extends Component { ); } - register() { - let email = this.state.email; - let name = this.state.name; - let password = this.state.Password; - - const { navigate } = this.props.navigation; - - auth - .createUserWithEmailAndPassword(email, password) - .then(function (data) { - data.user - .updateProfile({ - displayName: name, - }) - .then( - function () { - console.log("Updated User Data.."); - }, - function (error) { - console.log("Error Updating User Data.." + error); - } - ); - alert("Welcome to Go Social!"); - navigate("App"); - }) - .catch(function (error) { - var errorMessage = error.message; - console.log("Error = " + errorMessage); - alert(errorMessage); - }); - } - - signUpAsync = async () => { - if (EmailValidator.validate(this.state.email) === true) { - if (this.state.Password === this.state.ConfirmPassword) { - this.register(); - } else { - alert("password Missmatch"); - } - } else { - alert("Please enter A Valid Email"); - } - }; } From 26c2bf34cfd553d16170831cc68ffe57abf693eb Mon Sep 17 00:00:00 2001 From: aman190 Date: Mon, 13 Mar 2023 17:10:22 +0530 Subject: [PATCH 2/6] Fix signin/signup with facebook --- android/app/build.gradle | 1 + android/app/src/main/AndroidManifest.xml | 19 ++- android/app/src/main/res/values/strings.xml | 4 +- app/screens/LoginScreen/loginScreen.js | 117 ++++++++---------- app/screens/SignupScreen/signupScreen.js | 127 +++++++++----------- package.json | 2 +- 6 files changed, 130 insertions(+), 140 deletions(-) diff --git a/android/app/build.gradle b/android/app/build.gradle index 0845c3b..59e3429 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -152,6 +152,7 @@ dependencies { // The version of react-native is set by the React Native Gradle Plugin implementation("com.facebook.react:react-android") implementation("androidx.swiperefreshlayout:swiperefreshlayout:1.0.0") + implementation 'com.facebook.android:facebook-android-sdk:11.1.0' // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:31.2.3') diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index c57e0f5..0dcae1a 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -1,10 +1,12 @@ - + + + + + + + + + + + + + diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index 284c98a..b001aeb 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -1,4 +1,6 @@ Go_social - 2349388348405699 + 222891166977339 + fb1234 + PLACE_YOUR_CLIENT_TOKEN_HERE diff --git a/app/screens/LoginScreen/loginScreen.js b/app/screens/LoginScreen/loginScreen.js index fe38954..19382d5 100644 --- a/app/screens/LoginScreen/loginScreen.js +++ b/app/screens/LoginScreen/loginScreen.js @@ -9,9 +9,15 @@ import { KeyboardAvoidingView, ScrollView, } from "react-native"; -import { AccessToken, LoginManager } from "react-native-fbsdk"; +import { LoginManager, AccessToken } from "react-native-fbsdk-next"; import { app, auth, db } from "../../../config/config.js"; -import { signInWithEmailAndPassword, onAuthStateChanged } from "firebase/auth"; +import { + signInWithEmailAndPassword, + onAuthStateChanged, + signInWithCredential, + FacebookAuthProvider, +} from "firebase/auth"; +import { ref, set, orderByChild, equalTo, once } from "firebase/database"; import * as EmailValidator from "email-validator"; import { SocialIcon } from "react-native-elements"; import styles from "./style"; @@ -39,85 +45,64 @@ export default class LoginScreen extends Component { navigate("App"); } + // Validate the user's email and password + async _signInAsync() { + if (!EmailValidator.validate(this.state.email)) { + alert("Please enter a valid email!"); + } else if (this.state.password == "") { + alert("Enter your password!"); + } else { + this.login(); + } + } + + // Signin with email and password async login() { try { let email = this.state.email; let password = this.state.password; const res = await signInWithEmailAndPassword(auth, email, password); - console.log("User signed in successfully!"); } catch (error) { alert(error.message.toString()); } } - async _signInAsync() { - if (!EmailValidator.validate(this.state.email)) { - alert("Please enter a valid email!"); - } else if (this.state.password == "") { - alert("Enter your password!"); - } else { - this.login(); - } - } - - onPressLogin() { - LoginManager.logInWithReadPermissions(["public_profile", "email"]).then( - result => this._handleCallBack(result), - function (error) { - alert("Login fail with error: " + error); + // Signin user with facebook account + async _fbSignInAsync() { + try { + const result = await LoginManager.logInWithPermissions(["public_profile", "email"]); + if (!result.isCancelled) { + // Get the user's access token + const data = await AccessToken.getCurrentAccessToken(); + + // Use the user's access token to authenticate with Firebase Authentication + const credential = FacebookAuthProvider.credential(data.accessToken); + const { user } = await signInWithCredential(auth, credential); + + const response = await fetch( + `https://graph.facebook.com/v2.8/me?fields=id,first_name,last_name,email,birthday&access_token=${data.accessToken}` + ); + const userData = await response.json(); + const photoURL = `https://graph.facebook.com/${userData.id}/picture?height=120`; + this.createUser(user.uid, userData, data.accessToken, photoURL); } - ); + } catch (error) { + alert(error.message.toString()); + } } - _handleCallBack(result) { - let _this = this; - if (result.isCancelled) { - alert("Login cancelled"); - } else { - AccessToken.getCurrentAccessToken().then(data => { - const token = data.accessToken; - fetch( - "https://graph.facebook.com/v2.8/me?fields=id,first_name,last_name,gender,birthday&access_token=" + - token - ) - .then(response => response.json()) - .then(json => { - const imageSize = 120; - const facebookID = json.id; - const fbImage = `https://graph.facebook.com/${facebookID}/picture?height=${imageSize}`; - this.authenticate(data.accessToken).then(function (result) { - const { uid } = result; - _this.createUser(uid, json, token, fbImage); - }); - }) - .catch(function (err) { - console.log(err); - }); - }); + // Create user + async createUser(uid, userData, token, photoURL) { + try { + const defaults = { uid, token, photoURL, Range: [20, 30] }; + const usersRef = ref(db, "users/" + uid); + set(usersRef, { ...userData, ...defaults }); + } catch (error) { + alert(error.message.toString()); } } - authenticate = token => { - const provider = auth.FacebookAuthProvider; - const credential = provider.credential(token); - let ret = auth.signInWithCredential(credential); - return ret; - }; - - createUser = (uid, userData, token, dp) => { - const defaults = { - uid, - token, - dp, - ageRange: [20, 30], - }; - f.database() - .ref("users") - .child(uid) - .update({ ...userData, ...defaults }); - }; - handleInput(input, text) { this.setState(prevState => ({ ...prevState, [input]: text })); } @@ -162,9 +147,9 @@ export default class LoginScreen extends Component { Forgot Password? - + this._handleCallBack(result), - function (error) { - alert("Login fail with error: " + error); - } - ); - } + // Sign up with email and password + async signup() { + try { + let name = this.state.name; + let email = this.state.email; + let password = this.state.password; - _handleCallBack(result) { - let _this = this; - if (result.isCancelled) { - alert("Login cancelled"); - } else { - AccessToken.getCurrentAccessToken().then(data => { - const token = data.accessToken; - fetch( - "https://graph.facebook.com/v2.8/me?fields=id,first_name,last_name,gender,birthday&access_token=" + - token - ) - .then(response => response.json()) - .then(json => { - const imageSize = 120; - const facebookID = json.id; - const fbImage = `https://graph.facebook.com/${facebookID}/picture?height=${imageSize}`; - this.authenticate(data.accessToken).then(function (result) { - const { uid } = result; - _this.createUser(uid, json, token, fbImage); - }); - }) - .catch(function (err) { - console.log(err); - }); - }); + const { user } = await createUserWithEmailAndPassword(auth, email, password); + await updateProfile(user, { displayName: name }); + } catch (error) { + alert(error.message.toString()); } } - authenticate = token => { - const provider = auth.FacebookAuthProvider; - const credential = provider.credential(token); - let ret = auth.signInWithCredential(credential); - return ret; - }; + // Signup user with facebook account + async _fbSignUpAsync() { + try { + const result = await LoginManager.logInWithPermissions(["public_profile", "email"]); + if (!result.isCancelled) { + // Get the user's access token + const data = await AccessToken.getCurrentAccessToken(); - createUser = (uid, userData, token, dp) => { - const defaults = { - uid, - token, - dp, - ageRange: [20, 30], - }; - f.database() - .ref("users") - .child(uid) - .update({ ...userData, ...defaults }); - }; + // Use the user's access token to authenticate with Firebase Authentication + const credential = FacebookAuthProvider.credential(data.accessToken); + const { user } = await signInWithCredential(auth, credential); + + const response = await fetch( + `https://graph.facebook.com/v2.8/me?fields=id,first_name,last_name,email,birthday&access_token=${data.accessToken}` + ); + const userData = await response.json(); + const photoURL = `https://graph.facebook.com/${userData.id}/picture?height=120`; + this.createUser(user.uid, userData, data.accessToken, photoURL); + } + } catch (error) { + alert(error.message.toString()); + } + } + + // Create user + async createUser(uid, userData, token, photoURL) { + try { + const defaults = { uid, token, photoURL, Range: [20, 30] }; + const usersRef = ref(db, "users/" + uid); + set(usersRef, { ...userData, ...defaults }); + } catch (error) { + alert(error.message.toString()); + } + } handleInput(input, text) { this.setState(prevState => ({ ...prevState, [input]: text })); @@ -178,9 +163,9 @@ export default class SignUpScreen extends Component { or - + Date: Sat, 18 Mar 2023 09:25:24 +0530 Subject: [PATCH 3/6] Update config.example file with firebase v9 config --- app/screens/LoginScreen/loginScreen.js | 2 +- app/screens/SignupScreen/signupScreen.js | 2 +- config/config.example.js | 22 +++++++++++++--------- 3 files changed, 15 insertions(+), 11 deletions(-) diff --git a/app/screens/LoginScreen/loginScreen.js b/app/screens/LoginScreen/loginScreen.js index 19382d5..d8dd76c 100644 --- a/app/screens/LoginScreen/loginScreen.js +++ b/app/screens/LoginScreen/loginScreen.js @@ -17,7 +17,7 @@ import { signInWithCredential, FacebookAuthProvider, } from "firebase/auth"; -import { ref, set, orderByChild, equalTo, once } from "firebase/database"; +import { ref, set } from "firebase/database"; import * as EmailValidator from "email-validator"; import { SocialIcon } from "react-native-elements"; import styles from "./style"; diff --git a/app/screens/SignupScreen/signupScreen.js b/app/screens/SignupScreen/signupScreen.js index 1382d20..c18e569 100644 --- a/app/screens/SignupScreen/signupScreen.js +++ b/app/screens/SignupScreen/signupScreen.js @@ -20,7 +20,7 @@ import { signInWithCredential, FacebookAuthProvider, } from "firebase/auth"; -import { ref, set, orderByChild, equalTo, once } from "firebase/database"; +import { ref, set} from "firebase/database"; import { SocialIcon } from "react-native-elements"; export default class SignUpScreen extends Component { diff --git a/config/config.example.js b/config/config.example.js index b5b9722..dd7cb3a 100644 --- a/config/config.example.js +++ b/config/config.example.js @@ -1,19 +1,23 @@ -import firebase from "firebase"; +import { initializeApp } from "firebase/app"; +import { getAuth } from "firebase/auth"; +import { getStorage } from "firebase/storage"; +import { getDatabase } from "firebase/database"; -var config = { +const firebaseConfig = { apiKey: "", authDomain: "", databaseURL: "", projectId: "", storageBucket: "", messagingSenderId: "", + appId: "", + measurementId: "", }; -firebase.initializeApp(config); -var MAP_API_KEY = ""; +const app = initializeApp(firebaseConfig); +const auth = getAuth(app); +const storage = getStorage(app); +const db = getDatabase(app); +const MAP_API = ""; -export const f = firebase; -export const database = firebase.database(); -export const auth = firebase.auth(); -export const storage = firebase.storage(); -export const MAP_API = MAP_API_KEY; +export { app, auth, storage, db, MAP_API }; From b307f2f11ec2963abd9a74f9b2c6ba1a26d9c10d Mon Sep 17 00:00:00 2001 From: aman190 Date: Fri, 24 Mar 2023 08:31:06 +0530 Subject: [PATCH 4/6] Update readme for latest fbsdk config --- README.md | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 56e4a21..7accd90 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ Today's community use mobile phones to make their life easier, and community-bas - Use [this link](https://cloud.google.com/maps-platform/) to **generate Google Map Api key** for the map view in G-social. This is not necessary. You can use the given api key. But it is not guaranteed that the given key will always work. It is better to have your own key. Enable all maps, routes, places in your key. -- Now you need a **Facebook app id** if you want to enable Facebook login for Go-social. Use [this link](https://developers.facebook.com/) for that and make sure to enable both email/password and Facebook sign-in method in Firebase. +- Now you need a **Facebook app id** & **Facebook Client Token** if you want to enable Facebook login for Go-social. Use [this link](https://developers.facebook.com/) for that and make sure to enable both email/password and Facebook sign-in method in Firebase. So place your Firebase details and Google map API key in **config.example.js** file and **rename it** to **config.js**. @@ -42,14 +42,19 @@ So place your Firebase details and Google map API key in **config.example.js** f 1. Find the file name `AndroidManifest.xml` which is located in `android/app/src/main` path. Place your **Google map API key** in there. - > Ex : +``` - android:name="com.google.android.geo.API_KEY" - android:value=**"AIzaSyDmwJddIPTcALyZtj7p9mFFlkMvpMkati8"**/> +1. Find the file name as `strings.xml` located in `android/app/src/main/res/values`. Place your **Facebook app id** & **Facebook Client Token** in there. -1. Find the file name as `strings.xml` located in `android/app/src/main/res/values`. Place your **Facebook app id** in there. - - > Ex: **2349388348405699** +```sh +2349388348405699 +fb1234 +PLACE_YOUR_CLIENT_TOKEN_HERE +``` So now you are ready to run Go-social. From 8dfaab81de1a46fa80b5dd8a4505b3901a27a849 Mon Sep 17 00:00:00 2001 From: aman190 Date: Fri, 24 Mar 2023 17:27:21 +0530 Subject: [PATCH 5/6] Updated config.example firebase to firebase compat mode --- config/config.example.js | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/config/config.example.js b/config/config.example.js index dd7cb3a..f2c2cc8 100644 --- a/config/config.example.js +++ b/config/config.example.js @@ -1,7 +1,7 @@ -import { initializeApp } from "firebase/app"; -import { getAuth } from "firebase/auth"; -import { getStorage } from "firebase/storage"; -import { getDatabase } from "firebase/database"; +import firebase from "firebase/compat/app" +import "firebase/compat/auth" +import "firebase/compat/storage"; +import "firebase/compat/database"; const firebaseConfig = { apiKey: "", @@ -14,10 +14,12 @@ const firebaseConfig = { measurementId: "", }; -const app = initializeApp(firebaseConfig); -const auth = getAuth(app); -const storage = getStorage(app); -const db = getDatabase(app); +firebase.initializeApp(firebaseConfig) + +const app = firebase; +const auth = firebase.auth(); +const storage = firebase.storage(); +const db = firebase.database(); const MAP_API = ""; export { app, auth, storage, db, MAP_API }; From 4b7f080117d6d3c2d2fcb8e7ff6b437ee50fd1c5 Mon Sep 17 00:00:00 2001 From: aman190 Date: Fri, 24 Mar 2023 17:29:14 +0530 Subject: [PATCH 6/6] Updated all signin/signup firebase method to compat mode --- app/constants/auth.js | 5 ++ app/screens/LoginScreen/loginScreen.js | 47 +++++++++---------- app/screens/SignupScreen/signupScreen.js | 58 ++++++++++++------------ 3 files changed, 55 insertions(+), 55 deletions(-) create mode 100644 app/constants/auth.js diff --git a/app/constants/auth.js b/app/constants/auth.js new file mode 100644 index 0000000..e40cea2 --- /dev/null +++ b/app/constants/auth.js @@ -0,0 +1,5 @@ +export const fetchUserFbData = (token) => { + return fetch( + `https://graph.facebook.com/v2.8/me?fields=id,first_name,last_name,email,birthday&access_token=${token}` + ) +} \ No newline at end of file diff --git a/app/screens/LoginScreen/loginScreen.js b/app/screens/LoginScreen/loginScreen.js index d8dd76c..cc1281b 100644 --- a/app/screens/LoginScreen/loginScreen.js +++ b/app/screens/LoginScreen/loginScreen.js @@ -10,17 +10,12 @@ import { ScrollView, } from "react-native"; import { LoginManager, AccessToken } from "react-native-fbsdk-next"; -import { app, auth, db } from "../../../config/config.js"; -import { - signInWithEmailAndPassword, - onAuthStateChanged, - signInWithCredential, - FacebookAuthProvider, -} from "firebase/auth"; -import { ref, set } from "firebase/database"; +import { app, auth, database } from "../../../config/config.js"; +import {FacebookAuthProvider} from "firebase/auth"; import * as EmailValidator from "email-validator"; import { SocialIcon } from "react-native-elements"; import styles from "./style"; +import { fetchUserFbData } from "../../constants/auth.js"; export default class LoginScreen extends Component { constructor(props) { @@ -33,7 +28,7 @@ export default class LoginScreen extends Component { componentDidMount() { var that = this; - onAuthStateChanged(auth, function (user) { + auth.onAuthStateChanged(function (user) { if (user) { that.redirectUser(); } @@ -47,22 +42,26 @@ export default class LoginScreen extends Component { // Validate the user's email and password async _signInAsync() { - if (!EmailValidator.validate(this.state.email)) { - alert("Please enter a valid email!"); - } else if (this.state.password == "") { - alert("Enter your password!"); - } else { - this.login(); + switch(true) { + case !EmailValidator.validate(this.state.email): + alert("Please enter a valid email!"); + break; + case this.state.password === "": + alert("Enter your password!"); + break; + default: + this.login(); + break; } } // Signin with email and password async login() { try { - let email = this.state.email; - let password = this.state.password; + const email = this.state.email; + const password = this.state.password; - const res = await signInWithEmailAndPassword(auth, email, password); + const res = await auth.signInWithEmailAndPassword(email, password); } catch (error) { alert(error.message.toString()); } @@ -78,12 +77,11 @@ export default class LoginScreen extends Component { // Use the user's access token to authenticate with Firebase Authentication const credential = FacebookAuthProvider.credential(data.accessToken); - const { user } = await signInWithCredential(auth, credential); + const { user } = await auth.signInWithCredential(credential); - const response = await fetch( - `https://graph.facebook.com/v2.8/me?fields=id,first_name,last_name,email,birthday&access_token=${data.accessToken}` - ); + const response = await fetchUserFbData(data.accessToken) const userData = await response.json(); + const photoURL = `https://graph.facebook.com/${userData.id}/picture?height=120`; this.createUser(user.uid, userData, data.accessToken, photoURL); } @@ -95,9 +93,8 @@ export default class LoginScreen extends Component { // Create user async createUser(uid, userData, token, photoURL) { try { - const defaults = { uid, token, photoURL, Range: [20, 30] }; - const usersRef = ref(db, "users/" + uid); - set(usersRef, { ...userData, ...defaults }); + const defaults = { uid, token, photoURL, Range: [20, 30] }; + await database.ref(`users/${uid}`).set({ ...userData, ...defaults }); } catch (error) { alert(error.message.toString()); } diff --git a/app/screens/SignupScreen/signupScreen.js b/app/screens/SignupScreen/signupScreen.js index c18e569..ec84652 100644 --- a/app/screens/SignupScreen/signupScreen.js +++ b/app/screens/SignupScreen/signupScreen.js @@ -12,16 +12,10 @@ import { import styles from "./style"; import * as EmailValidator from "email-validator"; import { LoginManager, AccessToken } from "react-native-fbsdk-next"; -import { app, auth, db } from "../../../config/config.js"; -import { - createUserWithEmailAndPassword, - onAuthStateChanged, - updateProfile, - signInWithCredential, - FacebookAuthProvider, -} from "firebase/auth"; -import { ref, set} from "firebase/database"; +import { app, auth, database } from "../../../config/config.js"; +import { updateProfile, FacebookAuthProvider} from "firebase/auth"; import { SocialIcon } from "react-native-elements"; +import { fetchUserFbData } from "../../constants/auth"; export default class SignUpScreen extends Component { constructor(props) { @@ -36,7 +30,7 @@ export default class SignUpScreen extends Component { componentDidMount() { var that = this; - onAuthStateChanged(auth, function (user) { + auth.onAuthStateChanged(function (user) { if (user) { that.redirectUser(); } @@ -50,27 +44,33 @@ export default class SignUpScreen extends Component { // Validate user input for sign up async _signUpAsync() { - if (this.state.name == "") { - alert("Please enter your name!"); - } else if (!EmailValidator.validate(this.state.email)) { - alert("Please enter a valid email!"); - } else if (this.state.password == "") { - alert("Please enter a password!"); - } else if (this.state.password != this.state.confirmPassword) { - alert("Password and Confirm password must be same"); - } else { - this.signup(); + switch (true) { + case (this.state.name === ""): + alert("Please enter your name!"); + break; + case (!EmailValidator.validate(this.state.email)): + alert("Please enter a valid email!"); + break; + case (this.state.password === ""): + alert("Please enter a password!"); + break; + case (this.state.password !== this.state.confirmPassword): + alert("Password and Confirm password must be same"); + break; + default: + this.signup(); + break; } } // Sign up with email and password async signup() { try { - let name = this.state.name; - let email = this.state.email; - let password = this.state.password; + const name = this.state.name; + const email = this.state.email; + const password = this.state.password; - const { user } = await createUserWithEmailAndPassword(auth, email, password); + const { user } = await auth.createUserWithEmailAndPassword(email, password); await updateProfile(user, { displayName: name }); } catch (error) { alert(error.message.toString()); @@ -87,12 +87,11 @@ export default class SignUpScreen extends Component { // Use the user's access token to authenticate with Firebase Authentication const credential = FacebookAuthProvider.credential(data.accessToken); - const { user } = await signInWithCredential(auth, credential); + const { user } = await auth.signInWithCredential(credential); - const response = await fetch( - `https://graph.facebook.com/v2.8/me?fields=id,first_name,last_name,email,birthday&access_token=${data.accessToken}` - ); + const response = await fetchUserFbData(data.accessToken) const userData = await response.json(); + const photoURL = `https://graph.facebook.com/${userData.id}/picture?height=120`; this.createUser(user.uid, userData, data.accessToken, photoURL); } @@ -105,8 +104,7 @@ export default class SignUpScreen extends Component { async createUser(uid, userData, token, photoURL) { try { const defaults = { uid, token, photoURL, Range: [20, 30] }; - const usersRef = ref(db, "users/" + uid); - set(usersRef, { ...userData, ...defaults }); + await database.ref(`users/${uid}`).set({ ...userData, ...defaults }); } catch (error) { alert(error.message.toString()); }