簡體   English   中英

Remix Auth - `destroySession` 返回 [object Promise] 而不是清除 session

[英]Remix Auth - `destroySession` returning [object Promise] instead of clearing the session

我正在嘗試在 Remix 應用程序中實施用戶身份驗證,並且一直在兜圈子試圖弄清楚為什么銷毀 session 會返回[object Promise]而不是清除它。

在此處輸入圖像描述

我的auth.server.js文件包含管理與創建、檢索和銷毀 Session Cookie 以及 function login相關的任何功能。

import { hash, compare } from "bcryptjs";
import { prisma } from "./database.server";
import { createCookieSessionStorage, redirect } from "@remix-run/node";

export const sessionStorage = createCookieSessionStorage({
  cookie: {
    secure: process.env.NODE_ENV === "production",
    path: "/",
    secrets: [process.env.SESSION_SECRET],
    sameSite: "lax",
    maxAge: 30 * 24 * 60 * 60, // 30 days
    httpOnly: true
  }
});

async function createUserSession(userId, redirectPath) {
  const session = await sessionStorage.getSession();
  session.set("userId", userId);
  return redirect(redirectPath, {
    headers: {
      "Set-Cookie": await sessionStorage.commitSession(session)
    }
  });
}

export async function getUserFromSession(request) {
  const session = await sessionStorage.getSession(
    request.headers.get("Cookie")
  );

  const userId = session.get("userId");
  return userId ? userId : null;
}

export function destroyUserSession(request) {
  const session = sessionStorage.getSession(request.headers.get("Cookie"));

  return redirect("/", {
    headers: {
      "Set-Cookie": sessionStorage.destroySession(session)
    }
  });
}

export async function login({ email, password }) {
  const existingUser = await prisma.user.findFirst({ where: { email } });
  if (!existingUser) {
    return throwError(
      "Could not log you in, please check provided email.",
      401
    );
  }

  const passwordCorrect = await compare(password, existingUser.password);
  if (!passwordCorrect) {
    return throwError(
      "Could not log you in, please check provided password.",
      401
    );
  }

  return createUserSession(existingUser.id, "/");
}

function throwError(text, code) {
  const error = new Error(text);
  error.status = code; // authentication error code
  throw error; // this triggers ErrorBoundary, as it's not an error response
}

我的logout function 位於/routes文件夾內的一個單獨的.js文件中。

import { json } from "@remix-run/node";
import { destroyUserSession } from "~/data/auth.server";

export function action({ request }) {
  if (request.method !== "POST") {
    throw json({ message: "Invalid request method" }, { status: 400 });
  }

  return destroyUserSession(request);
}

最后, Logout按鈕位於導航欄內並包含在<Form>元素中。

<Form method="post" action="/logout">
   <button type="submit">Logout</button>
</Form>

解決了
我以某種方式能夠通過將注銷 function 移動到auth.server.js並將以下內容留在logout.js路由中來解決它:

import { redirect } from "@remix-run/node";
import { logout } from "~/data/auth.server";

export const action = ({ request }) => logout(request);
export const loader = () => redirect("/auth");

session 函數都是async的。 你有[object Promise]的原因是你直接返回 promise 。 您需要使用await

export function destroyUserSession(request) {
  const session = sessionStorage.getSession(request.headers.get("Cookie"));

  return redirect("/", {
    headers: {
      // use await on session functions
      "Set-Cookie": await sessionStorage.destroySession(session)
    }
  });
}

PS 這是 TypeScript 的好處之一。它會告訴您標頭需要一個字符串值,並且不允許 Promise 返回。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM