Skip to content

Instantly share code, notes, and snippets.

@luandevpro
Last active June 29, 2019 12:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luandevpro/3b78328a9957b2273cc02c8f588ec385 to your computer and use it in GitHub Desktop.
Save luandevpro/3b78328a9957b2273cc02c8f588ec385 to your computer and use it in GitHub Desktop.
import React, { useEffect } from 'react';
import gql from 'graphql-tag';
import { auth, googleAuthProvider, database } from '../lib/firebase';
import initialApollo from '../lib/initialApollo';
const getUser = gql`
query getUser($id: String!) {
user_by_pk(id: $id) {
id
email
photoURL
displayName
}
}
`;
const addUser = gql`
mutation insert_user($objects: [user_insert_input!]!) {
insert_user(
objects: $objects
on_conflict: { constraint: user_pkey, update_columns: [displayName, photoURL, email] }
) {
returning {
id
photoURL
}
}
}
`;
function Login() {
useEffect(
() =>
auth.onAuthStateChanged(async user => {
if (user) {
const metadataRef = await database.ref(`metadata/${user.uid}/refreshTime`);
const callback = async () => {
const token = await user.getIdToken();
const idTokenResult = await user.getIdTokenResult();
const hasuraClaim = await idTokenResult.claims['https://hasura.io/jwt/claims'];
if (hasuraClaim) {
const initialApolloGraph = initialApollo(token);
initialApolloGraph
.query({
query: getUser,
variables: {
id: user.uid,
},
})
.then(users => {
if (users.data.user_by_pk !== null) {
console.log(users);
} else {
initialApolloGraph
.mutate({
mutation: addUser,
variables: {
objects: [
{
id: user.uid,
email: user.email,
displayName: user.displayName,
photoURL: user.photoURL,
},
],
},
context: {},
})
.then(() => console.log('success'))
.catch(result => console.log(result));
}
})
.catch(err => {
console.log(err);
});
}
};
metadataRef.on('value', callback);
}
}),
[]
);
const signinWithGoogle = async () => {
try {
await auth.signInWithPopup(googleAuthProvider);
} catch (error) {
console.log(error);
}
};
const signOut = async () => {
try {
await auth.signOut();
} catch (error) {
console.log(error);
}
};
return (
<div>
<button type="button" onClick={signinWithGoogle}>
Login
</button>
<button type="button" onClick={signOut}>
Sign out
</button>
</div>
);
}
export default Login;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment