Created
September 4, 2020 20:53
-
-
Save codeartistryio/101317bc359ee8f84e32140afd561abb to your computer and use it in GitHub Desktop.
auth.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useMutation } from "@apollo/react-hooks"; | |
import { Snackbar } from "@material-ui/core"; | |
import CloseIcon from "@material-ui/icons/Close"; | |
import firebase from "firebase/app"; | |
import "firebase/auth"; | |
import "firebase/database"; | |
import React from "react"; | |
import App from "./App"; | |
import IconButton from "@material-ui/core/IconButton"; | |
import defaultUserImage from "./images/default-user-image.jpg"; | |
import { CREATE_USER } from "./graphql/mutations"; | |
// NOTE: SET SUPPORT E-MAIL ADDRESS IF GETTING OAUTH ERROR | |
const provider = new firebase.auth.GoogleAuthProvider(); | |
// Your web app's Firebase configuration | |
var firebaseConfig = { | |
apiKey: "AIzaSyD7hFycz-FfLPPb-kYd773r2wh3_QBt5lA", | |
authDomain: "instagraham-clone.firebaseapp.com", | |
databaseURL: "https://instagraham-clone.firebaseio.com", | |
projectId: "instagraham-clone", | |
storageBucket: "instagraham-clone.appspot.com", | |
messagingSenderId: "1053685366267", | |
appId: "1:1053685366267:web:7510d66eee6dbb5c" | |
}; | |
// Initialize Firebase | |
firebase.initializeApp(firebaseConfig); | |
export const AuthContext = React.createContext(); | |
export default function Auth() { | |
const [authState, setAuthState] = React.useState({ status: "loading" }); | |
const [open, setOpen] = React.useState(false); | |
const [error, setError] = React.useState(null); | |
const [createUser] = useMutation(CREATE_USER); | |
React.useEffect(() => { | |
firebase.auth().onAuthStateChanged(async user => { | |
if (user) { | |
const token = await user.getIdToken(); | |
const idTokenResult = await user.getIdTokenResult(); | |
const hasuraClaim = | |
idTokenResult.claims["https://hasura.io/jwt/claims"]; | |
if (hasuraClaim) { | |
setAuthState({ status: "in", user, token }); | |
} else { | |
// Check if refresh is required. | |
const metadataRef = firebase | |
.database() | |
.ref(`metadata/${user.uid}/refreshTime`); | |
metadataRef.on("value", async () => { | |
// Force refresh to pick up the latest custom claims changes. | |
const token = await user.getIdToken(true); | |
setAuthState({ status: "in", user, token }); | |
}); | |
} | |
} else { | |
setAuthState({ status: "out" }); | |
} | |
}); | |
}, []); | |
async function signUpWithEmailAndPassword(formData) { | |
try { | |
const data = await firebase | |
.auth() | |
.createUserWithEmailAndPassword(formData.email, formData.password); | |
if (data.additionalUserInfo.isNewUser) { | |
const variables = { | |
website: "", | |
bio: "", | |
name: formData.name, | |
username: formData.username, | |
user_id: data.user.uid, | |
email: data.user.email, | |
profile_image: data.user.photoURL || defaultUserImage | |
}; | |
const result = await createUser({ variables }); | |
console.log({ result }); | |
} | |
} catch (error) { | |
console.log(error); | |
setOpen(true); | |
setError(error.message); | |
} | |
} | |
async function logInWithEmailAndPassword(email, password) { | |
try { | |
const data = await firebase | |
.auth() | |
.signInWithEmailAndPassword(email, password); | |
console.log({ data }); | |
} catch (error) { | |
console.log(error); | |
setOpen(true); | |
setError(error.message); | |
} | |
} | |
async function logInWithGoogle() { | |
try { | |
const data = await firebase.auth().signInWithPopup(provider); | |
if (data.additionalUserInfo.isNewUser) { | |
const variables = { | |
website: "", | |
bio: "", | |
name: data.user.displayName, | |
username: data.user.displayName.replace(/\s/g, "").toLowerCase(), | |
user_id: data.user.uid, | |
email: data.user.email, | |
profile_image: data.user.photoURL | |
}; | |
const result = await createUser({ variables }); | |
console.log({ result }); | |
} | |
} catch (error) { | |
console.log(error); | |
setOpen(true); | |
setError(error.message); | |
} | |
} | |
async function logOut() { | |
try { | |
setAuthState({ status: "loading" }); | |
await firebase.auth().signOut(); | |
setAuthState({ status: "out" }); | |
} catch (error) { | |
console.log(error); | |
} | |
} | |
function handleClose(event, reason) { | |
if (reason === "clickaway") { | |
return; | |
} | |
setOpen(false); | |
} | |
let content; | |
if (authState.status === "loading") { | |
content = null; | |
} else { | |
content = ( | |
<AuthContext.Provider | |
value={{ | |
authState, | |
logOut, | |
logInWithGoogle, | |
logInWithEmailAndPassword, | |
signUpWithEmailAndPassword | |
}} | |
> | |
<App /> | |
<Snackbar | |
open={open} | |
anchorOrigin={{ | |
vertical: "bottom", | |
horizontal: "right" | |
}} | |
message={error} | |
action={ | |
<IconButton color="inherit" onClick={handleClose}> | |
<CloseIcon /> | |
</IconButton> | |
} | |
/> | |
</AuthContext.Provider> | |
); | |
} | |
return content; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment