Esmael
Esmael

Reputation: 1

I am getting an "access denied" error in next auth with github as a provider

Issue with NextAuth SignIn Callback when using Sanity Write Client

I am using Sanity's read and write token with NextAuth and GitHub as a provider.

The problem seems to occur in the signIn callback when I use the writeClient to create a document in Sanity. If I comment out the part of the code where writeClient.create() is used, the authentication works fine. However, when I uncomment it, the error AccessDenied is returned.

Here is my auth.ts file:


import NextAuth from "next-auth";
import GitHub from "next-auth/providers/github"; // Correct import
import { AUTHOR_BY_GITHUB_ID_QUERY } from "@/sanity/lib/queries";
import { client } from "@/sanity/lib/client";
import { writeClient } from "./sanity/lib/write_client";

export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [
    GitHub({
      clientId: process.env.AUTH_GITHUB_ID!, // GitHub client ID
      clientSecret: process.env.AUTH_GITHUB_SECRET!, // GitHub client secret
      authorization: { params: { scope: "read:user user:email" } },
    }),
  ],

  callbacks: {
    async signIn({ user, profile }) {
      const { name, email, image } = user;
      const { id, login, bio } = profile;

      const existingUser = await client
        .withConfig({ useCdn: false })
        .fetch(AUTHOR_BY_GITHUB_ID_QUERY, {
          id,
        });

      if (!existingUser) {
        await writeClient.create({
          _type: "author",
          id,
          name,
          username: login,
          email,
          image,
          bio: bio || "",
        });
      }
      return true;
    },

    async jwt({ token, account, profile }) {
      if (account && profile) {
        const user = await client
          .withConfig({ useCdn: false })
          .fetch(AUTHOR_BY_GITHUB_ID_QUERY, {
            id: profile?.id,
          });

        token.id = user?._id;
      }

      return token;
    },

    async session({ session, token }) {
      Object.assign(session, { id: token.id });
      return session;
    },
  },
});

What I've Tried:

Environment:

Error Logs: AccessDenied error occurs when writeClient.create() is called.

Question: What could be causing this issue with the writeClient.create() call in the signIn callback, and how can I resolve it?

Any help or insight would be appreciated!

Upvotes: 0

Views: 39

Answers (0)

Related Questions