adrianhajdin / healthcare

Build a healthcare platform that streamlines patient registration, appointment scheduling, and medical records, and learn to implement complex forms and SMS notifications.
https://jsmastery.pro
1.7k stars 393 forks source link

An error occurred while creating a new user: AppwriteException: User (role: guests) missing scope (users.write) #2

Open bharatpaliwal-169 opened 1 month ago

bharatpaliwal-169 commented 1 month ago
{
  code: 401,
  type: 'general_unauthorized_scope',
  response: {
    message: 'User (role: guests) missing scope (users.write)',
    code: 401,
    type: 'general_unauthorized_scope',
    version: '1.5.7'
  }
}

I am getting this message when we use createUser function

image

I seems that this code is not picking the correct value. Please help.

bharatpaliwal-169 commented 1 month ago

UPDATE: Yes the problem seems to be that these env variables are not picked up from .env.local file. Can anyone help with the possible fix for this issue

AkashGautam0001 commented 1 month ago

I am also facing this error. Please help us.

sujatagunale commented 1 month ago

@bharatpaliwal-169 @AkashGautam0001, did you console log and see if these values from the env file are picked up in the code?

From what I see, it seems to be a permission issue, which you can fix by going to that collection settings and setting read-write access to "any"

Screenshot 2024-07-09 at 11 03 05 PM
bharatpaliwal-169 commented 1 month ago

@bharatpaliwal-169 @AkashGautam0001, did you console log and see if these values from the env file are picked up in the code?

From what I see, it seems to be a permission issue, which you can fix by going to that collection settings and setting read-write access to "any" Screenshot 2024-07-09 at 11 03 05 PM

Hi @sujatagunale I confirm that I checked the permissions and no that was not the issue. The problem is with the environment variables which are not working with the code provided. I tried reinstall node_modules , restarts, making .env instead of .env.local the project only resumes when we hard code the key values in the string in the client endpoint func().

I still request you or anyone who can resolve this issue with nextjs.

AkashGautam0001 commented 1 month ago

Yes,i checked permission all are set "any read-write ... in appwrite" and also i did console log, values are also picked from .env.local correctly . when write this client .setEndpoint("https://cloud.appwrite.io/v1") .setProject("668b8d2223eg3s257d8ab0") //my env value - now random .setKey( "5fac4c444f265e62d60bea390b4748f4f4cdbfb27d222999947384hfjdd231c994f0e9fc4a584e17edb7ec17848dcb3f24c3d908f7d6148ceb83fa262dcf9c850fkdjfenrjhfj4kndjf37b2d86475e581956c759da52dbe86de6bfb00590b4202a001da4cd628e40acbea3d74dfaf53498eaaadade8c0f55700888fc50667336a897c8" //my env value - now random ); -- it works , works correctly

but but when i did this client .setEndpoint(process.env.NEXT_PUBLIC_ENDPOINT!) .setProject(process.env.NEXT_PUBLIC_PROJECT_ID!) .setKey(process.env.NEXT_PUBLIC_API_KEY!); it does not work does not work....


appwrite.config.ts `import * as sdk from "node-appwrite"; export const { API_KEY, PROJECT_ID, DATABASE_ID, PATIENT_COLLECTION_ID, DOCTOR_COLLECTION_ID, APPOINTMENT_COLLECTION_ID, NEXT_PUBLIC_BUCKET_ID, NEXT_PUBLIC_ENDPOINT, } = process.env;

console.log(API_KEY); // it give values of my api key

const client = new sdk.Client(); client .setEndpoint(process.env.NEXT_PUBLIC_ENDPOINT!) .setProject(process.env.NEXT_PUBLIC_PROJECT_ID!) .setKey(process.env.NEXT_PUBLIC_API_KEY!); export const databases = new sdk.Databases(client); export const storage = new sdk.Storage(client); export const messaging = new sdk.Messaging(client); export const users = new sdk.Users(client); `

this is code which i written in patient.actions.ts `"use server"; import { ID, Query } from "node-appwrite"; import { users } from "../appwrite.config"; import { parseStringify } from "../utils";

export const createUser = async (user: CreateUserParams) => { try { const newUser = await users.create( ID.unique(), user.email, user.phone, undefined, // Add password to parameters user.name );

    return parseStringify(newUser);
} catch (error: any) {
    if (error && error?.code === 409) {
        const existingUser = await users.list([
            Query.equal("email", [user.email]),
        ]);

        return existingUser?.users[0];
    } else if (error) {
        console.error(
            "Error creating user:",
            error,
            error.code,
            error.message
        ); // More specific logging
    }
}

}; `

code in PatientForm.ts `"use client";

import { zodResolver } from "@hookform/resolvers/zod"; import { useForm } from "react-hook-form"; import { z } from "zod"; import { Form } from "@/components/ui/form"; import CustomFormField from "../CustomFormField"; import SubmitButton from "../SubmitButton"; import { useState } from "react"; import { UserFormValidation } from "@/lib/validation"; import { useRouter } from "next/navigation"; import { createUser } from "@/lib/actions/patient.actions";

export enum FormFieldType { INPUT = "input", TEXTAREA = "textarea", PHONE_INPUT = "phoneInput", CHECKBOX = "checkbox", DATE_PICKER = "datePicker", SELECT = "select", SKELETON = "skeleton", }

function PatientForm() { const [isLoading, setIsLoading] = useState(false); const router = useRouter(); const form = useForm<z.infer>({ resolver: zodResolver(UserFormValidation), defaultValues: { name: "", email: "", phone: "", }, });

async function onSubmit({
    name,
    email,
    phone,
}: z.infer<typeof UserFormValidation>) {
    setIsLoading(true);
    try {
        const userData = { name, email, phone };
        console.log("userData", userData); //give values
        const user = await createUser(userData);
        console.log("user ", user); // give undefined
        if (user) router.push(`/patients/${user.$id}/register`);
    } catch (error) {
        console.log(error);
    }
    setIsLoading(false);
}

return (
    <Form {...form}>
        <form
            onSubmit={form.handleSubmit(onSubmit)}
            className="space-y-8"
        >
            <section className="mb-12 space-y-4">
                <h1 className="header">Hi there 👋</h1>
                <p className="text-dark-700">
                    Schedul your first appointment.
                </p>
            </section>
            <CustomFormField
                control={form.control}
                fieldType={FormFieldType.INPUT}
                name="name"
                label="Full Name"
                placeholder="John Doe"
                iconSrc="/assets/icons/user.svg"
                iconAlt="user"
            />
            <CustomFormField
                control={form.control}
                fieldType={FormFieldType.INPUT}
                name="email"
                label="Email"
                placeholder="johndoe@jsmastery.pro"
                iconSrc="/assets/icons/email.svg"
                iconAlt="email"
            />
            <CustomFormField
                control={form.control}
                fieldType={FormFieldType.PHONE_INPUT}
                name="phone"
                label="Phone number"
                placeholder="(555) 123-4567"
            />
            <SubmitButton isLoading={isLoading}>Get Started</SubmitButton>
        </form>
    </Form>
);

}

export default PatientForm; `

Please, Please help me to solve this issue , it give very long error

code: 404, type: '', response: { message: '<!DOCTYPE html> <link rel="preload" href="/fonts/poppins/poppins-v19-latin-500.woff2" as="font.............................................................................very long error

bharatpaliwal-169 commented 1 month ago

@AkashGautam0001 bro calm down , for now just simply hard code and move on.... there would be some solution to this problem in future.... maybe chatGPT can help try that.

nihalsheikh commented 2 weeks ago

Does anyone have an actual solution for this??

meoawww commented 1 week ago

Man I have been finding solution for this from past 5 days still couldn't find it.

meoawww commented 1 week ago

The error mainly occurs when we try to use account.get() when the user is not logged in.

Here's my svelte code:

onMount(async () => {
  if (browser) {
    try {
      const user = await account.get();
      userId = user.$id;
      await fetchDomains();
      await fetchTotalSold();
    } catch (error) {
      console.error('Error getting current user:', error);
      goto('/auth');
    } finally {
      isLoading = false;
    }
  }
});

The issue is not related to database permission it has to do with something else.

I tried testing it on different browsers(Brave, Chrome and Safari), it only works on edge(i.e authenticate user and redirect them success page but still the error shows on console).