Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix the Sign In, Sign Up with email & password and Facebook #176

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions android/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down
19 changes: 18 additions & 1 deletion android/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">

<uses-permission android:name="android.permission.INTERNET" />
<!-- <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/> -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.gms.permission.AD_ID" tools:node="remove"/>



<application
Expand All @@ -26,10 +28,25 @@
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.facebook.FacebookActivity"
android:configChanges=
"keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="@string/app_name" />
<activity
android:name="com.facebook.CustomTabActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="@string/fb_login_protocol_scheme" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyDmwJddIPTcALyZtj7p9mFFlkMvpMkati8"/>
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
<meta-data android:name="com.facebook.sdk.ClientToken" android:value="@string/facebook_client_token"/>
</application>

</manifest>
4 changes: 3 additions & 1 deletion android/app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
<resources>
<string name="app_name">Go_social</string>
<string name="facebook_app_id">2349388348405699</string>
<string name="facebook_app_id">222891166977339</string>
<string name="fb_login_protocol_scheme">fb1234</string>
<string name="facebook_client_token">PLACE_YOUR_CLIENT_TOKEN_HERE</string>
Comment on lines +4 to +5
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If these are configurations that should be configured by the developer, readme file should contain step by step guide to config this.

Copy link
Contributor Author

@ajaman190 ajaman190 Mar 24, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added configuration in old readme file

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please review the update reademe pr #169, so that i can also update this comfig in new readme file.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please address the issues in #169 first.

Copy link
Contributor Author

@ajaman190 ajaman190 Mar 28, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, i will address this first

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added this configuration, please review #169

</resources>
169 changes: 70 additions & 99 deletions app/screens/LoginScreen/loginScreen.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,132 +9,103 @@ import {
KeyboardAvoidingView,
ScrollView,
} from "react-native";
import { AccessToken, LoginManager } from "react-native-fbsdk";
import { f, auth } from "../../../config/config.js";
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 * 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");
}
// 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 {
alert("Please enter A Valid Email");
this.login();
}
};

onPressLogin() {
LoginManager.logInWithReadPermissions(["public_profile", "email"]).then(
result => this._handleCallBack(result),
function (error) {
alert("Login fail with error: " + error);
}
);
}

_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);
});
});
// Signin with email and password
async login() {
try {
let email = this.state.email;
let password = this.state.password;
ajaman190 marked this conversation as resolved.
Show resolved Hide resolved

const res = await signInWithEmailAndPassword(auth, email, password);
} 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 });
};

_signInAsync = async () => {
if (EmailValidator.validate(this.state.email) === true) {
if (this.state.Pasword != "") {
this.login();
} else {
alert("Enter the password");
// 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}`
ajaman190 marked this conversation as resolved.
Show resolved Hide resolved
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can use Promise.allSettled() for this. Would be an performance improvement on my perspective.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I got this on internet

"Uses of await or Promise.allSettled() depends on the specific use case and the performance characteristics of the promises being used. In general, if the promises can execute in parallel and the outcome of rejected promises is not important, Promise.allSettled() can be a good choice. However, if the promises need to execute sequentially or the outcome of rejected promises needs to be handled specifically, await may be a better choice."

Also in our case the response of promises are dependent on each other.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@shehand Whats your suggestion on it.

Copy link
Collaborator

@shehand shehand Mar 26, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you please explain that how they are depending in each other? I can see two awaited calls which do not depend on each other at all.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes you are right, these two promises are independent of each other but they are dependent on the above promises, which are not visible in this snippet.

So, I can either execute these two promises in parallel using Promise.allSettled() and explicitly check for their success and failure (since Promise.allSettled() will wait for all functions passed in the array to either resolve or reject without rejecting itself),
or I can use Promise.all(), which will reject as soon as one of the functions passed in the array rejects.

);
const userData = await response.json();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So then we can remove await in here

const photoURL = `https://graph.facebook.com/${userData.id}/picture?height=120`;
this.createUser(user.uid, userData, data.accessToken, photoURL);
}
} else {
alert("Please enter A Valid Email");
} 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 }));
}

render() {
return (
Expand All @@ -151,7 +122,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;
}}
Expand All @@ -161,24 +132,24 @@ 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;
}}
/>
</View>
</KeyboardAvoidingView>
<TouchableOpacity onPress={this._signInAsync} style={styles.loginButton}>
<TouchableOpacity onPress={this._signInAsync.bind(this)} style={styles.loginButton}>
<Text style={styles.buttonText}>Sign In</Text>
</TouchableOpacity>

<TouchableOpacity onPress={() => this.props.navigation.navigate("ForgotPassword")}>
<Text style={styles.text}>Forgot Password?</Text>
</TouchableOpacity>

<TouchableOpacity onPress={this.onPressLogin.bind(this)}>
<TouchableOpacity onPress={this._fbSignInAsync.bind(this)}>
<SocialIcon
style={{ width: 200 }}
style={{ width: 290 }}
title="Sign In With Facebook"
button
type="facebook"
Expand Down
Loading