Skip to content
This repository has been archived by the owner on Dec 12, 2023. It is now read-only.

Commit

Permalink
Merge pull request #64 from mct-joken/feat/auth-check-accounts
Browse files Browse the repository at this point in the history
feat: `accounts`テーブルに存在するアカウントのみがログインできるようにする
  • Loading branch information
kiharu3112 authored Sep 18, 2023
2 parents 0263ead + 9c9764a commit fdf72b1
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 8 deletions.
47 changes: 39 additions & 8 deletions app/hooks/useAuth.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,49 @@
import { User, getAuth } from "firebase/auth";
import { Unsubscribe, User, getAuth } from "firebase/auth";
import { useEffect, useState } from "react";

export const useAuth = (): { ready: boolean; user: User | null } => {
/**
* 現在の認証状態をリッスンして返すフック
* @param enableVerification 存在するAccountのログインのみ受け付けるか
* @returns \{`ready`: Firebase authの初期化が完了したか, `user`: ログイン中のユーザ \}
*/
export const useAuth = (
enableVerification: boolean = false
): { ready: boolean; user: User | null } => {
const auth = getAuth();
const [ready, setReady] = useState(false);
const [user, setUser] = useState<User | null>(null);

const verifyAuth = async (user: User | null) => {
if (user == null) {
return;
}
if (user.email == null) {
throw new Error("Authentication rejected");
}

const form = new FormData();
form.append("email", user.email);
const response = await fetch("/api/v1/account/verify", {
method: "POST",
body: form,
});
const data = (await response.json()) as { valid: boolean };
if (!data.valid) {
throw new Error("Authentication rejected");
}
};

useEffect(() => {
(async () => {
await auth.authStateReady();
setReady(true);
})();
return auth.onAuthStateChanged(setUser);
}, [auth]);
const unsubscribes: Unsubscribe[] = [];
auth.authStateReady().then(() => setReady(true));
unsubscribes.push(auth.onAuthStateChanged(setUser));
if (enableVerification) {
unsubscribes.push(auth.beforeAuthStateChanged(verifyAuth));
}
return () => {
unsubscribes.forEach((unsubscribe) => unsubscribe());
};
}, [auth, enableVerification]);

return { ready, user };
};
17 changes: 17 additions & 0 deletions app/routes/api.v1.account.verify.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { ActionArgs, json } from "@remix-run/cloudflare";
import { getAccountByEmail } from "~/models/account.server";

export const action = async ({ request, context }: ActionArgs) => {
const formData = await request.formData();
const email = formData.get("email");
if (typeof email !== "string") {
return json({}, 400);
}

const account = await getAccountByEmail(context, email);
if (account == null) {
return json({ valid: false });
}

return json({ valid: true });
};

0 comments on commit fdf72b1

Please sign in to comment.