Kshitij Ingale
Kshitij Ingale

Reputation: 13

AppwriteException: User (role: guest) missing scope (account), not able to get account after creating a session

Throwing error on line account.get() Stuck on this from past 3 days can anyone help me please

Register account controller code :

const User = require('../model/User');
const { Client, Account } = require('appwrite');

exports.register = async (req, res) => {
    try {
        const { name, email, password } = req.body;

        // Validate data if exist
        if (!(name && email && password)) {
            return res.status(401).json({
                success: false,
                message: "All fields are required"
            })
        }

        // Check user already exist or not
        const doesExist = await User.findOne({ email })
        if (doesExist) {
            return res.status(401).json({
                success: false,
                message: "User already exists"
            })
        }

        //check if email is in correct format
        if (!(validateEmail(email))) {
            return res.status(401).json({
                success: false,
                message: "Invalid Email"
            })
        }

        // Save to DB
        const user = await User.create({
            name,
            email,
        })

        user.password = undefined

        const client = new Client()
            .setEndpoint('http://localhost/v1')
            .setProject(`${process.env.APPWRITE_PROJECT_ID}`);
        ;

        const account = new Account(client);

        await account.create(
            user._id.toString(),
            email,
            password,
            name
        );

        await account.get()

        return res.status(200).json({
            success: true,
            user,
        })

    } catch (error) {
        console.log(`Error :: register route :: ${error}`);
        return res.status(500).json({
            success: false,
            message: error.message
        })
    }
}

function validateEmail(email) {
    var re = /\S+@\S+\.\S+/;
    return re.test(email);
}

Login account controller code :

const User = require('../model/User');
const { Client, Account } = require('appwrite');

exports.login = async (req, res) => {
    try {
        const { email, password } = req.body;

        // Validate data
        if (!(email && password)) {
            res.status(401).send('All fields are required')
        }

        // check if user exist
        const user = await User.findOne({ email })

        // if user does not exist
        if (!user) {
            return res.status(401).json({
                success: false,
                message: "User does not exist"
            })
        }

        const client = new Client()
            .setEndpoint('http://localhost/v1')
            .setProject(`${process.env.APPWRITE_PROJECT_ID}`);
        ;

        const account = new Account(client);


        await account.createEmailSession(
            email,
            password,
        );

        await account.get()


        return res.status(200).json({
            success: true,
            user,
        })


    } catch (error) {
        console.log(`Error :: login route :: ${error}`);
        return res.status(500).json({
            success: false,
            message: error.message
        })
    }
}

I tried reading Appwrite docs to change permission for guest role, but didn't find anything for account.get(). It was for databases and files. And read some issues regarding this that i should use appwrite locally but even after install it locally, problem stays the same.

Upvotes: 1

Views: 8819

Answers (4)

Erhan Olgunelma
Erhan Olgunelma

Reputation: 31

It is actually normal to get this error. Check out my flutter code below.

  static Future<bool> checkAuthState() async {
    try {
      currentUser = await account.get();
      return true;
    } catch (e) {
      // Not logged in
      return false;
    }
  }

As you can see, you can use this to tell if the user is logged in or not. Also, if the user is logged in, you can access the user with the currentUser object.

Upvotes: 0

Pratik
Pratik

Reputation: 11

I was also getting same exception while using appwrite in flutter . It occurse when we triggere checksession() method and there is no user ("Current") available in appwrite auth tab .

solution - on getting exception navigate user to authentication screen to login or create account , once account is created , then when ever you trigger checksession() it will return result not exception.

Upvotes: 1

yash
yash

Reputation: 11

As per my understanding, you get this exception when you try to get the current user using the account.get() method but are logged in with any user. In other words, I interpret this exception as the user not logged in.

Upvotes: 1

Joe
Joe

Reputation: 56

You can make the session on the client-side. If you attempt to create a session server-side, it will result in a cookies header being returned, which the server will ignore and the session will be created, but the session information will not be stored anywhere.

Also, if I may ask, why do you need a server in the middle of your Client and backend?

Appwrite does a lot of heavy lifting for you as a Backend as a Service and hence you don't need to implement things yourself. If you point me to your use-case, maybe I can help you eliminate manual implementations.

Upvotes: 2

Related Questions