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?
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);
}
}
Recommended threads
- I'm experiencing a critical bug on Appwr...
Hey <@870607367597850624> team / support 👋 I'm experiencing a critical bug on Appwrite Cloud that's blocking my production Flutter app. I've already filed GitH...
- Bug: TOTP MFA verification always fails ...
*Bug: TOTP MFA verify always returns `user_invalid_token` (Cloud 1.8.1, Frankfurt)** Project ID: `68dd48440003e537d849` SDK: `appwrite@18.2.0` (also tested wit...
- SSL Certificate Issuance Failed
When we first deployed our site using appwrite and a custom domain everything was working, but it seems like the SSL certificate never got renewed. I tried dele...