Complete rewrite of local state management.
This commit is contained in:
@@ -1,91 +1,29 @@
|
||||
//Baselined on https://blog.hasura.io/authentication-and-authorization-using-hasura-and-firebase/
|
||||
import React from "react";
|
||||
import { Mutation, Query } from "react-apollo";
|
||||
import { GET_CURRENT_USER, SET_CURRENT_USER } from "../graphql/local.queries";
|
||||
|
||||
import React, { useState, useEffect } from "react";
|
||||
import firebase from "../firebase/firebase.utils";
|
||||
import App from "./App";
|
||||
|
||||
import { gql } from "apollo-boost";
|
||||
import { HttpLink } from "apollo-link-http";
|
||||
import ApolloClient from "apollo-client";
|
||||
import { InMemoryCache } from "apollo-cache-inmemory";
|
||||
|
||||
import Spin from "../components/loading-spinner/loading-spinner.component";
|
||||
|
||||
const UPSERT_USER = gql`
|
||||
mutation upsert_user($authEmail: String!, $authToken: String!) {
|
||||
insert_users(
|
||||
objects: [{ email: $authEmail, authid: $authToken }]
|
||||
on_conflict: { constraint: users_pkey, update_columns: [authid] }
|
||||
) {
|
||||
returning {
|
||||
authid
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const SET_CURRENT_USER = gql`
|
||||
mutation SetCurrentUser($user: User!) {
|
||||
setCurrentUser(user: $user) @client
|
||||
}
|
||||
`;
|
||||
|
||||
const client = new ApolloClient({
|
||||
link: new HttpLink({
|
||||
uri: process.env.REACT_APP_GRAPHQL_ENDPOINT
|
||||
}),
|
||||
cache: new InMemoryCache()
|
||||
});
|
||||
|
||||
export default function Auth() {
|
||||
const [authState, setAuthState] = useState({ status: "loading" });
|
||||
|
||||
useEffect(() => {
|
||||
return firebase.auth().onAuthStateChanged(async user => {
|
||||
if (user) {
|
||||
console.log("Current User:", user);
|
||||
|
||||
client
|
||||
.mutate({
|
||||
mutation: UPSERT_USER,
|
||||
variables: { authEmail: user.email, authToken: user.uid }
|
||||
})
|
||||
.then(r => console.log("Successful Upsert", r))
|
||||
.catch(error => console.log("Upsert error!!!!", error));
|
||||
|
||||
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" });
|
||||
}
|
||||
});
|
||||
}, []);
|
||||
|
||||
let content;
|
||||
if (authState.status === "loading") {
|
||||
content = <Spin />;
|
||||
} else {
|
||||
content = (
|
||||
<>
|
||||
<App authState={authState} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return <div className="app-container">{content}</div>;
|
||||
}
|
||||
export default () => {
|
||||
return (
|
||||
<Query query={GET_CURRENT_USER}>
|
||||
{({ loading, error, data: { currentUser } }) => {
|
||||
if (loading) return <Spin />;
|
||||
if (error) return error.message;
|
||||
return (
|
||||
<Mutation mutation={SET_CURRENT_USER}>
|
||||
{setCurrentUser => (
|
||||
<App
|
||||
currentUser={currentUser}
|
||||
setCurrentUser={user => {
|
||||
setCurrentUser({ variables: { user } });
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</Mutation>
|
||||
);
|
||||
}}
|
||||
</Query>
|
||||
);
|
||||
};
|
||||
|
||||
78
client/src/App/App.container.jsx.bak
Normal file
78
client/src/App/App.container.jsx.bak
Normal file
@@ -0,0 +1,78 @@
|
||||
//Baselined on https://blog.hasura.io/authentication-and-authorization-using-hasura-and-firebase/
|
||||
|
||||
import React, { useState, useEffect } from "react";
|
||||
import firebase from "../firebase/firebase.utils";
|
||||
import App from "./App";
|
||||
|
||||
import { gql } from "apollo-boost";
|
||||
import { HttpLink } from "apollo-link-http";
|
||||
import ApolloClient from "apollo-client";
|
||||
import { InMemoryCache } from "apollo-cache-inmemory";
|
||||
|
||||
import Spin from "../components/loading-spinner/loading-spinner.component";
|
||||
|
||||
const UPSERT_USER = gql`
|
||||
mutation upsert_user($authEmail: String!, $authToken: String!) {
|
||||
insert_users(
|
||||
objects: [{ email: $authEmail, authid: $authToken }]
|
||||
on_conflict: { constraint: users_pkey, update_columns: [authid] }
|
||||
) {
|
||||
returning {
|
||||
authid
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export default function Auth() {
|
||||
const [authState, setAuthState] = useState({ status: "loading" });
|
||||
|
||||
useEffect(() => {
|
||||
return firebase.auth().onAuthStateChanged(async user => {
|
||||
if (user) {
|
||||
console.log("Current User:", user);
|
||||
|
||||
client
|
||||
.mutate({
|
||||
mutation: UPSERT_USER,
|
||||
variables: { authEmail: user.email, authToken: user.uid }
|
||||
})
|
||||
.then(r => console.log("Successful Upsert", r))
|
||||
.catch(error => console.log("Upsert error!!!!", error));
|
||||
|
||||
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" });
|
||||
}
|
||||
});
|
||||
}, []);
|
||||
|
||||
let content;
|
||||
if (authState.status === "loading") {
|
||||
content = <Spin />;
|
||||
} else {
|
||||
content = (
|
||||
<>
|
||||
<App authState={authState} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return <div className="app-container">{content}</div>;
|
||||
}
|
||||
@@ -1,71 +1,105 @@
|
||||
import React from "react";
|
||||
import { Switch, Route, Redirect } from "react-router";
|
||||
import { ApolloProvider } from "react-apollo";
|
||||
import { HttpLink } from "apollo-link-http";
|
||||
import ApolloClient from "apollo-client";
|
||||
import { InMemoryCache } from "apollo-cache-inmemory";
|
||||
import { resolvers, typeDefs } from "../graphql/resolvers";
|
||||
import initialState from "../graphql/initial-state";
|
||||
import { gql } from "apollo-boost";
|
||||
//Styling imports
|
||||
import { Switch, Route } from "react-router-dom";
|
||||
import firebase from "../firebase/firebase.utils";
|
||||
|
||||
import "./App.css";
|
||||
|
||||
//Component Imports
|
||||
import LandingPage from "../pages/landing/landing.page";
|
||||
import Manage from "../pages/manage/manage.page";
|
||||
|
||||
import PrivateRoute from "../utils/private-route";
|
||||
import SignInContainer from "../pages/sign-in/sign-in.container";
|
||||
import SignInPage from "../pages/sign-in/sign-in.page";
|
||||
import Unauthorized from "../pages/unauthorized/unauthorized.component";
|
||||
|
||||
const graphqlEndpoint = process.env.REACT_APP_GRAPHQL_ENDPOINT;
|
||||
import { auth } from "../firebase/firebase.utils";
|
||||
|
||||
export default function App({ authState }) {
|
||||
const isIn = authState.status === "in";
|
||||
const headers = isIn ? { Authorization: `Bearer ${authState.token}` } : {};
|
||||
const httpLink = new HttpLink({
|
||||
uri: graphqlEndpoint,
|
||||
headers
|
||||
});
|
||||
const client = new ApolloClient({
|
||||
link: httpLink,
|
||||
cache: new InMemoryCache(),
|
||||
resolvers,
|
||||
typeDefs
|
||||
});
|
||||
class App extends React.Component {
|
||||
unsubscribeFromAuth = null;
|
||||
|
||||
//Init local state.
|
||||
client.writeData({
|
||||
data: {
|
||||
...initialState,
|
||||
currentUser: {
|
||||
__typename: null,
|
||||
email: authState.user ? authState.user.email : null,
|
||||
displayName: authState.user ? authState.user.displayName : null
|
||||
componentDidMount() {
|
||||
const { setCurrentUser } = this.props;
|
||||
|
||||
this.unsubscribeFromAuth = auth.onAuthStateChanged(async user => {
|
||||
console.log("Current User:", user);
|
||||
if (user) {
|
||||
// client
|
||||
// .mutate({
|
||||
// mutation: UPSERT_USER,
|
||||
// variables: { authEmail: user.email, authToken: user.uid }
|
||||
// })
|
||||
// .then(r => console.log("Successful Upsert", r))
|
||||
// .catch(error => console.log("Upsert error!!!!", error));
|
||||
|
||||
const token = await user.getIdToken();
|
||||
const idTokenResult = await user.getIdTokenResult();
|
||||
const hasuraClaim =
|
||||
idTokenResult.claims["https://hasura.io/jwt/claims"];
|
||||
if (hasuraClaim) {
|
||||
setCurrentUser({
|
||||
email: user.email,
|
||||
displayName: user.displayName,
|
||||
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);
|
||||
setCurrentUser({
|
||||
email: user.email,
|
||||
displayName: user.displayName,
|
||||
token
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
//add the bearer token to the headers.
|
||||
localStorage.setItem("token", token);
|
||||
} else {
|
||||
setCurrentUser({
|
||||
email: null,
|
||||
displayName: null,
|
||||
token: null
|
||||
});
|
||||
localStorage.removeItem("token");
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<ApolloProvider client={client}>
|
||||
<div>{authState.status}</div>
|
||||
<Switch>
|
||||
<Route exact path="/" component={LandingPage} />
|
||||
<Route exact path="/unauthorized" component={Unauthorized} />
|
||||
<Route
|
||||
exact
|
||||
path="/signin"
|
||||
render={() =>
|
||||
authState.status == "in" ? (
|
||||
<Redirect to="/manage" />
|
||||
) : (
|
||||
<SignInContainer />
|
||||
)
|
||||
}
|
||||
/>
|
||||
{/* <Route path="/signin" component={SignInContainer} /> */}
|
||||
<PrivateRoute isAuthorized={isIn} path="/manage" component={Manage} />
|
||||
</Switch>
|
||||
</ApolloProvider>
|
||||
);
|
||||
componentWillUnmount() {
|
||||
this.unsubscribeFromAuth();
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<div>
|
||||
<Switch>
|
||||
<Route exact path="/" component={LandingPage} />
|
||||
<Route exact path="/unauthorized" component={Unauthorized} />
|
||||
{/* <Route
|
||||
exact
|
||||
path="/signin"
|
||||
render={() =>
|
||||
this.props.currentUser.email != null ? (
|
||||
<Redirect to="/manage" />
|
||||
) : (
|
||||
<SignInContainer />
|
||||
)
|
||||
}
|
||||
/> */}
|
||||
<Route path="/signin" component={SignInPage} />
|
||||
<PrivateRoute
|
||||
isAuthorized={this.props.currentUser.email != null}
|
||||
path="/manage"
|
||||
component={Manage}
|
||||
/>
|
||||
</Switch>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default App;
|
||||
|
||||
71
client/src/App/App.js.bak
Normal file
71
client/src/App/App.js.bak
Normal file
@@ -0,0 +1,71 @@
|
||||
import React from "react";
|
||||
import { Switch, Route, Redirect } from "react-router";
|
||||
import { ApolloProvider } from "react-apollo";
|
||||
import { HttpLink } from "apollo-link-http";
|
||||
import ApolloClient from "apollo-client";
|
||||
import { InMemoryCache } from "apollo-cache-inmemory";
|
||||
import { resolvers, typeDefs } from "../graphql/resolvers";
|
||||
import initialState from "../graphql/initial-state";
|
||||
import { gql } from "apollo-boost";
|
||||
//Styling imports
|
||||
import "./App.css";
|
||||
|
||||
//Component Imports
|
||||
import LandingPage from "../pages/landing/landing.page";
|
||||
import Manage from "../pages/manage/manage.page";
|
||||
|
||||
import PrivateRoute from "../utils/private-route";
|
||||
import SignInContainer from "../pages/sign-in/sign-in.container";
|
||||
import Unauthorized from "../pages/unauthorized/unauthorized.component";
|
||||
|
||||
const graphqlEndpoint = process.env.REACT_APP_GRAPHQL_ENDPOINT;
|
||||
|
||||
export default function App({ authState }) {
|
||||
const isIn = authState.status === "in";
|
||||
const headers = isIn ? { Authorization: `Bearer ${authState.token}` } : {};
|
||||
const httpLink = new HttpLink({
|
||||
uri: graphqlEndpoint,
|
||||
headers
|
||||
});
|
||||
const client = new ApolloClient({
|
||||
link: httpLink,
|
||||
cache: new InMemoryCache(),
|
||||
resolvers,
|
||||
typeDefs
|
||||
});
|
||||
|
||||
//Init local state.
|
||||
client.writeData({
|
||||
data: {
|
||||
...initialState,
|
||||
currentUser: {
|
||||
__typename: null,
|
||||
email: authState.user ? authState.user.email : null,
|
||||
displayName: authState.user ? authState.user.displayName : null
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<ApolloProvider client={client}>
|
||||
<div>{authState.status}</div>
|
||||
<Switch>
|
||||
<Route exact path="/" component={LandingPage} />
|
||||
<Route exact path="/unauthorized" component={Unauthorized} />
|
||||
<Route
|
||||
exact
|
||||
path="/signin"
|
||||
render={() =>
|
||||
authState.status == "in" ? (
|
||||
<Redirect to="/manage" />
|
||||
) : (
|
||||
<SignInContainer />
|
||||
)
|
||||
}
|
||||
/>
|
||||
{/* <Route path="/signin" component={SignInContainer} /> */}
|
||||
<PrivateRoute isAuthorized={isIn} path="/manage" component={Manage} />
|
||||
</Switch>
|
||||
</ApolloProvider>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user