Skip to content

Instantly share code, notes, and snippets.

@NicholusMuwonge
Created October 24, 2020 13:54
Show Gist options
  • Save NicholusMuwonge/59880a3b994980752e7c5af2100bd53b to your computer and use it in GitHub Desktop.
Save NicholusMuwonge/59880a3b994980752e7c5af2100bd53b to your computer and use it in GitHub Desktop.
Social Login example
import React from "react";
import { GoogleAPI, GoogleLogin, GoogleLogout } from "react-google-oauth";
import FacebookLogin from 'react-facebook-login';
function App() {
return (
<div className="App">
<div className="App-header">
<GoogleAPI className="GoogleLogin" clientId={CLIENT_ID}>
<div>
<GoogleLogin
height="10"
width="500px"
backgroundColor="#4285f4"
access="offline"
scope="email profile"
onLoginSuccess={responseGoogle}
onFailure={responseGoogle}
/>
</div>
</GoogleAPI>
<FacebookLogin
appId={CLIENT_ID}
autoLoad={true}
fields="email"
onClick={responseFacebook}
callback={responseFacebook} />
</div>
</div>
);
}
const responseFacebook = (response) => {
console.log(response, "Facebook response");
var data = {
provider: "facebook",
uid: response.userID,
id_token: response.accessToken,
info: {
email: response.email
}
}
console.log(data, "Data to be sent to the backend")
const requestOptions = {
method: 'POST',
headers: {
'Authorization': `Bearer ${response.accessToken}`,
'Content-Type': 'application/json',
'access_token': `${response.accessToken}`
},
body: JSON.stringify(data)
}
return fetch(`call back url set in the backend`, requestOptions)
.then(response => response.json()) // make sure you jsonify the response
.then(response => {
console.log(response, "I AM RESPONSE FROM THE BACKEND WITH THE USER LOGIN TOKEN AND HEADERS");
// set cookies or something
})
.catch(err=>err) //catch any errors
}
const responseGoogle = (response) => {
console.log(response, "I AM RESPONSE FROM GOOGLE")
var token = response;
var data = {
provider: "google_oauth2",
uid: token.Ca,
id_token: response.wc.id_token,
info: {
email: token.nt.Wt
}
}
console.log(data, "MY USER OBJECT I WANT TO SEND TO THE BACKEND")
const requestOptions = {
method: 'POST',
headers: {
'Authorization': `Bearer ${response.wc.access_token}`,
'Content-Type': 'application/json',
'access_token': `${response.wc.access_token}`
},
body: JSON.stringify(data)
}
return fetch(`call back url set in the backend`, requestOptions)
.then(response => response.json())
.then(response => {
console.log(response, "I AM RESPONSE FROM THE BACKEND");
// do something
})
.catch(err=>console.log(err))
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment