表单策略 (FormStrategy)

一种用于处理任何表单的 Remix Auth 策略。

支持的运行时

运行时 是否支持
Node.js
Cloudflare

如何使用

此策略在验证回调中返回请求的 FormData 实例以及来自 action 的上下文(如果已定义)。

这允许您使用表单中的任何字段,并使用您想要的名称,因此您不限于仅使用用户名+密码或邮箱+密码,如果您需要第三个字段,也可以使用它。

首先,安装策略和 Remix Auth。

$ npm install remix-auth remix-auth-form

然后,创建一个 Authenticator 实例。

import { Authenticator } from "remix-auth";
import { sessionStorage } from "~/services/session.server";
import { User, findOrCreateUser } from "~/models/user";

export let authenticator = new Authenticator<User>(sessionStorage);

您可以告诉验证器使用 FormStrategy。

import { FormStrategy } from "remix-auth-form";

// The rest of the code above here...

authenticator.use(
  new FormStrategy(async ({ form, context }) => {
    // Here you can use `form` to access and input values from the form.
    // and also use `context` to access more things from the server
    let username = form.get("username"); // or email... etc
    let password = form.get("password");

    // You can validate the inputs however you want
    invariant(typeof username === "string", "username must be a string");
    invariant(username.length > 0, "username must not be empty");

    invariant(typeof password === "string", "password must be a string");
    invariant(password.length > 0, "password must not be empty");

    // And if you have a password you should hash it
    let hashedPassword = await hash(password);

    // And finally, you can find, or create, the user
    let user = await findOrCreateUser(username, hashedPassword);

    // And return the user as the Authenticator expects it
    return user;
  }),
);

为了验证用户,您可以在 action 函数内部使用以下代码

export async function action({ context, request }: ActionArgs) {
  return await authenticator.authenticate("form", request, {
    successRedirect: "/",
    failureRedirect: "/login",
    context, // optional
  });
}