Back

401 user_unauthorized: The current user is not authorized to perform the requested action.

  • 0
  • Databases
Jamieyes
12 Sep, 2024, 14:36

I am using NextJs with the node-apprite cli. When a user creates an account I need a document to be added to my Users collection. When the code to create the new user's document is called, i get the error stated in the title. This is strange however, since the session is creaed, the user is logged in and the document is created in the database. I've sent a couple of days trying to figure this out. My permissions are essentially set to anyone (any, guest & users) for the sake of experimentation. This is the code to create a user and post to the DB:

TypeScript
  const session = await account.createEmailPasswordSession(email, password);
  cookies().set("auth-session", session.secret, {
    path: "/",
    httpOnly: true,
    sameSite: "strict",
    secure: true,
  });

  await addUserToDatabase(username, session.userId, email);

... 

  async function addUserToDatabase(
    userName: string,
    userId: string,
    userEmail: string
  ) {
    const { databases } = await createDatabaseClient();
  
    try {
      return await databases.createDocument(
        databaseId,
        usersCollectionId,
        ID.unique(),
        {
          userName,
          userId,
          userEmail,
        }
      );
    } catch (error: any) {
      if (error.type === "user_unauthorized") {
        console.error("Unauthorized to add user to database", error);
      } else {
        console.error("Error adding user to database", error);
      }
    }
  }
TL;DR
Error message '401 user_unauthorized' when attempting to add user to database even though the user is logged in and the document is created. Permissions are set to anyone for testing. Potential issue related to creating a document in another collection. Solution: Check database authorization settings and ensure correct permissions are set for adding users.
Jamieyes
12 Sep, 2024, 15:13

Ok, it would appear the error was being caused by a relation to another collection.

Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more