FormStrategy
一個用於處理任何表單的 Remix Auth 策略。
支援的執行環境
執行環境 | 是否支援 |
---|---|
Node.js | ✅ |
Cloudflare | ✅ |
如何使用
此策略會在驗證函式中回傳請求的 FormData 實例以及來自 action 的請求。
這讓您可以使用表單中的任何欄位及其所需的名稱,因此您不僅限於 username+password 或 email+password,如果需要第三個欄位也可以使用。
首先,安裝此策略和 Remix Auth。
$ npm install remix-auth remix-auth-form
然後,建立一個 Authenticator 實例。
import { Authenticator } from "remix-auth";
import { User, findOrCreateUser } from "~/models/user";
export let authenticator = new Authenticator<User>();
您可以告訴驗證器使用 FormStrategy。
import { FormStrategy } from "remix-auth-form";
// The rest of the code above here...
authenticator.use(
new FormStrategy(async ({ form, request }) => {
// Here you can use `form` to access and input values from the form.
// and also use `request` to access more data
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({ request }: Route.ActionArgs) {
let user = await authenticator.authenticate("form", request);
// Now you have the user object with the data you returned in the verify function
}
一旦您取得策略驗證函式回傳的 user
物件,您可以對該資訊執行任何操作。這可以是將使用者儲存在 session 中、在資料庫中建立新使用者、將帳戶連結到資料庫中現有的使用者等等。