24
loading...
This website collects cookies to deliver better user experience
API
tab on top. Enter a sample query and run it to test if everything is functioning properlyquery MyQuery {
tweets {
owner_id
tweet_text
}
}
/pages/api/session.ts
in the Next.js project folder.import { getSession, withApiAuthRequired } from "@auth0/nextjs-auth0";
import type { NextApiRequest, NextApiResponse } from "next";
export default withApiAuthRequired(async function getSessionId(
req: NextApiRequest,
res: NextApiResponse
) {
try {
const session = await getSession(req, res);
res.status(200).json({ session });
} catch (error) {
console.error(error);
}
});
idToken
which is needed to establish a connection with Hasura.yarn add @apollo/client graphql axios
apollo-client.js
in the root of the folder with the following code.import { ApolloClient, createHttpLink, InMemoryCache } from "@apollo/client";
import { setContext } from "@apollo/client/link/context";
import axios from "axios";
const httpLink = createHttpLink({
uri: "insert_url_here",
fetch: (...args) => fetch(...args),
});
async function fetchSession() {
const res = await axios.get(`/api/session`);
return res.data.session.idToken;
}
const authLink = setContext((_, { headers }) => {
const authLinkWithHeader = fetchSession().then((token) => {
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : "",
},
};
});
return authLinkWithHeader;
});
export const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
});
export default client;
user_id
and role
. Remember to change the url
to your Hasura graphql endpoint./pages/_app.tsx
and wrap the app component with providers from Apollo and Auth0.import type { AppProps } from "next/app";
import { ApolloProvider } from "@apollo/client";
import { UserProvider } from "@auth0/nextjs-auth0";
import client from "../../apollo-client";
function MyApp({ Component, pageProps }: AppProps): JSX.Element {
return (
<UserProvider>
<ApolloProvider client={client}>
<Component {...pageProps} />
</ApolloProvider>
</UserProvider>
);
}
export default MyApp;
/pages/index.tsx
so that it looks like this:import type { NextPage } from "next";
import { gql, useQuery } from "@apollo/client";
import Head from "next/head";
import styles from "../styles/Home.module.css";
interface TweetType {
owner_id: string;
tweet_text: string;
__typename: string;
}
const GET_TWEETS = gql`
query GetTweets {
tweets {
owner_id
tweet_text
}
}
`;
const Home: NextPage = () => {
const { data, loading } = useQuery(GET_TWEETS);
return (
<div className={styles.container}>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<a href="/api/auth/login">Login</a>
<a href="/api/auth/logout">Logout</a>
<div>
{loading
? "loading..."
: data?.tweets.map((tweet: TweetType, index: number) => (
<div
key={`${tweet.owner_id}-${index}`}
style={{ margin: "12px 0px" }}
>
<div>By user: {tweet.owner_id}</div>
<div>{tweet.tweet_text}</div>
</div>
)) ?? "No data received."}
</div>
</div>
);
};
export default Home;
yarn run dev
. Log in to the app with the test account you used to add dummy data into the Hasura instance. The graphql should retrieve all the tweets in the database irrespective of the owner. login-hasura-token
which embeds the user_id
and role
into the token that we receive from Auth0. In the code, we hardcoded the role as user
for simplicity. We're getting the above error because we haven't set up the permissions for the user
role. Let's do that now.tweets
table and click on the permissions
tab. You'll see that the role admin
is given all-access. In the text field under admin
type user
. Now click on the red cross under the select
column to open up the permission settings.Without any checks
, and for column select permissions, select the columns that you want the user to access. Click on Save Permissions
. Go back to the Next.js app and refresh. The tweets should show up now.user
role attached to them. This means everyone has access to your data. And hence, all registered users can update or delete your data. That sucks.user_id
embedded in the token and the owner_id
of the tweet. If they are the same, then the requester is the owner of the tweet. tweets
table, click on the permissions tab and click on the update
operation corresponding to the user
role.With custom check
. Click on the drop-down and choose owner_id
. We want to see if it is equal to the user_id
in the token, so select the _eq
operation and second variable as X-Hasura-User-Id
. In the Column update permissions, choose which all columns you want the requester to have access to. Apply the settings.