Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Error: AppwriteException: User (role: guests) missing scope (account)] #31

Open
shiva00007 opened this issue Jun 19, 2024 · 9 comments

Comments

@shiva00007
Copy link

how to fix this whenever i try to signup the page this error occur

@RoyAditya19
Copy link

I also encountered with the same issue.

@UnschooledGamer
Copy link

UnschooledGamer commented Jul 8, 2024

@shiva00007 to suppress the log/error just catch(use catch block) the error in account.get() function and either return null or console log it and return null, That easily suppresses the Error.

@shubhamprkash
Copy link

shubhamprkash commented Aug 5, 2024

@UnschooledGamer still getting the same error
kindly provide proper instructions for this issue if you know the solution.
Is there any way to reduce the time from shifting from sign-up screen to home screen?

@AwwdLabs
Copy link

AwwdLabs commented Aug 5, 2024

Do you have an example so I can try help?

@AwwdLabs
Copy link

AwwdLabs commented Aug 5, 2024

@UnschooledGamer still getting the same error kindly provide proper instructions for this issue if you know the solution. Is there any way to reduce the time from shifting from sign-up screen to home screen?

are you exporting your account from appwrite.js?

export const account = new Account(client) ?

@shubhamprkash
Copy link

shubhamprkash commented Aug 5, 2024

@UnschooledGamer still getting the same error kindly provide proper instructions for this issue if you know the solution. Is there any way to reduce the time from shifting from sign-up screen to home screen?

are you exporting your account from appwrite.js?

export const account = new Account(client) ?

yes, I have dismissed the error still the time it takes to shift from signup screen to home screen to high. And while trying to sign-in with same credentials getting the error "Property 'setUser' doesn't exist"

@AwwdLabs
Copy link

AwwdLabs commented Aug 5, 2024

Do you have an example so I can try help?

const client = new Client();

client .setEndpoint(appwriteConfig.endpoint) .setProject(appwriteConfig.projectID) .setPlatform(appwriteConfig.platform);

const account = new Account(client); const storage = new Storage(client); const avatars = new Avatars(client); const databases = new Databases(client);

// Register user export async function createUser(email, password, username) { try { const newAccount = await account.create( ID.unique(), email, password, username );

if (!newAccount) throw Error;

const avatarUrl = avatars.getInitials(username);

await signIn(email, password);

const newUser = await databases.createDocument(
  appwriteConfig.databaseID,
  appwriteConfig.userCollectionID,
  ID.unique(),
  {
    accountId: newAccount.$id,
    email: email,
    username: username,
    avatar: avatarUrl,
  }
);

return newUser;

} catch (error) { throw new Error(error); } }

// Sign In export async function signIn(email, password) { try { const session = await account.createEmailPasswordSession(email, password);

return session;

} catch (error) { // throw new Error(error); console.log(error); } }

// Get Account export async function getAccount() { try { if (!account) { console.log('Account object is not initialized'); } const currentAccount = await account.get();

return currentAccount;

} catch (error) { // throw new Error(error); console.log("appwrite file error",error); } }

// Get Current User export async function getCurrentUser() { try { const currentAccount = await getAccount(); if (!currentAccount) throw Error;

const currentUser = await databases.listDocuments(
  appwriteConfig.databaseID,
  appwriteConfig.userCollectionID,
  [Query.equal("accountId", currentAccount.$id)]
);

if (!currentUser) throw Error;

return currentUser.documents[0];

} catch (error) { console.log(error); return null; } }

// Sign Out export async function signOut() { try { const session = await account.deleteSession("current");

return session;

} catch (error) { throw new Error(error); } }

// Upload File export async function uploadFile(file, type) { if (!file) return;

const { mimeType, ...rest } = file; const asset = { type: mimeType, ...rest };

try { const uploadedFile = await storage.createFile( appwriteConfig.storageId, ID.unique(), asset );

const fileUrl = await getFilePreview(uploadedFile.$id, type);
return fileUrl;

} catch (error) { throw new Error(error); } }

// Get File Preview export async function getFilePreview(fileId, type) { let fileUrl;

try { if (type === "video") { fileUrl = storage.getFileView(appwriteConfig.storageId, fileId); } else if (type === "image") { fileUrl = storage.getFilePreview( appwriteConfig.storageId, fileId, 2000, 2000, "top", 100 ); } else { throw new Error("Invalid file type"); }

if (!fileUrl) throw Error;

return fileUrl;

} catch (error) { throw new Error(error); } }

// Create Video Post export async function createVideoPost(form) { try { const [thumbnailUrl, videoUrl] = await Promise.all([ uploadFile(form.thumbnail, "image"), uploadFile(form.video, "video"), ]);

const newPost = await databases.createDocument(
  appwriteConfig.databaseID,
  appwriteConfig.videoCollectionID,
  ID.unique(),
  {
    title: form.title,
    thumbnail: thumbnailUrl,
    video: videoUrl,
    prompt: form.prompt,
    creator: form.userId,
  }
);

return newPost;

} catch (error) { throw new Error(error); } }

