adrianhajdin / aora

Build your first mobile application
https://jsmastery.pro
1.68k stars 310 forks source link

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

Open shiva00007 opened 3 months ago

shiva00007 commented 3 months ago

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

RoyAditya19 commented 3 months ago

I also encountered with the same issue.

UnschooledGamer commented 2 months ago

@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 commented 2 months ago

@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 commented 2 months ago

Do you have an example so I can try help?

AwwdLabs commented 2 months ago

@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 commented 2 months ago

@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 commented 2 months ago

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 commented 2 months ago

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 commented 2 months ago

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 👍🏻