Skip to content

Commit

Permalink
App CheckのtokenをAPI使用時に取得するように変更
Browse files Browse the repository at this point in the history
  • Loading branch information
MurakawaTakuya committed Jan 27, 2025
1 parent e618d2a commit 05647d4
Show file tree
Hide file tree
Showing 13 changed files with 229 additions and 55 deletions.
15 changes: 14 additions & 1 deletion src/Components/GoalModal/DeleteGoalModal.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"use client";
import { appCheckToken, functionsEndpoint } from "@/app/firebase";
import { functionsEndpoint } from "@/app/firebase";
import getAppCheckToken from "@/utils/getAppCheckToken";
import { useDeleteGoal } from "@/utils/ResultContext";
import DeleteOutlineIcon from "@mui/icons-material/DeleteOutline";
import { DialogContent, DialogTitle, Modal, ModalDialog } from "@mui/joy";
Expand All @@ -14,6 +15,18 @@ export default function DeleteGoalModal({ goalId }: { goalId: string }) {
const [open, setOpen] = useState(false);

const handleDelete = async () => {
const appCheckToken = await getAppCheckToken().catch((error) => {
showSnackBar({
message: error.message,
type: "warning",
});
return "";
});

if (!appCheckToken) {
return;
}

try {
const response = await fetch(`${functionsEndpoint}/goal/${goalId}`, {
method: "DELETE",
Expand Down
15 changes: 14 additions & 1 deletion src/Components/NameUpdate/NameUpdate.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"use client";
import { appCheckToken, auth, functionsEndpoint } from "@/app/firebase";
import { auth, functionsEndpoint } from "@/app/firebase";
import getAppCheckToken from "@/utils/getAppCheckToken";
import { useUser } from "@/utils/UserContext";
import {
DialogContent,
Expand Down Expand Up @@ -33,6 +34,18 @@ export default function NameUpdate() {
return;
}

const appCheckToken = await getAppCheckToken().catch((error) => {
showSnackBar({
message: error.message,
type: "warning",
});
return "";
});

if (!appCheckToken) {
return;
}

try {
const response = await fetch(
`${functionsEndpoint}/user/${user?.userId}`,
Expand Down
15 changes: 14 additions & 1 deletion src/Components/PostModal/DeletePostModal.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"use client";
import { appCheckToken, functionsEndpoint } from "@/app/firebase";
import { functionsEndpoint } from "@/app/firebase";
import getAppCheckToken from "@/utils/getAppCheckToken";
import { useDeletePost } from "@/utils/ResultContext";
import DeleteOutlineIcon from "@mui/icons-material/DeleteOutline";
import { DialogContent, DialogTitle, Modal, ModalDialog } from "@mui/joy";
Expand All @@ -20,6 +21,18 @@ export default function DeletePostModal({
const [open, setOpen] = useState(false);

const handleDelete = async () => {
const appCheckToken = await getAppCheckToken().catch((error) => {
showSnackBar({
message: error.message,
type: "warning",
});
return "";
});

if (!appCheckToken) {
return;
}

try {
const response = await fetch(`${functionsEndpoint}/post/${goalId}`, {
method: "DELETE",
Expand Down
41 changes: 1 addition & 40 deletions src/app/firebase.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,5 @@
import { showSnackBar } from "@/Components/SnackBar/SnackBar";
import { Analytics, getAnalytics } from "firebase/analytics";
import { initializeApp } from "firebase/app";
import {
getToken,
initializeAppCheck,
ReCaptchaV3Provider,
} from "firebase/app-check";
import {
browserLocalPersistence,
connectAuthEmulator,
Expand All @@ -31,44 +25,11 @@ export const storage = getStorage(app);
export const auth = getAuth(app);
let messaging: Messaging | null = null;
let analytics: Analytics | null = null;
let appCheckToken = "";

// クライアントサイドでのみ実行する初期化
if (typeof window !== "undefined") {
messaging = getMessaging(app);
analytics = getAnalytics(app);

// 開発環境ならApp Checkを使用しない
// ステージング環境でApp Checkのデバッグトークンを有効にする
if (process.env.NODE_ENV !== "development") {
if (process.env.NEXT_PUBLIC_IS_STAGING === "true") {
(
window as unknown as { FIREBASE_APPCHECK_DEBUG_TOKEN: boolean }
).FIREBASE_APPCHECK_DEBUG_TOKEN = true;
console.log("App Check Debug Token Enabled");
}
// App Checkの設定
const appCheck = initializeAppCheck(app, {
provider: new ReCaptchaV3Provider(
process.env.NEXT_PUBLIC_FIREBASE_RECAPTCHA_SITEKEY as string
),
isTokenAutoRefreshEnabled: true,
});

getToken(appCheck)
.then((token) => {
console.log("App Check: Success");
appCheckToken = token.token;
})
.catch((error) => {
console.log(error.message);
showSnackBar({
message:
"App Checkの初期化に失敗しました。debug tokenがサーバーに登録されていることを確認してください。",
type: "warning",
});
});
}
}

export const googleProvider = new GoogleAuthProvider();
Expand Down Expand Up @@ -99,5 +60,5 @@ if (process.env.NODE_ENV === "production") {
console.log("Functions: Emulator");
}

export { analytics, appCheckToken, functionsEndpoint, messaging };
export { analytics, functionsEndpoint, messaging };
console.log("firebaseConfig initialized");
16 changes: 15 additions & 1 deletion src/utils/API/Goal/createGoal.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { appCheckToken, functionsEndpoint } from "@/app/firebase";
import { functionsEndpoint } from "@/app/firebase";
import { showSnackBar } from "@/Components/SnackBar/SnackBar";
import { Goal } from "@/types/types";
import getAppCheckToken from "@/utils/getAppCheckToken";

/**
* Cloud FunctionsのAPIを呼び出して、目標をFirestoreに登録する
Expand All @@ -18,6 +20,18 @@ export const createGoal = async (postData: Goal) => {
throw new Error("too long comment");
}

const appCheckToken = await getAppCheckToken().catch((error) => {
showSnackBar({
message: error.message,
type: "warning",
});
return "";
});

if (!appCheckToken) {
return;
}

const response = await fetch(`${functionsEndpoint}/goal/`, {
method: "POST",
headers: {
Expand Down
16 changes: 15 additions & 1 deletion src/utils/API/Goal/updateGoal.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { appCheckToken, functionsEndpoint } from "@/app/firebase";
import { functionsEndpoint } from "@/app/firebase";
import { showSnackBar } from "@/Components/SnackBar/SnackBar";
import getAppCheckToken from "@/utils/getAppCheckToken";

/**
* Cloud FunctionsのAPIを呼び出して、目標を編集する
Expand Down Expand Up @@ -27,6 +29,18 @@ export const updateGoal = async (
throw new Error("too long comment");
}

const appCheckToken = await getAppCheckToken().catch((error) => {
showSnackBar({
message: error.message,
type: "warning",
});
return "";
});

if (!appCheckToken) {
return;
}

const response = await fetch(`${functionsEndpoint}/goal/${goalId}`, {
method: "PUT",
headers: {
Expand Down
16 changes: 15 additions & 1 deletion src/utils/API/Post/createPost.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { appCheckToken, functionsEndpoint } from "@/app/firebase";
import { functionsEndpoint } from "@/app/firebase";
import { showSnackBar } from "@/Components/SnackBar/SnackBar";
import { PostWithGoalId } from "@/types/types";
import getAppCheckToken from "@/utils/getAppCheckToken";

/**
* Cloud FunctionsのAPIを呼び出して、投稿をFirestoreに登録する
Expand All @@ -13,6 +15,18 @@ export const createPost = async (postData: PostWithGoalId) => {
throw new Error("too long comment");
}

const appCheckToken = await getAppCheckToken().catch((error) => {
showSnackBar({
message: error.message,
type: "warning",
});
return "";
});

if (!appCheckToken) {
return;
}

const response = await fetch(`${functionsEndpoint}/post/`, {
method: "POST",
headers: {
Expand Down
16 changes: 15 additions & 1 deletion src/utils/API/Reaction/updateReaction.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { appCheckToken, functionsEndpoint } from "@/app/firebase";
import { functionsEndpoint } from "@/app/firebase";
import { showSnackBar } from "@/Components/SnackBar/SnackBar";
import { ReactionTypeMap } from "@/types/types";
import getAppCheckToken from "@/utils/getAppCheckToken";

/**
* Cloud FunctionsのAPIを呼び出して、リアクションを更新する
Expand All @@ -15,6 +17,18 @@ export const updateReaction = async (
goalId: string,
reactionType: ReactionTypeMap | ""
) => {
const appCheckToken = await getAppCheckToken().catch((error) => {
showSnackBar({
message: error.message,
type: "warning",
});
return "";
});

if (!appCheckToken) {
return;
}

const response = await fetch(`${functionsEndpoint}/reaction/${goalId}`, {
method: "PUT",
headers: {
Expand Down
16 changes: 15 additions & 1 deletion src/utils/API/Result/fetchResult.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { appCheckToken, functionsEndpoint } from "@/app/firebase";
import { functionsEndpoint } from "@/app/firebase";
import { showSnackBar } from "@/Components/SnackBar/SnackBar";
import getAppCheckToken from "@/utils/getAppCheckToken";

/**
* Cloud FunctionsのAPIを呼び出して、結果の一覧を取得する
Expand Down Expand Up @@ -34,6 +36,18 @@ export const fetchResult = async ({
queryParams.append("limit", limit.toString());
}

const appCheckToken = await getAppCheckToken().catch((error) => {
showSnackBar({
message: error.message,
type: "warning",
});
return "";
});

if (!appCheckToken) {
return;
}

const response = await fetch(
`${functionsEndpoint}/result/${userId}?${queryParams.toString()}`,
{
Expand Down
16 changes: 15 additions & 1 deletion src/utils/API/User/fetchUser.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { appCheckToken, functionsEndpoint } from "@/app/firebase";
import { functionsEndpoint } from "@/app/firebase";
import { showSnackBar } from "@/Components/SnackBar/SnackBar";
import { User } from "@/types/types";
import getAppCheckToken from "@/utils/getAppCheckToken";

/**
* Cloud FunctionsのAPIを呼び出して、ユーザー情報をFirestoreから取得する
Expand All @@ -8,6 +10,18 @@ import { User } from "@/types/types";
* @return {*} {Promise<User>}
*/
export const fetchUserById = async (userId: string): Promise<User> => {
const appCheckToken = await getAppCheckToken().catch((error) => {
showSnackBar({
message: error.message,
type: "warning",
});
return "";
});

if (!appCheckToken) {
throw new Error("Failed to get App Check token");
}

const response = await fetch(`${functionsEndpoint}/user/id/${userId}`, {
method: "GET",
headers: {
Expand Down
15 changes: 14 additions & 1 deletion src/utils/Auth/signUpWithMail.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { appCheckToken, auth, functionsEndpoint } from "@/app/firebase";
import { auth, functionsEndpoint } from "@/app/firebase";
import { showSnackBar } from "@/Components/SnackBar/SnackBar";
import {
createUserWithEmailAndPassword,
sendEmailVerification,
updateProfile,
} from "firebase/auth";
import getAppCheckToken from "../getAppCheckToken";
import { updateUser } from "../UserContext";

/**
Expand All @@ -31,6 +32,18 @@ export const signUpWithMail = async (
console.error("Error updating user name:", profileUpdateError);
}

const appCheckToken = await getAppCheckToken().catch((error) => {
showSnackBar({
message: error.message,
type: "warning",
});
return "";
});

if (!appCheckToken) {
return;
}

// displayNameをFirestoreに登録
const response = await fetch(`${functionsEndpoint}/user/${user.uid}`, {
method: "PUT",
Expand Down
Loading

0 comments on commit 05647d4

Please sign in to comment.