// Get all video Posts export async function getAllPosts() { try { const posts = await databases.listDocuments( appwriteConfig.databaseID, appwriteConfig.videoCollectionID );

return posts.documents;

} catch (error) { throw new Error(error); } }

// Get video posts created by user export async function getUserPosts(userId) { try { const posts = await databases.listDocuments( appwriteConfig.databaseID, appwriteConfig.videoCollectionID, [Query.equal("creator", userId)] );

return posts.documents;

} catch (error) { throw new Error(error); } }

// Get video posts that matches search query export async function searchPosts(query) { try { const posts = await databases.listDocuments( appwriteConfig.databaseID, appwriteConfig.videoCollectionID, [Query.search("title", query)] );

if (!posts) throw new Error("Something went wrong");

return posts.documents;

} catch (error) { throw new Error(error); } }

// Get latest created video posts export async function getLatestPosts() { try { const posts = await databases.listDocuments( appwriteConfig.databaseID, appwriteConfig.videoCollectionID, [Query.orderDesc("$createdAt"), Query.limit(7)] );

return posts.documents;

} catch (error) { throw new Error(error); } }

IMG_2432

Hmmm 🤔

should there be a call for getting the account once create
const newAccount = await account.create(
ID.unique(),
email,
password,
username
);

if (!newAccount) throw Error;

const avatarUrl = avatars.getInitials(username);

await signIn(email, password);

const newUser = await databases.createDocument(
appwriteConfig.databaseID,
appwriteConfig.userCollectionID,
ID.unique(),
{
accountId: newAccount.$id,
email: email,
username: username,
avatar: avatarUrl,
}
);

return newUser;
} catch (error) {

====================

Like await account.get() and put that into a variable.

@AwwdLabs
Copy link

AwwdLabs commented Aug 5, 2024

When is this error happening? when you visit a page, when you fire a function like register or login etc?

When you create that account

const newAccount = await account.create( ID.unique(), email, password, username );

await login(email, password); i think this should come straight after then do the account.get() and put that account into the variable.

i think new account should be success or failure here

and then const avatarUrl = .... because you would have an account then kind of like this process

const register = async (formData) => { dispatch(setLoading(true)); try { const { email, password, username, firstName, lastName, dateOfBirth, country, } = formData;

        let userId = ID.unique();

        // Create the user account
        const newUser = await account.create(userId, email, password, username);

        // Log in the user immediately after registration
        await login(email, password);

        // Now that the user is logged in, we can create the documents with the correct permissions
        const permissions = [
            Permission.read(Role.any()),
            Permission.update(Role.user(userId)),
            Permission.delete(Role.user(userId))
        ];

        // Create a profile document with permissions
        await db.createDocument(
            process.env.NEXT_PUBLIC_APPWRITE_DATABASE_ID,
            process.env.NEXT_PUBLIC_APPWRITE_PROFILES,
            userId,
            {
                userId: userId,
                username: username,
                firstName: firstName,
                lastName: lastName,
                dateOfBirth: dateOfBirth,
                country: country,
                agreeToTerms: true,
            },
            permissions,
        );

        const unamePermissions = [
            Permission.read(Role.any()),
            Permission.update(Role.user(userId)),
            Permission.delete(Role.user(userId))
        ];

        // Create a handle document with permissions
        await db.createDocument(
            process.env.NEXT_PUBLIC_APPWRITE_DATABASE_ID,
            process.env.NEXT_PUBLIC_APPWRITE_HANDLES,
            userId,
            {
                userId: userId,
                handle: username
            },
            unamePermissions
        );

        console.log(newUser);
        dispatch(setUser(newUser));

        router.push('/dashboard');
        return newUser;

    } catch (error) {
        console.error("Registration failed", error);
        dispatch(setError(error.message || "Registration failed. Please try again."));
        throw error;
    } finally {
        dispatch(setLoading(false));
    }
};

When is this error happening? when you visit a page, when you fire a function like register or login etc?

When you create that account

const newAccount = await account.create(
ID.unique(),
email,
password,
username
);

await login(email, password); i think this should come straight after
then do the account.get() and put that account into the variable.

i think new account should be success or failure here

and then const avatarUrl = .... because you would have an account then kind of like this process

const register = async (formData) => {
dispatch(setLoading(true));
try {
const {
email,
password,
username,
firstName,
lastName,
dateOfBirth,
country,
} = formData;

    let userId = ID.unique();

    // Create the user account
    const newUser = await account.create(userId, email, password, username);

    // Log in the user immediately after registration
    await login(email, password);

    // Now that the user is logged in, we can create the documents with the correct permissions
    const permissions = [
        Permission.read(Role.any()),
        Permission.update(Role.user(userId)),
        Permission.delete(Role.user(userId))
    ];

    // Create a profile document with permissions
    await db.createDocument(
        process.env.NEXT_PUBLIC_APPWRITE_DATABASE_ID,
        process.env.NEXT_PUBLIC_APPWRITE_PROFILES,
        userId,
        {
            userId: userId,
            username: username,
            firstName: firstName,
            lastName: lastName,
            dateOfBirth: dateOfBirth,
            country: country,
            agreeToTerms: true,
        },
        permissions,
    );

    const unamePermissions = [
        Permission.read(Role.any()),
        Permission.update(Role.user(userId)),
        Permission.delete(Role.user(userId))
    ];

    // Create a handle document with permissions
    await db.createDocument(
        process.env.NEXT_PUBLIC_APPWRITE_DATABASE_ID,
        process.env.NEXT_PUBLIC_APPWRITE_HANDLES,
        userId,
        {
            userId: userId,
            handle: username
        },
        unamePermissions
    );

    console.log(newUser);
    dispatch(setUser(newUser));

    router.push('/dashboard');
    return newUser;

} catch (error) {
    console.error("Registration failed", error);
    dispatch(setError(error.message || "Registration failed. Please try again."));
    throw error;
} finally {
    dispatch(setLoading(false));
}

};

@shubhamprkash
Copy link

When is this error happening? when you visit a page, when you fire a function like register or login etc?
When you create that account
const newAccount = await account.create( ID.unique(), email, password, username );
await login(email, password); i think this should come straight after then do the account.get() and put that account into the variable.
i think new account should be success or failure here
and then const avatarUrl = .... because you would have an account then kind of like this process
const register = async (formData) => { dispatch(setLoading(true)); try { const { email, password, username, firstName, lastName, dateOfBirth, country, } = formData;

        let userId = ID.unique();

        // Create the user account
        const newUser = await account.create(userId, email, password, username);

        // Log in the user immediately after registration
        await login(email, password);

        // Now that the user is logged in, we can create the documents with the correct permissions
        const permissions = [
            Permission.read(Role.any()),
            Permission.update(Role.user(userId)),
            Permission.delete(Role.user(userId))
        ];

        // Create a profile document with permissions
        await db.createDocument(
            process.env.NEXT_PUBLIC_APPWRITE_DATABASE_ID,
            process.env.NEXT_PUBLIC_APPWRITE_PROFILES,
            userId,
            {
                userId: userId,
                username: username,
                firstName: firstName,
                lastName: lastName,
                dateOfBirth: dateOfBirth,
                country: country,
                agreeToTerms: true,
            },
            permissions,
        );

        const unamePermissions = [
            Permission.read(Role.any()),
            Permission.update(Role.user(userId)),
            Permission.delete(Role.user(userId))
        ];

        // Create a handle document with permissions
        await db.createDocument(
            process.env.NEXT_PUBLIC_APPWRITE_DATABASE_ID,
            process.env.NEXT_PUBLIC_APPWRITE_HANDLES,
            userId,
            {
                userId: userId,
                handle: username
            },
            unamePermissions
        );

        console.log(newUser);
        dispatch(setUser(newUser));

        router.push('/dashboard');
        return newUser;

    } catch (error) {
        console.error("Registration failed", error);
        dispatch(setError(error.message || "Registration failed. Please try again."));
        throw error;
    } finally {
        dispatch(setLoading(false));
    }
};

When is this error happening? when you visit a page, when you fire a function like register or login etc?

When you create that account

const newAccount = await account.create( ID.unique(), email, password, username );

await login(email, password); i think this should come straight after then do the account.get() and put that account into the variable.

i think new account should be success or failure here

and then const avatarUrl = .... because you would have an account then kind of like this process

const register = async (formData) => { dispatch(setLoading(true)); try { const { email, password, username, firstName, lastName, dateOfBirth, country, } = formData;

    let userId = ID.unique();

    // Create the user account
    const newUser = await account.create(userId, email, password, username);

    // Log in the user immediately after registration
    await login(email, password);

    // Now that the user is logged in, we can create the documents with the correct permissions
    const permissions = [
        Permission.read(Role.any()),
        Permission.update(Role.user(userId)),
        Permission.delete(Role.user(userId))
    ];

    // Create a profile document with permissions
    await db.createDocument(
        process.env.NEXT_PUBLIC_APPWRITE_DATABASE_ID,
        process.env.NEXT_PUBLIC_APPWRITE_PROFILES,
        userId,
        {
            userId: userId,
            username: username,
            firstName: firstName,
            lastName: lastName,
            dateOfBirth: dateOfBirth,
            country: country,
            agreeToTerms: true,
        },
        permissions,
    );

    const unamePermissions = [
        Permission.read(Role.any()),
        Permission.update(Role.user(userId)),
        Permission.delete(Role.user(userId))
    ];

    // Create a handle document with permissions
    await db.createDocument(
        process.env.NEXT_PUBLIC_APPWRITE_DATABASE_ID,
        process.env.NEXT_PUBLIC_APPWRITE_HANDLES,
        userId,
        {
            userId: userId,
            handle: username
        },
        unamePermissions
    );

    console.log(newUser);
    dispatch(setUser(newUser));

    router.push('/dashboard');
    return newUser;

} catch (error) {
    console.error("Registration failed", error);
    dispatch(setError(error.message || "Registration failed. Please try again."));
    throw error;
} finally {
    dispatch(setLoading(false));
}

};

Okay 👍🏻

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants