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 all 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
19 changes: 12 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,22 +34,27 @@ 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**.

- To make Google map and Facebook login to work, you have to follow these extra steps.\*

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 : <meta-data
```sh
<meta-data
android: name="com.google.android.geo.API_KEY"
android: value="AIzaSyDmwJddIPTcALyZtj7p9mFFlkMvpMkati8"/>
```

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: <string name="facebook_app_id">**2349388348405699**</string>
```sh
<string name="facebook_app_id">2349388348405699</string>
<string name="fb_login_protocol_scheme">fb1234</string>
<string name="facebook_client_token">PLACE_YOUR_CLIENT_TOKEN_HERE</string>
```

So now you are ready to run Go-social.

Expand Down
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>
5 changes: 5 additions & 0 deletions app/constants/auth.js
Original file line number Diff line number Diff line change
@@ -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}`
)
}
164 changes: 66 additions & 98 deletions app/screens/LoginScreen/loginScreen.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,132 +9,100 @@ 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, database } from "../../../config/config.js";
import {FacebookAuthProvider} from "firebase/auth";
import * as EmailValidator from "email-validator";
import styles from "./style";
import { SocialIcon } from "react-native-elements";
import styles from "./style";
import { fetchUserFbData } from "../../constants/auth.js";

export default class LoginScreen extends Component {
constructor(props) {
super(props);
this.state = {
email: "",
Password: "",
password: "",
};
}

componentDidMount() {
var that = this;

auth.onAuthStateChanged(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 != "") {
// Validate the user's email and password
async _signInAsync() {
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();
} else {
alert("Enter the password");
}
} else {
alert("Please enter A Valid Email");
break;
}
};

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 {
const email = this.state.email;
const password = this.state.password;

const res = await auth.signInWithEmailAndPassword(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 auth.signInWithCredential(credential);

const response = await fetchUserFbData(data.accessToken)
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] };
await database.ref(`users/${uid}`).set({ ...userData, ...defaults });
} catch (error) {
alert(error.message.toString());
}
}

handleInput(input, text) {
this.setState(prevState => ({ ...prevState, [input]: text }));
}

render() {
return (
Expand All @@ -151,7 +119,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 +129,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