Skip to content
Back

Unexpected Document Permissions issue running in functions

  • 0
  • Databases
  • Functions
  • Cloud
hoi66
28 Feb, 2025, 12:36

Hi, I’ve been struggling to figure out why my function isn’t behaving as expected. The function I’m building is supposed to create a user profile. Any user can call it and we’ll check if he doesn’t already have a user profile and the username he provided is unique. If it is, we’ll create a user document and give him permissions to it. For some reason the function fails at the last step (as in, creating the user document). This is the error I get:   Permissions must be one of: (any, guests)   I’ve read that this usually happens if a user wants to create a document and give himself full permissions, which would make sense, but I’m running on the server here with an API key. The dynamic function key has the full database scope and access to the projects users. The collection has document level security enabled. No permissions for anyone by default.   This is my code. Am I missing something here?

TypeScript
import { Client, Databases, ID, Permission, Query, Role } from 'node-appwrite';
 
export default async function ({ req, res, log }) {
  log(JSON.stringify(req));
  // Initialize Appwrite SDK
  const client = new Client()
    .setEndpoint(process.env.APPWRITE_FUNCTION_API_ENDPOINT)
    .setProject(process.env.APPWRITE_FUNCTION_PROJECT_ID)
    .setKey(process.env.APPWRITE_FUNCTION_API_KEY);
 
  const databases = new Databases(client);
 
  // Get user info from Appwrite function context
  const userId = req.headers['x-appwrite-user-id']; // User executing this function
  if (!userId) {
    return res.json({ error: 'Unauthorized request' }, 401);
  }
  log(`userId is present -> ${userId}`);
 
  // Parse request body
  const { username, avatarId } = req.bodyJson;
  if (!username) {
    return res.json({ error: 'Username is required' }, 400);
  }
  log(`username is present -> ${username}`);
 
  try {
    log('Checking user');
    const databaseId = process.env.DATABASE_ID;
    const collectionId = process.env.USER_COLLECTION;
 
    // Step 1: Check if user document already exists
    const existingUser = await databases.listDocuments(
      databaseId,
      collectionId,
      [Query.equal('userId', userId)]
    );
    if (existingUser.documents.length > 0) {
      return res.json({ error: 'User document already exists' }, 400);
    }
    log('User Profile does not already exist, proceeding...');
 
    // Step 2: Check if username is taken
    const existingUsername = await databases.listDocuments(
      databaseId,
      collectionId,
      [Query.equal('username', username)]
    );
    if (existingUsername.documents.length > 0) {
      return res.json({ error: 'Username is already taken' }, 400);
    }
    log('Username does not already exist, proceeding...');
 
    // Step 3: Create user document
    log(
      `Creating new user profile with data -> ${JSON.stringify({
        databaseId,
        collectionId,
        userId,
        username,
        avatarId: avatarId || null,
      })}`
    );
    const newUser = await databases.createDocument(
      databaseId,
      collectionId,
      ID.unique(),
      {
        userId,
        username,
        avatarId: avatarId || null, // Avatar is optional
      },
      [
        Permission.read(Role.user(userId)),
        Permission.update(Role.user(userId)),
        Permission.delete(Role.user(userId)),
      ]
    );
    log('User Profile created successfully.');
 
    return res.json({ message: 'User created successfully', user: newUser });
  } catch (error) {
    return res.json({ error: error.message }, 500);
  }
}
TL;DR
Developers encountering issue while running a function to create a user profile. Function fails when creating user document due to permissions error. Even with a dynamic function key with full database scope, error persists. Collection has document level security enabled. Missing 'Type' parameter in permissions causing the issue. Solution: Add "Permission.create(Role.user(userId))" to permissions array in "databases.createDocument" method.
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