Skip to content

Instantly share code, notes, and snippets.

@gcpantazis
Created May 17, 2020 21:04
Show Gist options
  • Save gcpantazis/037c77351c5b3f99db79d07e20dbc22a to your computer and use it in GitHub Desktop.
Save gcpantazis/037c77351c5b3f99db79d07e20dbc22a to your computer and use it in GitHub Desktop.
import gql from "graphql-tag";
import jwt from "jsonwebtoken";
import getConfig from "next/config";
import qs from "qs";
import React from "react";
import { withApollo, WithApolloClient } from "react-apollo";
import FullPageLoader from "../components/fullPageLoader";
import { currentUser } from "../__generated__/currentUser";
import { userSignUp } from "../__generated__/userSignUp";
const { publicRuntimeConfig } = getConfig();
interface AuthCallbackProps {}
type AuthCallbackPropsWithApollo = WithApolloClient<AuthCallbackProps>;
class AuthCallback extends React.Component<AuthCallbackPropsWithApollo> {
async componentDidMount() {
const { client } = this.props;
const query = window.location.hash.substr(1);
const params = qs.parse(query);
const decodedJWT = jwt.decode(params.id_token);
/* Context for API calls */
const context = {
headers: {
authorization: `Bearer ${params.id_token}`
}
};
try {
/* Check if a user exists, if not an error will be thrown */
const userResult = await client.query<currentUser>({
query: gql`
query currentUser {
user {
id
}
}
`,
context
});
window.localStorage.setItem("token", params.id_token);
window.localStorage.setItem("last-token-check", new Date().toISOString());
window.location.href = `/account`;
return;
} catch {
/* Sign up user if the request errored */
if (decodedJWT && typeof decodedJWT === "object" && decodedJWT.email) {
try {
const userSignUpResult = await client.mutate<userSignUp>({
mutation: gql`
mutation userSignUp($user: UserCreateInput!) {
userSignUp(user: $user) {
id
email
}
}
`,
variables: {
user: { email: decodedJWT.email }
},
context
});
window.localStorage.setItem("token", params.id_token);
window.localStorage.setItem(
"last-token-check",
new Date().toISOString()
);
window.location.href = `/account`;
return;
} catch (e) {
console.log(e);
window.location.href = `/logout`;
}
}
}
}
render() {
return <FullPageLoader text="Hold tight..." />;
}
}
export default withApollo(AuthCallback);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment