Back

Unauthorized 401 on Login when User is Logged In

  • 0
  • Self Hosted
ZachHandley
27 May, 2024, 02:09

So this, idk. https://dailymatchup.com -- I updated the SDK, and thought that would fix it, but I'm getting a 401 from the user being... logged in currently. Which, sure, but for some reason my onMounted on the dashboard runs this in Vue

TypeScript
onMounted(async () => {
  const user = await $getUserAccountAsync();
  console.log("User", user);
  if (authInfo.value || user) {
    const loggedIn = connected.value;
    if (loggedIn) {
      console.log("Loaded and logged in, fetching articles and XML's");
      articles.value = await $fetchArticles();
      xmls.value = await $fetchXmls();
      articles.value.sort((a, b) => {
        return (
          new Date(b.$createdAt).getTime() - new Date(a.$createdAt).getTime()
        );
      });
      xmls.value.sort((a, b) => {
        return (
          new Date(b.$createdAt).getTime() - new Date(a.$createdAt).getTime()
        );
      });
      articlesLoaded.value = true;
      xmlsLoaded.value = true;
    } else {
      window.location.replace("/login");
      console.log("Not logged in");
    }
  } else {
    const user = await $getUserAccountAsync();
    if (!user) {
      window.location.replace("/login");
    }
  }
});

and that's redirecting to the login. Which also doesn't make any sense. How can someone be logged in and not at the same time??

so I checked the login function, but that just does

TypeScript
export const $login = async (email: string, password: string) => {
  console.log("Logging in...");
  let response, type;
  try {
    if (!$account) return { response: "No account", type: "error" };
    const loggedIn = await $account.createEmailPasswordSession(email, password);
    $connected.set(loggedIn);
    const user = await $account.get();
    $authInfo.set(user);
    // if (!user.emailVerification) {
    //   await $account.createVerification(`https://dailymatchup.com/dashboard`);
    // }
    const writer = await $getDocumentFiltered(COLLECTION_WRITERS, [
      Query.equal("user_id", user.$id),
    ]);
    if (writer) {
      $writerInfo.set(writer);
      $writer.set(WriterDataSchema.parse(writer));
    } else {
      console.error("Error getting writer in login");
    }
    response = "Logged in";
    type = "success";
  } catch (error: any) {
    response = error.message;
    type = "error";
  }
  return { response: response, type: type };
};

which I also checked, the writers collection does have any read permissions. So that leave... somewhere in the middle? I'm confused as to what is happening here to be quite frank.

TL;DR
Developers are experiencing a `401 Unauthorized` error during login, even when the user is logged in. The issue seems to be with the logic in the `onMounted` function in Vue. The problem might be related to how user authentication is handled. Ensure that the user session and authentication status are managed correctly to avoid unnecessary redirects to the login page when the user is already authenticated.
ZachHandley
27 May, 2024, 02:09
TypeScript
export const $getUserAccountAsync =
  async (): Promise<Models.User<Models.Preferences> | null> => {
    try {
      const user = await $account.get();
      $authInfo.set(user);
      if (!$writer.get()) {
        const writer = $writerInfo.get();
        if (!writer) {
          const writer = await $getUserWriterInfo(user.$id);
          if (writer) {
            $writerInfo.set(writer);
            $writer.set(WriterDataSchema.parse(writer));
          } else {
            console.error("Error getting writer in $getUserAccountAsync");
          }
        }
      }
      if (!$paymentProfile.get()) {
        const paymentProfile = await $getPaymentProfile(user.$id);
        if (paymentProfile) $paymentProfile.set(paymentProfile);
      }
      return user;
    } catch (error) {
      return null;
    }
  };
Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more